index.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092
  1. <?php
  2. /**
  3. * HSDN Looking Glass version 1.2.5b
  4. *
  5. * General Features:
  6. * - Supports the Telnet and SSH (through Putty/plink)
  7. * - Supports the Cisco, MikroTik v5 and v6, Quagga (Zebra) and JunOS routers
  8. * - Supports the IPv4 and IPv6 protocols
  9. * - Automatic conversion IPs to subnets using RADb (for MikroTik)
  10. * - Drawing graph of BGP AS pathes using GraphViz toolkit
  11. * - Works on php 5.2.0 and above
  12. *
  13. * System Requirements:
  14. * - php version 5.2.0 and above with Sockets and Filter
  15. * http://www.php.net/
  16. * - Putty for SSH connections usign `plink' command
  17. * http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
  18. * - GraphViz toolkit for drawing BGP pathes graph
  19. * http://www.graphviz.org/
  20. * - php pear package Image_GraphViz
  21. * http://pear.php.net/package/Image_GraphViz
  22. *
  23. *
  24. * Copyright (C) 2012-2017 Information Networks Ltd. <info@hsdn.org>
  25. * http://www.hsdn.org/
  26. *
  27. * Copyright (C) 2000-2002 Cougar <cougar@random.ee>
  28. * http://www.version6.net/
  29. *
  30. * Copyright (C) 2014 Regional Networks Ltd. <info@regnets.ru>
  31. * http://www.regnets.ru/
  32. *
  33. * This program is free software: you can redistribute it and/or modify
  34. * it under the terms of the GNU General Public License as published by
  35. * the Free Software Foundation, either version 3 of the License, or
  36. * (at your option) any later version.
  37. *
  38. * This program is distributed in the hope that it will be useful,
  39. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  40. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  41. * GNU General Public License for more details.
  42. *
  43. * You should have received a copy of the GNU General Public License
  44. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  45. */
  46. // ------------------------------------------------------------------------
  47. // BEGIN CONFIGURATIONS
  48. // ------------------------------------------------------------------------
  49. /*
  50. * Your own AS number
  51. */
  52. $_CONFIG['asn'] = '56727';
  53. /*
  54. * Your own company name
  55. */
  56. $_CONFIG['company'] = 'Information Networks Ltd.';
  57. /*
  58. * Your logo URL (or FALSE)
  59. */
  60. $_CONFIG['logo'] = 'lg_logo.gif';
  61. /*
  62. * Main style color
  63. */
  64. $_CONFIG['color'] = '#3366cc';
  65. /*
  66. * Putty `plink' command path (for SSH connections)
  67. */
  68. $_CONFIG['plink'] = '/usr/local/bin/plink';
  69. /*
  70. * URL address of the IP whois service
  71. */
  72. $_CONFIG['ipwhois'] = 'http://noc.hsdn.org/whois/';
  73. /*
  74. * URL address of the AS whois service
  75. */
  76. $_CONFIG['aswhois'] = 'http://noc.hsdn.org/aswhois/';
  77. /**
  78. * Router nodes
  79. *
  80. * Parameters:
  81. * url - URL address in format: [ssh|telnet]://[login]:[password]@[host]:[port]
  82. * pingtraceurl - URL address for ping and traceroute tools (or FALSE)
  83. * description - Node description
  84. * group - Node group name (of FALSE)
  85. * ipv6 - Node is supports IPv6 (TRUE/FALSE)
  86. * os - Node OS (ios, mikrotik, quagga, junos)
  87. */
  88. $_CONFIG['routers'] = array
  89. (
  90. /*'saratov-br1' => array
  91. (
  92. 'url' => 'telnet://rviews@91.226.136.130:23',
  93. 'pingtraceurl' => 'telnet://rviews:Rviews@91.226.136.130:2300',
  94. 'description' => 'Saratov (RU), BR1',
  95. 'group' => 'AS56727',
  96. 'ipv6' => TRUE,
  97. 'os' => 'quagga',
  98. ),*/
  99. 'saratov-br1' => array
  100. (
  101. 'url' => 'telnet://91.226.136.129:23',
  102. 'pingtraceurl' => FALSE,
  103. 'description' => 'Saratov (RU), BR1',
  104. 'group' => 'AS56727',
  105. 'ipv6' => TRUE,
  106. 'os' => 'ios',
  107. ),
  108. 'rs' => array
  109. (
  110. 'url' => 'telnet://91.226.136.180:23',
  111. 'pingtraceurl' => FALSE,
  112. 'description' => 'Route Server',
  113. 'group' => 'AS56727',
  114. 'ipv6' => TRUE,
  115. 'os' => 'ios',
  116. ),
  117. 'kemerovo-br1' => array
  118. (
  119. 'url' => 'telnet://46.8.40.1:23',
  120. 'pingtraceurl' => FALSE,
  121. 'description' => 'Kemerovo (RU), BR1',
  122. 'group' => 'AS60894',
  123. 'ipv6' => TRUE,
  124. 'os' => 'ios',
  125. ),
  126. /*'test' => array
  127. (
  128. 'url' => 'telnet://rviews:rviews@route-server.ip.att.net',
  129. 'pingtraceurl' => FALSE,
  130. 'description' => 'AT&T test',
  131. 'group' => '',
  132. 'ipv6' => FALSE,
  133. 'os' => 'junos',
  134. ),*/
  135. );
  136. // ------------------------------------------------------------------------
  137. // END OF CONFIGURATIONS
  138. // ------------------------------------------------------------------------
  139. // ------------------------------------------------------------------------
  140. // Do not edit below this line, unless you fully understand the implications.
  141. // ------------------------------------------------------------------------
  142. //error_reporting(0);
  143. @ob_end_flush();
  144. $router = isset($_REQUEST['router']) ? trim($_REQUEST['router']) : FALSE;
  145. $protocol = isset($_REQUEST['protocol']) ? trim($_REQUEST['protocol']) : FALSE;
  146. $command = isset($_REQUEST['command']) ? trim($_REQUEST['command']) : FALSE;
  147. $query = isset($_REQUEST['query']) ? trim($_REQUEST['query']) : FALSE;
  148. if ($command != 'graph' OR !isset($_REQUEST['render']) OR !isset($_CONFIG['routers'][$router]))
  149. {
  150. // HTML header
  151. ?>
  152. <!DOCTYPE html>
  153. <html lang="en">
  154. <head>
  155. <title>AS<?php print $_CONFIG['asn'] ?> Looking Glass</title>
  156. <meta charset="utf-8">
  157. <link rel="shortcut icon" href="favicon.ico">
  158. <style type="text/css">
  159. <!--
  160. body { font: 14px normal Arial, Helvetica, sans-serif; margin: 30px 10%; color: #000; background: #fff; }
  161. h2 { font-size: 24px; font-weight: normal; }
  162. form { margin: 0; padding: 0 0 15px 0; }
  163. p, object { margin: 0; padding: 0 0 15px 0; }
  164. hr { margin: 0 0 15px 0; border: none; color: #000; background-color: #000; height: 1px; }
  165. a:link, a:visited { color: <?php print $_CONFIG['color'] ?>; }
  166. a:hover { color: #ccc; }
  167. table { border: 0; }
  168. table th { background: <?php print $_CONFIG['color'] ?>; color: #fff; white-space: nowrap; font-size: 14px; text-align: center; }
  169. .form { margin: auto; text-align: left; background: #efefef; border: 5px solid #efefef; }
  170. .center { text-align: center; }
  171. .error { color: red; font-weight: bold; }
  172. .warning { color: blue; font-weight: bold; }
  173. .legend { font-size: 12px; margin: auto; }
  174. //-->
  175. </style>
  176. <script type="text/javascript">
  177. <!--
  178. function load()
  179. {
  180. var loading = document.getElementById('loading');
  181. if (loading !== null)
  182. {
  183. loading.style.display = 'none';
  184. }
  185. }
  186. //-->
  187. </script>
  188. </head>
  189. <body onload="load();">
  190. <?php if (isset($_CONFIG['logo']) AND $_CONFIG['logo']): ?>
  191. <div class="center"><a href="?"><img src="<?php print $_CONFIG['logo'] ?>" border="0" alt="lg"></a></div>
  192. <?php endif ?>
  193. <div class="center"><h2>AS<?php print $_CONFIG['asn'] ?> Looking Glass</h2></div>
  194. <hr>
  195. <?php
  196. flush();
  197. }
  198. $queries = array
  199. (
  200. 'ios' => array
  201. (
  202. 'ipv4' => array
  203. (
  204. 'bgp' => 'show ip bgp %s',
  205. 'advertised-routes' => 'show ip bgp neighbors %s advertised-routes',
  206. 'received-routes' => 'show ip bgp neighbors %s received-routes',
  207. 'routes' => 'show ip bgp neighbors %s routes',
  208. 'summary' => 'show ip bgp summary',
  209. 'ping' => 'ping ip %s',
  210. 'trace' => 'traceroute ip %s'
  211. ),
  212. 'ipv6' => array
  213. (
  214. 'bgp' => 'show bgp ipv6 unicast %s',
  215. 'advertised-routes' => 'show bgp ipv6 neighbors %s advertised-routes',
  216. 'received-routes' => 'show bgp ipv6 neighbors %s received-routes',
  217. 'routes' => 'show bgp ipv6 neighbors %s routes',
  218. 'summary' => 'show bgp ipv6 unicast summary',
  219. 'ping' => 'ping ipv6 %s',
  220. 'trace' => 'traceroute ipv6 %s'
  221. )
  222. ),
  223. 'quagga' => array
  224. (
  225. 'ipv4' => array
  226. (
  227. 'bgp' => 'show ip bgp %s',
  228. 'advertised-routes' => 'show ip bgp neighbors %s advertised-routes',
  229. 'received-routes' => 'show ip bgp neighbors %s received-routes',
  230. 'routes' => 'show ip bgp neighbors %s routes',
  231. 'summary' => 'show ip bgp summary',
  232. 'ping' => 'ping -t 5 -c 5 %s',
  233. 'trace' => 'traceroute -Iaw 1 %s',
  234. ),
  235. 'ipv6' => array
  236. (
  237. 'bgp' => 'show ipv6 bgp %s',
  238. 'advertised-routes' => 'show ipv6 bgp neighbors %s advertised-routes',
  239. 'received-routes' => 'show ipv6 bgp neighbors %s received-routes',
  240. 'routes' => 'show ipv6 bgp neighbors %s routes',
  241. 'summary' => 'show ipv6 bgp summary',
  242. 'ping' => 'ping6 -c 5 %s',
  243. 'trace' => 'traceroute6 -Ialw 1 %s',
  244. )
  245. ),
  246. 'mikrotik' => array
  247. (
  248. 'ipv4' => array
  249. (
  250. 'bgp' => '/ip route print detail where dst-address=%s',
  251. 'advertised-routes' => '/routing bgp advertisements print peer=%s',
  252. 'routes' => '/ip route print where gateway=%s',
  253. 'summary' => '/routing bgp peer print status where address-families=ip',
  254. 'ping' => '/ping count=5 size=56 %s',
  255. 'trace' => '/tool traceroute %s size=60 count=1',
  256. ),
  257. 'ipv6' => array
  258. (
  259. 'bgp' => '/ipv6 route print detail where dst-address=%s',
  260. 'advertised-routes' => '/routing bgp advertisements print peer=%s',
  261. 'routes' => '/ipv6 route print where gateway=%s',
  262. 'summary' => '/routing bgp peer print status where address-families=ipv6',
  263. 'ping' => '/ping count=5 size=56 %s',
  264. 'trace' => '/tool traceroute %s size=60 count=1',
  265. )
  266. ),
  267. 'junos' => array
  268. (
  269. 'ipv4' => array
  270. (
  271. 'bgp' => 'show bgp %s',
  272. 'advertised-routes' => 'show route advertising-protocol bgp %s',
  273. 'routes' => 'show route receive-protocol bgp %s active-path',
  274. 'summary' => 'show bgp summary',
  275. 'ping' => 'ping count 5 %s',
  276. 'trace' => 'traceroute %s as-number-lookup',
  277. ),
  278. 'ipv6' => array
  279. (
  280. 'bgp' => 'show bgp %s',
  281. 'advertised-routes' => 'show route advertising-protocol bgp %s',
  282. 'routes' => 'show route receive-protocol bgp %s active-path',
  283. 'summary' => 'show bgp summary',
  284. 'ping' => 'ping count 5 %s',
  285. 'trace' => 'traceroute %s',
  286. )
  287. ),
  288. );
  289. if (isset($_CONFIG['routers'][$router]) AND
  290. isset($queries[$_CONFIG['routers'][$router]['os']][$protocol]) AND
  291. (isset($queries[$_CONFIG['routers'][$router]['os']][$protocol][$command]) OR $command == 'graph'))
  292. {
  293. if ($protocol == 'ipv6' AND (!isset($_CONFIG['routers'][$router]['ipv6']) OR
  294. $_CONFIG['routers'][$router]['ipv6'] !== TRUE))
  295. {
  296. $protocol = 'ipv4';
  297. print '<div class="center"><p class="warning">The router does not support IPv6. Using IPv4.</p></div>';
  298. print '<hr>';
  299. }
  300. $url = $_CONFIG['routers'][$router]['url'];
  301. if (($command == 'ping' OR $command == 'trace') AND
  302. isset($_CONFIG['routers'][$router]['pingtraceurl']) AND
  303. $_CONFIG['routers'][$router]['pingtraceurl'] != FALSE)
  304. {
  305. $url = $_CONFIG['routers'][$router]['pingtraceurl'];
  306. }
  307. $url = @parse_url($url);
  308. $os = $_CONFIG['routers'][$router]['os'];
  309. if ($command == 'graph' AND isset($queries[$os][$protocol]['bgp']))
  310. {
  311. $exec = $queries[$os][$protocol]['bgp'];
  312. }
  313. else
  314. {
  315. $exec = $queries[$os][$protocol][$command];
  316. }
  317. if (strpos($exec, '%s') !== FALSE)
  318. {
  319. if (preg_match('/^.[.a-z0-9_-]+\.[a-z]+$/i', $query))
  320. {
  321. if ($command != 'advertised-routes')
  322. {
  323. $query = get_host($query);
  324. }
  325. }
  326. if ($query AND ($command == 'bgp' OR $command == 'graph') AND ($os == 'mikrotik' OR ($protocol == 'ipv6' AND $os == 'ios')))
  327. {
  328. if (strpos($query, '/') === FALSE AND $radb = get_radb($query))
  329. {
  330. $route = FALSE;
  331. if (strpos($query, ':') AND isset($radb['route6']))
  332. {
  333. $route = $radb['route6'];
  334. }
  335. else if (isset($radb['route']))
  336. {
  337. $route = $radb['route'];
  338. }
  339. if ($route)
  340. {
  341. if ($command != 'graph')
  342. {
  343. print '<p>Address <b>'.$query.'</b> is converted to a subnet <b>'.$route.'</b> using the <a href="http://radb.net/" target="_blank">Merit RADb</a></p>';
  344. }
  345. $query = $route;
  346. }
  347. }
  348. }
  349. $exec = sprintf($exec, escapeshellcmd($query));
  350. if (!$query)
  351. {
  352. $exec = FALSE;
  353. if ($query === FALSE)
  354. {
  355. print '<div class="center"><p class="error">Can\'t resolve the hostname.</p></div>';
  356. }
  357. else
  358. {
  359. print '<div class="center"><p class="error">Parameter missing.</p></div>';
  360. }
  361. }
  362. }
  363. else if ($query != '' AND $command != 'graph')
  364. {
  365. print '<div class="center"><p class="warning">No parameter needed.</p></div>';
  366. print '<hr>';
  367. }
  368. if ($exec)
  369. {
  370. if ($os == 'junos')
  371. {
  372. // @see JunOS Routing Table Names (http://www.net-gyver.com/?p=602)
  373. $table = ($protocol == 'ipv6') ? 'inet6.0' : 'inet.0';
  374. if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+)$/", $exec, $exec_exp))
  375. {
  376. $exec = 'show bgp neighbor '.$exec_exp[1];
  377. }
  378. else if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+) ro\w*$/", $exec, $exec_exp))
  379. {
  380. $exec = 'show route receive-protocol bgp '.$exec_exp[1];
  381. }
  382. else if (preg_match("/^show bgp neighbors ([\d\.A-Fa-f:]+) routes all$/", $exec, $exec_exp))
  383. {
  384. $exec = 'show route receive-protocol bgp '.$exec_exp[1].' all';
  385. }
  386. else if (preg_match("/^show bgp neighbors ([\d\.A-Fa-f:]+) routes damping suppressed$/", $exec, $exec_exp))
  387. {
  388. $exec = 'show route receive-protocol bgp '.$exec_exp[1].' damping suppressed';
  389. }
  390. else if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+) advertised-routes ([\d\.A-Fa-f:\/]+)$/", $exec, $exec_exp))
  391. {
  392. $exec = 'show route advertising-protocol bgp '.$exec_exp[1].' '.$exec_exp[2].' exact detail';
  393. }
  394. else if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+) receive-protocol ([\d\.A-Fa-f:\/]+)$/", $exec, $exec_exp))
  395. {
  396. $exec = 'show route receive-protocol bgp '.$exec_exp[1].' '.$exec_exp[2].' exact detail';
  397. }
  398. else if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+) a[\w\-]*$/", $exec, $exec_exp))
  399. {
  400. $exec = 'show route advertising-protocol bgp '.$exec_exp[1];
  401. }
  402. else if (preg_match("/^show bgp\s+([\d\.A-Fa-f:]+\/\d+)$/", $exec, $exec_exp))
  403. {
  404. $exec = 'show route protocol bgp '.$exec_exp[1].' terse exact';
  405. }
  406. else if (preg_match("/^show bgp\s+([\d\.A-Fa-f:]+)$/", $exec, $exec_exp))
  407. {
  408. $exec = 'show route protocol bgp '.$exec_exp[1].' table '.$table;
  409. }
  410. else if (preg_match("/^show bgp\s+([\d\.A-Fa-f:\/]+) exact$/", $exec, $exec_exp))
  411. {
  412. $exec = 'show route protocol bgp '.$exec_exp[1].' exact detail all';
  413. }
  414. else if (preg_match("/^show bgp re\s+(.*)$/", $exec, $exec_exp))
  415. {
  416. $re = $exec_exp[1];
  417. if (!preg_match('/^\^/', $re))
  418. {
  419. $re = "^.*".$re;
  420. }
  421. if (!preg_match('/\$$/', $re))
  422. {
  423. $re = $re.".*\$";
  424. }
  425. $exec = 'show route aspath-regex "'.str_replace('_', ' ', $re).'" all';
  426. }
  427. }
  428. if ($command == 'graph')
  429. {
  430. $ER = error_reporting(0);
  431. @include 'Image/GraphViz.php';
  432. if (!class_exists('Image_GraphViz'))
  433. {
  434. print '<div class="center"><p class="error">Class Image_GraphViz not found!</p></div>';
  435. }
  436. else
  437. {
  438. if (isset($_REQUEST['render']))
  439. {
  440. $format = ($_REQUEST['render'] == 'png') ? 'png' : 'svg';
  441. if ($output = process($url, $exec, TRUE) AND $as_bgp_path = parse_bgp_path($output))
  442. {
  443. $as_best_path = $as_bgp_path['best'];
  444. $as_pathes = $as_bgp_path['pathes'];
  445. if (sizeof($as_pathes) < 1)
  446. {
  447. get_blank_graph('Not found BGP information of request.', $format);
  448. }
  449. get_path_graph($router, $query, $as_pathes, $as_best_path, $format);
  450. }
  451. get_blank_graph('Unable to get BGP information.', $format);
  452. }
  453. ?>
  454. <div class="center">
  455. <p>BGP routing graph for <b><?php print $query ?></b>, router: <b><?php print $_CONFIG['routers'][$router]['description'] ?></b></p>
  456. <p><a href="?command=bgp&amp;protocol=<?php print $protocol ?>&amp;query=<?php print $query ?>&amp;router=<?php print $router ?>">Run a bgp command on this router</a></p>
  457. <table border="0" class="legend">
  458. <tr><td bgcolor="#CCCCFF" width="15">&nbsp;</td><td>Upstream AS</td><td width="80">&nbsp;</td><td bgcolor="#CCFFCC" width="15">&nbsp;</td><td>Peering AS</td><td width="80">&nbsp;</td><td bgcolor="white"><div style="height:12px;width:37px;background-image:url('data:image/gif;base64,R0lGODlhJQAMAOcAAAQCBISChJQ2NMTCxERCRcSCTGRiZYRWNEw2HKSipOTi5CQiJWRCJORCROyiXPzClISGnFRSVXRydKyi5DQyNRQSFJSSqdwCBPTy99xqlNTS1PwiJNSGvMSm7FxGRGxijIR+fPzk5JySzPSKVLS0tCQlNFxSdCQXDERCXOTC3LS21Dw6PSwCBNQeHAwKDPxSLHxyo+x2hNTS9MTG5KRyROzs7JSGwRwaHeyitPzU1KSivGxsbGRagVxaXXx8fLSq8ZycnPw0NOSaXLyCTExKTrxqbHwiJPylpDQzRPz+/GxuhCwqN4yOjJRkPEQ+WeTk/CwsLPRCTKSa3PwUFBQOCtza/Py0tNSPVGxKLIyKn1RVZBQWHPwDBPz09PxkZPybnIR3rFxcbExKZPzExDw6VPx8fNzO/KyqxJyatPQeLBQCBMzMzERGVGRldFw+JDQiFHRyhNzb3PQqPPTu/PyEhLy8vLyy/AwNFPxVVMzK6pSOxBweLOza7Lyq9HxunDQuQfxMTLwmJPzavPyUlMyb3JxaXLx+TFRKbCQeLOxufKysrPSuvORKZMSy/OTO7Hx+lPwKDIyCt/x0dPzc3Pw8PPysrPy8vPxsbPzNzPyMjPxaXIyKjMyOzHRqlcyKVCweFLy+3JSWlNyWW4R+tJxqPMTC3LSyzFw6PPwaHPwsLPzs7AwGBFQ5JGxGLPSiYLSi5hwSDKSV1ExCXLy61tzW/Dw1TJSSlOzi9PxERKya3BwWJMQqLISClNTW5CwmNKx2ROzs/PSmtGxsfHx7jJyarOyeXJxmPHRNLFxafExKbJyOzIx+fPR2hIx+tAQGBERGRWRmZOTm5CQmJWRGLPzGnFRWVDQ2NZSWrPT298Sq9GxmjlxWeTw+PQwODNTW9pSKxBweHaSmvWRehFxeXExOTCwuNNze/IyOpExOXDw+TKyuypyetXR2iMzO7Lyu+FROcPwODHRunPweHfSmZLSm7ExGZOzm/Kye44SGhMTGxIRaNKSmpHR2dBQWFNTW1PwmJCwAAAAAJQAMAAAIagCTCBxIsKBBVQYTKlxo8AsXL5YYSpzokAuXKZIwTdxYsKJFi/LK5OC40ePHj6kyhRh4pKXLlzBjXjpJ82OQRElq6tw5ZWfNKCQb+rQYZFDQhCZPpqIz6ajCpCFHOl1YccqlMVMnHoG4MSAAOw==')"></div></td><td>Best route</td></tr>
  459. </table>
  460. <br>
  461. <div id="loading" style="display:inline"><p><b>Please wait...</b></p></div>
  462. <!--[if IE]>
  463. <p><img src="?command=graph&amp;protocol=<?php print $protocol ?>&amp;query=<?php print $query ?>&amp;router=<?php print $router ?>&amp;render=png" type="image/svg+xml" alt="" title=""></p>
  464. <![endif]-->
  465. <![if ! IE]>
  466. <object data="?command=graph&amp;protocol=<?php print $protocol ?>&amp;query=<?php print $query ?>&amp;router=<?php print $router ?>&amp;render=true" type="image/svg+xml"></object>
  467. <![endif]>
  468. <br>
  469. </div>
  470. <?php
  471. }
  472. error_reporting($ER);
  473. }
  474. else
  475. {
  476. print '<p><b>Router:</b> '.$_CONFIG['routers'][$router]['description'].'<br><b>Command:</b> '.$exec.'</p><pre><code>';
  477. flush();
  478. process($url, $exec);
  479. print '</code></pre>';
  480. }
  481. }
  482. }
  483. else
  484. {
  485. $routers = group_routers($_CONFIG['routers']);
  486. // HTML form
  487. ?>
  488. <form method="get" action="">
  489. <div class="center">
  490. <table class="form" cellpadding="2" cellspacing="2">
  491. <tr><th>Type of Query</th><th>Additional parameters</th><th>Node</th></tr>
  492. <tr><td>
  493. <table border="0" cellpadding="2" cellspacing="2">
  494. <tr><td><input type="radio" name="command" id="bgp" value="bgp" checked="checked"></td><td><label for="bgp">bgp</label></td></tr>
  495. <tr><td><input type="radio" name="command" id="advertised-routes" value="advertised-routes"></td><td><label for="advertised-routes">bgp&nbsp;advertised-routes</label></td></tr>
  496. <tr><td><input type="radio" name="command" id="summary" value="summary"></td><td><label for="summary">bgp&nbsp;summary</label></td></tr>
  497. <tr><td><input type="radio" name="command" id="graph" value="graph"></td><td><label for="graph">bgp graph</label></td></tr>
  498. <tr><td><input type="radio" name="command" id="trace" value="trace"></td><td><label for="trace">traceroute</label></td></tr>
  499. <tr><td><input type="radio" name="command" id="ping" value="ping"></td><td><label for="ping">ping</label></td></tr>
  500. <tr><td></td><td style="padding-top:10px">
  501. <select name="protocol">
  502. <option value="ipv4">IPv4</option>
  503. <option value="ipv6">IPv6</option>
  504. </select></td></tr>
  505. </table></td>
  506. <td align="center"><input name="query" size="30"></td>
  507. <td align="right">
  508. <select name="router" style="min-width: 180px">
  509. <?php foreach ($routers as $group => $group_data): ?>
  510. <?php if ($group != ''): ?>
  511. <optgroup label="<?php print htmlspecialchars($group) ?>">
  512. <?php endif ?>
  513. <?php foreach ($group_data as $router_id => $router_data): ?>
  514. <option value="<?php print $router_id ?>"><?php print htmlspecialchars($router_data['description']) ?></option>
  515. <?php endforeach ?>
  516. <?php if ($group != ''): ?>
  517. </optgroup>
  518. <?php endif ?>
  519. <?php endforeach ?>
  520. </select></td></tr>
  521. <tr><td align="center" colspan="3"><p><input type="submit" value="Submit"> | <input type="reset" value="Reset"></p></td></tr>
  522. </table>
  523. </div>
  524. </form>
  525. <?php
  526. }
  527. // HTML footer
  528. ?>
  529. <hr>
  530. <div class="center">
  531. <p><small>Information: <a href="https://stat.ripe.net/AS<?php print $_CONFIG['asn'] ?>" target="_blank">RIPEstat</a> <a href="http://bgp.he.net/AS<?php print $_CONFIG['asn'] ?>" target="_blank">he.net</a> <a href="http://as.robtex.com/as<?php print $_CONFIG['asn'] ?>.html#asinfo" target="_blank">robtex.com</a> <a href="http://as.robtex.com/as<?php print $_CONFIG['asn'] ?>.png" target="_blank">Peering Map</a> <a href="http://www.peeringdb.com/view.php?asn=<?php print $_CONFIG['asn'] ?>" target="_blank">PeeringDB</a></small></p>
  532. <p>Copyright &copy; <?php print date('Y') ?> <?php print htmlspecialchars($_CONFIG['company']) ?></p>
  533. </div>
  534. </body>
  535. </html>
  536. <?php
  537. // ------------------------------------------------------------------------
  538. /**
  539. * Execute command and print output
  540. */
  541. function process($url, $exec, $return_buffer = FALSE)
  542. {
  543. global $_CONFIG, $router, $protocol, $os, $command, $query, $ros;
  544. $lines = $line = $is_exception = FALSE;
  545. $index = 0;
  546. $str_in = array();
  547. switch ($url['scheme'])
  548. {
  549. case 'ssh':
  550. $params = array('-ssh');
  551. if (isset($url['user']) AND $url['user'] != '')
  552. {
  553. $params[] = '-l '.$url['user'];
  554. }
  555. if (isset($url['pass']) AND $url['pass'] != '')
  556. {
  557. $params[] = '-pw '.$url['pass'];
  558. }
  559. if (isset($url['port']) AND $url['port'] != '')
  560. {
  561. $params[] = '-P '.$url['port'];
  562. }
  563. $params[] = $url['host'];
  564. // Get MikroTik additional summary information
  565. if (preg_match('/^\/routing bgp peer print status/i', $exec) AND $os == 'mikrotik' AND $return_buffer != TRUE)
  566. {
  567. if ($instance = @shell_exec('echo n | '.$_CONFIG['plink'].' '.implode(' ', $params).' /routing bgp instance print'))
  568. {
  569. $instance_list = parse_list($instance);
  570. print 'BGP router identifier '.$instance_list['router-id'].', local AS number '.link_as($instance_list['as'])."\n";
  571. }
  572. }
  573. // Get MikroTik version for traceroute
  574. if (preg_match('/^\/tool traceroute/i', $exec) AND $os == 'mikrotik' AND $return_buffer != TRUE)
  575. {
  576. if ($instance = @shell_exec('echo n | '.$_CONFIG['plink'].' '.implode(' ', $params).' /system resource print'))
  577. {
  578. if (preg_match('/version: (\d+)/', $instance, $ver))
  579. {
  580. if (isset($ver[1]))
  581. {
  582. if ($ver[1] == 6)
  583. {
  584. $exec .= ' count=1';
  585. }
  586. $ros = $ver[1];
  587. }
  588. }
  589. }
  590. }
  591. if ($fp = @popen('echo n | '.$_CONFIG['plink'].' '.implode(' ', $params).' '.$exec, 'r'))
  592. {
  593. while (!feof($fp))
  594. {
  595. if (!$output = fgets($fp, 1024))
  596. {
  597. continue;
  598. }
  599. $line = !$return_buffer ? parse_out($output, TRUE) : $output;
  600. if ($line === TRUE)
  601. {
  602. if (!$return_buffer)
  603. {
  604. print '<p class="error">Command aborted.</p>';
  605. }
  606. break;
  607. }
  608. if ($line === FALSE OR $return_buffer === TRUE)
  609. {
  610. $lines .= $output;
  611. continue;
  612. }
  613. print $line;
  614. flush();
  615. if ($line === NULL)
  616. {
  617. $line = $output;
  618. }
  619. }
  620. pclose($fp);
  621. }
  622. break;
  623. case 'telnet':
  624. if (!isset($url['port']) OR $url['port'] == '')
  625. {
  626. $url['port'] = 23;
  627. }
  628. if (!isset($url['user']) OR $url['user'] == '')
  629. {
  630. $url['user'] = FALSE;
  631. }
  632. if (!isset($url['pass']) OR $url['pass'] == '')
  633. {
  634. $url['pass'] = FALSE;
  635. }
  636. try
  637. {
  638. if ($os == 'mikrotik')
  639. {
  640. $url['user'] .= '+ct';
  641. $prompt = '/[^\s]{2,} [>]/';
  642. }
  643. else
  644. {
  645. $prompt = '/[^\s]{2,}[\$%>] {0,1}$/';
  646. }
  647. $telnet = new Telnet($url['host'], $url['port']);
  648. $telnet->connect();
  649. $telnet->login($url['user'], $url['pass']);
  650. $telnet->write(($os == 'junos') ? $exec.' | no-more' : $exec);
  651. $buffer = '';
  652. $i = $j = 0;
  653. do
  654. {
  655. $c = $telnet->getc();
  656. if ($c === false)
  657. {
  658. break;
  659. }
  660. if ($c == $telnet->IAC)
  661. {
  662. if ($telnet->negotiateTelnetOptions())
  663. {
  664. continue;
  665. }
  666. }
  667. $buffer .= $c;
  668. // Clear buffer berofe backspace or escape notice
  669. if ($c == "\x08" OR $buffer == "Type escape sequence to abort.\r\n")
  670. {
  671. $buffer = '';
  672. continue;
  673. }
  674. //$c = preg_replace('/\[\d;?(\d+)?;?(\d)?m/x', ' ', $c); // Strip remaining
  675. //$c = preg_replace('/\x1B\x5B\x30\x6D/x', '\x0A', $c); // Convert to \n
  676. //$c = preg_replace('/[\x80-\xFF]/x', ' ', $c); // Strip Ext ASCII
  677. //$c = preg_replace('/[\x00-\x09\x0B-\x1F]/x', ' ', $c); // Strip Low ASCII
  678. $buffer = preg_replace('/\x1b\x5b;?([^\x6d]+)?\x6d/x', '', $buffer); // Strip colors
  679. if (preg_match($prompt, substr($buffer, -4)))
  680. {
  681. if ($j < 2)
  682. {
  683. $j++;
  684. if (substr($buffer, -2) != "\r\n")
  685. {
  686. $telnet->write();
  687. $i = 0;
  688. continue;
  689. }
  690. }
  691. $telnet->disconnect();
  692. break;
  693. }
  694. if (substr($buffer, -10) == ' --More-- ')
  695. {
  696. $telnet->write();
  697. }
  698. else if (substr($buffer, -2) == "\r\n")
  699. {
  700. // Clear buffer on first empty line
  701. if ($i == 1 AND $buffer == "\r\n")
  702. {
  703. $buffer = '';
  704. }
  705. $i++;
  706. if ($i > 1)
  707. {
  708. $line = !$return_buffer ? parse_out($buffer, TRUE) : $buffer;
  709. if ($line === TRUE)
  710. {
  711. if (!$return_buffer)
  712. {
  713. print '<p class="error">Command aborted.</p>';
  714. }
  715. $telnet->disconnect();
  716. break;
  717. }
  718. if ($line === FALSE OR $return_buffer === TRUE)
  719. {
  720. $lines .= $buffer;
  721. }
  722. else
  723. {
  724. print $line;
  725. flush();
  726. if ($line === NULL)
  727. {
  728. $line = $buffer;
  729. }
  730. }
  731. }
  732. $buffer = '';
  733. }
  734. }
  735. while ($c != $telnet->NULL OR $c != $telnet->DC1);
  736. }
  737. catch (Exception $exception)
  738. {
  739. $is_exception = TRUE;
  740. if (!$return_buffer)
  741. {
  742. print '<p class="error">Telnet error: '.$exception->getMessage().'</p>';
  743. }
  744. }
  745. break;
  746. }
  747. if ($lines)
  748. {
  749. if ($return_buffer)
  750. {
  751. return $lines;
  752. }
  753. if ($line = parse_out($lines))
  754. {
  755. print $line;
  756. }
  757. if (empty($line) AND $is_exception == FALSE)
  758. {
  759. print '<p class="error">Command failed.</p>';
  760. }
  761. }
  762. flush();
  763. }
  764. /**
  765. * Parse output contents
  766. */
  767. function parse_out($output, $check = FALSE)
  768. {
  769. global $_CONFIG, $router, $protocol, $os, $command, $exec, $query, $index, $lastip, $best, $count, $str_in, $ros;
  770. $output = str_replace("\r\n", "\n", $output);
  771. // MikroTik
  772. if (preg_match("/^\/(ip|ipv6) route print detail/i", $exec) AND $os == 'mikrotik')
  773. {
  774. if ($check)
  775. {
  776. return FALSE;
  777. }
  778. $output_parts = explode("\n" , trim($output), ($protocol != 'ipv6' ? 4 : 3));
  779. if (!isset($output_parts[2]))
  780. {
  781. return 'Records for '.strip_tags($query).' is not found';
  782. }
  783. $summary_parts = explode("\n\n" , $output_parts[($protocol != 'ipv6' ? 3 : 2)]);
  784. $output = implode("\n", array_slice($output_parts, 0, ($protocol != 'ipv6' ? 3 : 2)))."\n\n";
  785. foreach ($summary_parts as $summary_part)
  786. {
  787. $data_exp = explode(' ', trim($summary_part), 3);
  788. $summary_part = preg_replace_callback(
  789. "/bgp-as-path=\"([^\"]+)\"/x",
  790. function ($matches) {
  791. return stripslashes('bgp-as-path=\"'.link_as($matches[1]).'\"');
  792. },
  793. $summary_part
  794. );
  795. if (strpos($data_exp[1], 'A') !== FALSE)
  796. {
  797. $output .= '<span style="color:#ff0000">'.$summary_part."</span>\n\n";
  798. }
  799. else
  800. {
  801. $output .= $summary_part."\n\n";
  802. }
  803. }
  804. return $output;
  805. }
  806. // MikroTik
  807. if (preg_match("/^\/routing bgp advertisements print/i", $exec) AND $os == 'mikrotik')
  808. {
  809. return preg_replace_callback(
  810. "/^(.{8}\s)([\d\.A-Fa-f:\/]+)(\s+)/",
  811. function ($matches) {
  812. return $matches[1].link_command("bgp", $matches[2]).$matches[3];
  813. },
  814. $output
  815. );
  816. }
  817. // MikroTik
  818. if (preg_match("/^\/(ip|ipv6) route print/i", $exec) AND $os == 'mikrotik')
  819. {
  820. return preg_replace_callback(
  821. "/(^[\s\d]+)(\s+[A-z]+\s+)([\d\.A-Fa-f:\/]+)(\s+)/",
  822. function ($matches) {
  823. return $matches[1].$matches[2].link_command("bgp", $matches[3]).$matches[4];
  824. },
  825. $output
  826. );
  827. }
  828. // MikroTik
  829. if (preg_match("/^\/routing bgp peer print status/i", $exec) AND $os == 'mikrotik')
  830. {
  831. if ($check)
  832. {
  833. return FALSE;
  834. }
  835. $output_parts = explode("\n" , trim($output), 2);
  836. if (!isset($output_parts[1]))
  837. {
  838. return 'Records for '.strip_tags($query).' is not found';
  839. }
  840. $summary_parts = explode("\n\n" , $output_parts[1]);
  841. $table_array[] = array
  842. (
  843. 'remote-address' => 'Neighbor',
  844. 'name' => 'PeerName',
  845. 'remote-id' => 'RemoteID',
  846. 'remote-as' => 'AS',
  847. 'withdrawn-received' => 'MsgRcvd',
  848. 'updates-received' => 'MsgSent',
  849. 'uptime' => 'Up/Down',
  850. 'state' => 'State',
  851. 'prefix-count' => 'PfxRcd',
  852. 'updates-sent' => 'PfxSnd',
  853. );
  854. foreach ($summary_parts as $summary_part)
  855. {
  856. $data_exp = explode(' ', trim($summary_part), 3);
  857. if (sizeof($data_exp) != 3)
  858. {
  859. continue;
  860. }
  861. $data = parse_list($data_exp[2]);
  862. $table_array[] = array
  863. (
  864. 'remote-address' => isset($data['remote-address']) ? link_whois($data['remote-address']) : '',
  865. 'name' => isset($data['name']) ? $data['name'] : '',
  866. 'remote-id' => isset($data['remote-id']) ? $data['remote-id'] : '',
  867. 'remote-as' => isset($data['remote-as']) ? link_as($data['remote-as']) : '',
  868. 'withdrawn-received' => isset($data['withdrawn-received']) ? $data['withdrawn-received'] : '',
  869. 'updates-received' => isset($data['updates-received']) ? $data['updates-received'] : '',
  870. 'uptime' => isset($data['uptime']) ? $data['uptime'] : '',
  871. 'state' => $data_exp[1],
  872. 'prefix-count' => (isset($data['remote-address']) AND isset($data['prefix-count']))
  873. ? link_command('routes', $data['remote-address'], $data['prefix-count'])
  874. : '',
  875. 'updates-sent' => (isset($data['name']) AND isset($data['updates-sent']))
  876. ? link_command('advertised-routes', $data['name'], $data['updates-sent'])
  877. : '',
  878. );
  879. }
  880. return
  881. str_replace('Flags', 'State', $output_parts[0])."\n\n".
  882. build_table($table_array)."\n\n".
  883. 'Total number of neighbors '.(sizeof($table_array) - 1);
  884. }
  885. // MikroTik
  886. if (preg_match("/^\/ping/i", $exec) AND $os == 'mikrotik')
  887. {
  888. if (preg_match('/^HOST/', $output) AND $index == 0)
  889. {
  890. $index++;
  891. return 'PING '.$query.' ('.get_ptr($query).'): 56 data bytes'."\n";
  892. }
  893. if ($index > 0)
  894. {
  895. $exp = explode(' ', preg_replace('/[\s\t]+/', ' ', trim($output)));
  896. $exp = array_slice($exp, 0, 4);
  897. if (!$exp OR $exp[0] == '' OR $exp[0] == 'HOST' OR (isset($exp[1]) AND $exp[1] == 'timeout'))
  898. {
  899. return;
  900. }
  901. if (preg_match('/sent=([0-9]+) received=([0-9]+) packet-loss=([^ ]+)/', $output, $stat))
  902. {
  903. $return = "\n".'--- '.$query.' ping statistics ---'."\n".
  904. $stat[1].' packets transmitted, '.$stat[2].' packets received, '.trim($stat[3]).' packet loss'."\n";
  905. if (preg_match('/min-rtt=([0-9]+)ms avg-rtt=([0-9]+)ms/', $output, $stat2))
  906. {
  907. $return .= 'round-trip min/avg/max = '.$stat2[1].'/'.$stat2[2];
  908. }
  909. if (preg_match('/max-rtt=([0-9]+)ms/', $output, $stat3))
  910. {
  911. $return .= '/'.$stat3[1];
  912. }
  913. return $return;
  914. }
  915. // Пинг больше 99, отдача max-rtt отдельной строкой
  916. if (preg_match('/max-rtt=([0-9]+)ms/', $output, $stat3))
  917. {
  918. $return = '/'.$stat3[1];
  919. return $return;
  920. }
  921. $index++;
  922. return $exp[1].' bytes from '.$exp[0].': icmp_seq='.intval($index-1).' ttl='.$exp[2].' time='.$exp[3]."\n";
  923. }
  924. }
  925. // MikroTik
  926. if (preg_match("/^\/tool trace/i", $exec) AND $os == 'mikrotik' AND $ros >= 6)
  927. {
  928. if (preg_match('/^ # ADDRESS/', $output) AND $index == 0)
  929. {
  930. $index++;
  931. return 'traceroute to '.$query.' ('.get_ptr($query).'), 64 hops max, 60 byte packets'."\n";
  932. }
  933. if ($index > 0)
  934. {
  935. $exp = explode(' ', preg_replace('/[\s\t]+/', ' ', trim($output)));
  936. $exp = array_slice($exp, 0, 9);
  937. if (!$exp OR empty($exp[0]) OR (sizeof($exp) == 4 AND isset($exp[3]) AND $exp[3] != 'timeout'))
  938. {
  939. return;
  940. }
  941. $new_exp[0] = (strlen($exp[0]) < 2) ? ' '.$exp[0] : $exp[0];
  942. if ($exp[3] == 'timeout')
  943. {
  944. $new_exp[1] = '* * *';
  945. $new_exp = array_slice($new_exp, 0, 2);
  946. }
  947. else
  948. {
  949. $radb = get_radb($exp[1]);
  950. $new_exp[1] = get_ptr($exp[1]);
  951. $new_exp[2] = '('.$exp[1].')';
  952. $new_exp[3] = '['.(isset($radb['origin']) ? 'AS '.link_as($radb['origin']) : '').']';
  953. $new_exp[4] = $exp[5].'ms';
  954. $new_exp[5] = $exp[6].'ms';
  955. $new_exp[6] = $exp[7].'ms';
  956. }
  957. if ($index >= 64)
  958. {
  959. return TRUE;
  960. }
  961. $str = implode(' ', $new_exp)."\r\n";
  962. if (@in_array($str, $str_in))
  963. {
  964. return;
  965. }
  966. $str_in[] = $str;
  967. $index++;
  968. return $str;
  969. }
  970. }
  971. // MikroTik
  972. if (preg_match("/^\/tool trace/i", $exec) AND $os == 'mikrotik' AND $ros <= 5)
  973. {
  974. if (preg_match('/^ # ADDRESS/', $output) AND $index == 0)
  975. {
  976. $index++;
  977. return 'traceroute to '.$query.' ('.get_ptr($query).'), 64 hops max, 60 byte packets'."\n";
  978. }
  979. if ($index > 0)
  980. {
  981. $exp = explode(' ', preg_replace('/[\s\t]+/', ' ', trim($output)));
  982. $exp = array_slice($exp, 0, 5);
  983. if (!$exp OR empty($exp[0]))
  984. {
  985. return;
  986. }
  987. $exp[0] = (strlen($exp[0]) < 2) ? ' '.$exp[0] : $exp[0];
  988. if ($exp[1] == '0.0.0.0' OR $exp[1] = '::')
  989. {
  990. $exp[1] = '* * *';
  991. $exp = array_slice($exp, 0, 2);
  992. }
  993. else
  994. {
  995. $radb = get_radb($exp[1]);
  996. $exp[6] = $exp[4];
  997. $exp[5] = $exp[3];
  998. $exp[4] = $exp[2];
  999. $exp[3] = '['.(isset($radb['origin']) ? 'AS '.link_as($radb['origin']) : '').']';
  1000. $exp[2] = '('.$exp[1].')';
  1001. $exp[1] = get_ptr($exp[1]);
  1002. }
  1003. if ($index >= 64)
  1004. {
  1005. return TRUE;
  1006. }
  1007. $index++;
  1008. return implode(' ', $exp)."\r\n";
  1009. }
  1010. }
  1011. // Other OS parsers
  1012. if (preg_match('/^show bgp ipv6 unicast/i', $exec) AND $os = 'ios')
  1013. {
  1014. $output = str_replace('% Incomplete command.', '<p class="error">Please use network prefix in Parameter.</p>', $output);
  1015. }
  1016. if ($exec == 'show ip bgp summary')
  1017. {
  1018. $output = preg_replace_callback(
  1019. "/( local AS number )(\d+)/",
  1020. function ($matches) {
  1021. return $matches[1].link_as($matches[2]);
  1022. },
  1023. $output
  1024. );
  1025. // JunOS
  1026. if ($os == 'junos')
  1027. {
  1028. $output = preg_replace_callback(
  1029. "/^([\dA-Fa-f:\.]+\s+)(\d+)/",
  1030. function ($matches) {
  1031. return $matches[1].link_as($matches[2]);
  1032. },
  1033. $output
  1034. );
  1035. }
  1036. else
  1037. {
  1038. $output = preg_replace_callback(
  1039. "/^([\d\.]+\s+\d+\s+)(\d+)/",
  1040. function ($matches) {
  1041. return $matches[1].link_as($matches[2]);
  1042. },
  1043. $output
  1044. );
  1045. }
  1046. $output = preg_replace_callback(
  1047. "/^(\d+\.\d+\.\d+\.\d+)(\s+.*\s+)([1-9]\d*)\n$/",
  1048. function ($matches) {
  1049. return $matches[1].$matches[2].link_command("routes", $matches[1], $matches[3])."\n";
  1050. },
  1051. $output
  1052. );
  1053. $output = preg_replace_callback(
  1054. "/^(\d+\.\d+\.\d+\.\d+)(\s+)/",
  1055. function ($matches) {
  1056. return link_command("bgp", "neighbors+".$matches[1], $matches[1]).$matches[2];
  1057. },
  1058. $output
  1059. );
  1060. // IPv6 neighbours
  1061. $output = preg_replace_callback(
  1062. "/^(.{15} 4\s+)(\d+)/",
  1063. function ($matches) {
  1064. return $matches[1].link_as($matches[2]);
  1065. },
  1066. $output
  1067. );
  1068. $output = preg_replace_callback(
  1069. "/^([\dA-Fa-f]*:[\dA-Fa-f:]*)(\s+)/",
  1070. function ($matches) {
  1071. return link_command("bgp", "neighbors+".$matches[1], $matches[1]).$matches[2];
  1072. },
  1073. $output
  1074. );
  1075. $output = preg_replace_callback(
  1076. "/^([\dA-Fa-f]*:[\dA-Fa-f:]*)\n$/",
  1077. function ($matches) {
  1078. return link_command("bgp", "neighbors+".$matches[1], $matches[1])."\n";
  1079. },
  1080. $output
  1081. );
  1082. return $output;
  1083. }
  1084. if ($exec == 'show ipv6 bgp summary' OR $exec == 'show bgp ipv6 unicast summary')
  1085. {
  1086. $output = preg_replace_callback(
  1087. "/^(.{15} 4\s+)(\d+)/",
  1088. function ($matches) {
  1089. return $matches[1].link_as($matches[2]);
  1090. },
  1091. $output
  1092. );
  1093. if (preg_match("/^([\dA-Fa-f]*:[\dA-Fa-f:]*)\s+4\s+/", $output, $lastip_exp))
  1094. {
  1095. $lastip = $lastip_exp[1];
  1096. $output = preg_replace_callback(
  1097. "/^(.{15} 4\s+)(\d+)/",
  1098. function ($matches) {
  1099. return $matches[1].link_as($matches[2]);
  1100. },
  1101. $output
  1102. );
  1103. $output = preg_replace_callback(
  1104. "/^([\dA-Fa-f:]+)(\s+.*\s+)([1-9]\d*)$/",
  1105. function ($matches) use ($lastip) {
  1106. return link_command("routes", $lastip, $matches[3]);
  1107. },
  1108. $output
  1109. );
  1110. $output = preg_replace_callback(
  1111. "/^([\dA-Fa-f:]+)(\s+)/",
  1112. function ($matches) {
  1113. return link_command("routes", $matches[1]).$matches[2];
  1114. },
  1115. $output
  1116. );
  1117. unset($lastip);
  1118. }
  1119. if (preg_match("/^([\dA-Fa-f:]+)\n$/", $output, $lastip_exp))
  1120. {
  1121. $lastip = $lastip_exp[1];
  1122. $output = preg_replace_callback(
  1123. "/^([\dA-Fa-f:]+)/",
  1124. function ($matches) {
  1125. return link_command("routes", $matches[1]);
  1126. },
  1127. $output
  1128. );
  1129. }
  1130. if (isset($lastip) AND preg_match("/^(\s+.*\s+)([1-9]\d*)\n$/", $output))
  1131. {
  1132. $output = preg_replace_callback(
  1133. "/^(\s+.*\s+)([1-9]\d*)\n$/",
  1134. function ($matches) use ($lastip) {
  1135. return $matches[1].link_command("routes", $lastip, $matches[2])."\n";
  1136. },
  1137. $output
  1138. );
  1139. unset($lastip);
  1140. }
  1141. return $output;
  1142. }
  1143. if ($exec == 'show bgp summary')
  1144. {
  1145. // JunOS
  1146. if (preg_match("/^([\dA-Fa-f:][\d\.A-Fa-f:]+)\s+/", $output, $lastip_exp))
  1147. {
  1148. $lastip = $lastip_exp[1];
  1149. // IPv4
  1150. $output = preg_replace_callback(
  1151. "/^(\d+\.\d+\.\d+\.\d+)(\s+.*\s+)([1-9]\d*)(\s+\d+\s+\d+\s+\d+\s+\d+\s+[\d:]+\s+)(\d+)\/(\d+)\/(\d+)(\s+)/",
  1152. function ($matches) {
  1153. return $matches[1].$matches[2].
  1154. link_command("routes", $matches[1], $matches[3]).$matches[4].
  1155. link_command("routes", $matches[1], $matches[5])."/".
  1156. link_command("routes", $matches[1], $matches[6])."/".
  1157. link_command("routes", $matches[1], $matches[7]).$matches[8];
  1158. },
  1159. $output
  1160. );
  1161. // IPv4/IPv6
  1162. $output = preg_replace_callback(
  1163. "/^([\dA-Fa-f:][\d\.A-Fa-f:]+\s+)(\d+)(\s+)/",
  1164. function ($matches) {
  1165. return $matches[1].link_as($matches[2]).$matches[3];
  1166. },
  1167. $output
  1168. );
  1169. $output = preg_replace_callback(
  1170. "/^([\dA-Fa-f:][\d\.A-Fa-f:]+)(\s+)/",
  1171. function ($matches) {
  1172. return link_command("bgp", "neighbors+".$matches[1], $matches[1]).$matches[2];
  1173. },
  1174. $output
  1175. );
  1176. }
  1177. if (isset($lastip) AND preg_match("/( [^:]+: )(\d+)\/(\d+)\/(\d+)$/", $output))
  1178. {
  1179. $output = preg_replace_callback(
  1180. "/^( [^:]+: )(\d+)\/(\d+)\/(\d+)\n$/",
  1181. function ($matches) use ($lastip) {
  1182. return "\\1".
  1183. link_command("routes", $lastip, $matches[2])."/".
  1184. link_command("bgp", "neighbors+".$lastip."+routes+all", $matches[3])."/".
  1185. link_command("bgp", "neighbors+".$lastip."+routes+damping+suppressed", $matches[4])."\n";
  1186. },
  1187. $output
  1188. );
  1189. unset($lastip);
  1190. }
  1191. return $output;
  1192. }
  1193. if (preg_match("/^show ip bgp\s+n\w*\s+[\d\.]+\s+(ro|re|a)/i", $exec) OR
  1194. preg_match("/^show (ipv6 bgp|bgp ipv6)\s+n\w*\s+[\dA-Fa-f:]+\s+(ro|re|a)/i", $exec) OR
  1195. preg_match("/^show (ipv6 bgp|bgp ipv6)\s+re/i", $exec) OR
  1196. preg_match("/^show ip bgp\s+[\d\.]+\s+[\d\.]+\s+(l|s)/i", $exec) OR
  1197. preg_match("/^show (ip bgp|bgp ipv6) prefix-list/i", $exec) OR
  1198. preg_match("/^show (ip bgp|bgp ipv6) route-map/i", $exec))
  1199. {
  1200. $output = preg_replace_callback(
  1201. "/^([\*r ](>|d|h| ).{59})([\d\s,\{\}]+)([ie\?])\n$/",
  1202. function ($matches) {
  1203. return $matches[1].link_as($matches[3]).$matches[4]."\n";
  1204. },
  1205. $output
  1206. );
  1207. $output = preg_replace_callback(
  1208. "/^([\*r ](>|d|h| )[i ])([\d\.A-Fa-f:\/]+)(\s+)/",
  1209. function ($matches) {
  1210. return $matches[1].link_command("bgp", $matches[3]).$matches[4];
  1211. },
  1212. $output
  1213. );
  1214. $output = preg_replace_callback(
  1215. "/^([\*r ](>|d|h| )[i ])([\d\.A-Fa-f:\/]+)\n$/",
  1216. function ($matches) {
  1217. return $matches[1].link_command("bgp", $matches[3])."\n";
  1218. },
  1219. $output
  1220. );
  1221. $output = preg_replace_callback(
  1222. "/^(( ){20}.{41})([\d\s,\{\}]+)([ie\?])\n$/",
  1223. function ($matches) {
  1224. return $matches[1].link_as($matches[3]).$matches[4]."\n";
  1225. },
  1226. $output
  1227. );
  1228. $output = preg_replace_callback(
  1229. "/(, remote AS )(\d+)(,)/",
  1230. function ($matches) {
  1231. return $matches[1].link_as($matches[2]).$matches[3]."\n";
  1232. },
  1233. $output
  1234. );
  1235. return $output;
  1236. }
  1237. // JunOS
  1238. if (preg_match("/^show route receive-protocol bgp\s+[\d\.A-Fa-f:]+/i", $exec))
  1239. {
  1240. $output = preg_replace_callback(
  1241. "/(Community: )([\d: ]+)/",
  1242. function ($matches) {
  1243. return $matches[1].link_community($matches[2]);
  1244. },
  1245. $output
  1246. );
  1247. $output = preg_replace_callback(
  1248. "/(Communities: )([\d: ]+)/",
  1249. function ($matches) {
  1250. return $matches[1].link_community($matches[2]);
  1251. },
  1252. $output
  1253. );
  1254. $output = preg_replace_callback(
  1255. "/(^\s+AS path: )([\d ]+)/",
  1256. function ($matches) {
  1257. return $matches[1].link_as($matches[2]);
  1258. },
  1259. $output
  1260. );
  1261. $output = preg_replace_callback(
  1262. "/^([\d\.\s].{24})([\d\.]+)(\s+)/",
  1263. function ($matches) {
  1264. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]);
  1265. },
  1266. $output
  1267. );
  1268. $output = preg_replace_callback(
  1269. "/^([\d\.\/]+)(\s+)/",
  1270. function ($matches) {
  1271. return link_command("bgp", $matches[1]).$matches[2];
  1272. },
  1273. $output
  1274. );
  1275. $output = preg_replace_callback(
  1276. "/^([\d\.A-Fa-f:\/]+)(\s+)/",
  1277. function ($matches) {
  1278. return link_command("bgp", $matches[1]."+exact", $matches[1]).$matches[2];
  1279. },
  1280. $output
  1281. );
  1282. $output = preg_replace_callback(
  1283. "/^([\d\.A-Fa-f:\/]+)\s*\n$/",
  1284. function ($matches) {
  1285. return link_command("bgp", $matches[1]."+exact", $matches[1]);
  1286. },
  1287. $output
  1288. );
  1289. $output = preg_replace_callback(
  1290. "/^([ \*] )([\d\.A-Fa-f:\/]+)(\s+)/",
  1291. function ($matches) {
  1292. return $matches[1].link_command("bgp", $matches[2]."+exact", $matches[2]).$matches[3];
  1293. },
  1294. $output
  1295. );
  1296. return $output;
  1297. }
  1298. // JunOS
  1299. if (preg_match("/^show route advertising-protocol bgp\s+([\d\.A-Fa-f:]+)$/i", $exec, $ip_exp))
  1300. {
  1301. $ip = $ip_exp[1];
  1302. $output = preg_replace_callback(
  1303. "/^([\d\.\s].{64})([\d\s,\{\}]+)([I\?])\n$/",
  1304. function ($matches) {
  1305. return $matches[1].link_as($matches[2]).$matches[3]."\n";
  1306. },
  1307. $output
  1308. );
  1309. $output = preg_replace_callback(
  1310. "/^([\d\.\s].{24})([\d\.]+)(\s+)/",
  1311. function ($matches) {
  1312. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]).$matches[3];
  1313. },
  1314. $output
  1315. );
  1316. $output = preg_replace_callback(
  1317. "/^([\d\.\/]+)(\s+)/",
  1318. function ($matches) {
  1319. return link_command("bgp", $matches[1]).$matches[2];
  1320. },
  1321. $output
  1322. );
  1323. $output = preg_replace_callback(
  1324. "/^([\d\.A-Fa-f:\/]+)(\s+)/",
  1325. function ($matches) {
  1326. return link_command("bgp", $matches[1]."+exact", $matches[1]).$matches[2];
  1327. },
  1328. $output
  1329. );
  1330. $output = preg_replace_callback(
  1331. "/^([\d\.A-Fa-f:\/]+)\s*\n$/",
  1332. function ($matches) {
  1333. return link_command("bgp", $matches[1]."+exact", $matches[1])."\n";
  1334. },
  1335. $output
  1336. );
  1337. $output = preg_replace_callback(
  1338. "/^([ \*] )([\d\.A-Fa-f:\/]+)(\s+)/",
  1339. function ($matches) use ($ip) {
  1340. return $matches[1].link_command("bgp", "neighbors+".$ip."+advertised-routes+".$matches[2], $matches[2]).$matches[3];
  1341. },
  1342. $output
  1343. );
  1344. return $output;
  1345. }
  1346. if (preg_match("/^show ip bgp n\w*\s+([\d\.]+)/i", $exec) OR
  1347. preg_match("/^show ip bgp n\w*$/i", $exec))
  1348. {
  1349. if (!isset($lastip) AND preg_match("/^BGP neighbor is ([\d\.]+),/", $output, $lastip_exp))
  1350. {
  1351. $lastip = $lastip_exp[1];
  1352. }
  1353. $output = preg_replace_callback(
  1354. "/(Prefix )(advertised)( [1-9]\d*)/",
  1355. function ($matches) use ($lastip) {
  1356. return $matches[1].link_command("advertised-routes", $lastip, $matches[2]).$matches[3];
  1357. },
  1358. $output
  1359. );
  1360. $output = preg_replace_callback(
  1361. "/( Prefixes Total: )(\d+)( )/",
  1362. function ($matches) use ($lastip) {
  1363. return $matches[1].link_command("advertised-routes", $lastip, $matches[2]).$matches[3];
  1364. },
  1365. $output
  1366. );
  1367. $output = preg_replace_callback(
  1368. "/(prefixes )(received)( [1-9]\d*)/",
  1369. function ($matches) use ($lastip) {
  1370. return $matches[1].link_command("routes", $lastip, $matches[2]).$matches[3];
  1371. },
  1372. $output
  1373. );
  1374. $output = preg_replace_callback(
  1375. "/( Prefixes Current: \s+)(\d+)(\s+)(\d+)/",
  1376. function ($matches) use ($lastip) {
  1377. return $matches[1].
  1378. link_command("advertised-routes", $lastip, $matches[2]).$matches[3].
  1379. link_command("routes", $lastip, $matches[4]);
  1380. },
  1381. $output
  1382. );
  1383. $output = preg_replace_callback(
  1384. "/(\s+)(Received)( prefixes:\s+[1-9]\d*)/",
  1385. function ($matches) use ($lastip) {
  1386. return $matches[1].link_command("routes", $lastip, $matches[2]).$matches[3];
  1387. },
  1388. $output
  1389. );
  1390. $output = preg_replace_callback(
  1391. "/( Saved \(soft-reconfig\):\s+)(\d+|n\/a)(\s+)(\d+)/",
  1392. function ($matches) use ($lastip) {
  1393. return $matches[1].$matches[2].$matches[3].link_command("received-routes", $lastip, $matches[4]);
  1394. },
  1395. $output
  1396. );
  1397. $output = preg_replace_callback(
  1398. "/( [1-9]\d* )(accepted)( prefixes)/",
  1399. function ($matches) use ($lastip) {
  1400. return $matches[1].link_command("routes", $lastip, $matches[2]).$matches[3];
  1401. },
  1402. $output
  1403. );
  1404. $output = preg_replace_callback(
  1405. "/^( [1-9]\d* )(accepted|denied but saved)( prefixes consume \d+ bytes)/",
  1406. function ($matches) use ($lastip) {
  1407. return $matches[1].link_command("received-routes", $lastip, $matches[2]).$matches[3];
  1408. },
  1409. $output
  1410. );
  1411. $output = preg_replace_callback(
  1412. "/^(BGP neighbor is )(\d+\.\d+\.\d+\.\d+)(,)/",
  1413. function ($matches) {
  1414. return $matches[1].link_whois($matches[2]).$matches[3];
  1415. },
  1416. $output
  1417. );
  1418. $output = preg_replace("/^( Description: )(.*)$/", '\\1<b>\\2</b>', $output);
  1419. $output = preg_replace_callback(
  1420. "/(,\s+remote AS )(\d+)(,)/",
  1421. function ($matches) {
  1422. return $matches[1].link_as($matches[2]).$matches[3];
  1423. },
  1424. $output
  1425. );
  1426. $output = preg_replace_callback(
  1427. "/(, local AS )(\d+)(,)/",
  1428. function ($matches) {
  1429. return $matches[1].link_as($matches[2]).$matches[3];
  1430. },
  1431. $output
  1432. );
  1433. $output = preg_replace_callback(
  1434. "/( update prefix filter list is )(\S+)/",
  1435. function ($matches) {
  1436. return $matches[1].link_command("bgp", "prefix-list+".$matches[2], $matches[2]);
  1437. },
  1438. $output
  1439. );
  1440. $output = preg_replace_callback(
  1441. "/(Route map for \S+ advertisements is\s+:?\*?)(\S+)/",
  1442. function ($matches) {
  1443. return $matches[1].link_command("bgp", "route-map+".$matches[2], $matches[2]);
  1444. },
  1445. $output
  1446. );
  1447. return $output;
  1448. }
  1449. if (preg_match("/^show (ipv6 bgp|bgp ipv6) n\w*\s+([\dA-Fa-f:]+)/i", $exec, $ip_exp))
  1450. {
  1451. $ip = $ip_exp[1];
  1452. $output = preg_replace_callback(
  1453. "/(Prefix )(advertised)( [1-9]\d*)/",
  1454. function ($matches) use ($ip) {
  1455. return $matches[1].link_command("advertised-routes", "'.$ip.'", $matches[2]).$matches[3];
  1456. },
  1457. $output
  1458. );
  1459. $output = preg_replace_callback(
  1460. "/( [1-9]\d* )(accepted)( prefixes)/",
  1461. function ($matches) use ($ip) {
  1462. return $matches[1].link_command("routes", $ip, $matches[2]).$matches[3];
  1463. },
  1464. $output
  1465. );
  1466. $output = preg_replace("/^( Description: )(.*)$/", '\\1<b>\\2</b>', $output);
  1467. $output = preg_replace_callback(
  1468. "/(\s+remote AS )(\d+)(,)/",
  1469. function ($matches) {
  1470. return $matches[1].link_as($matches[2]).$matches[3];
  1471. },
  1472. $output
  1473. );
  1474. $output = preg_replace_callback(
  1475. "/(\s+local AS )(\d+)(,)/",
  1476. function ($matches) {
  1477. return $matches[1].link_as($matches[2]).$matches[3];
  1478. },
  1479. $output
  1480. );
  1481. $output = preg_replace_callback(
  1482. "/( update prefix filter list is )(\S+)/",
  1483. function ($matches) {
  1484. return $matches[1].link_command("bgp", "prefix-list+".$matches[2], $matches[2]);
  1485. },
  1486. $output
  1487. );
  1488. $output = preg_replace_callback(
  1489. "/(Route map for \S+ advertisements is\s+:?\*?)(\S+)/",
  1490. function ($matches) {
  1491. return $matches[1].link_command("bgp", "route-map+".$matches[2], $matches[2]);
  1492. },
  1493. $output
  1494. );
  1495. return $output;
  1496. }
  1497. if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+)/i", $exec, $ip_exp))
  1498. {
  1499. $ip = $ip_exp[1];
  1500. $output = preg_replace_callback(
  1501. "/(\s+AS )(\d+)/",
  1502. function ($matches) {
  1503. return $matches[1].link_as($matches[2]);
  1504. },
  1505. $output
  1506. );
  1507. $output = preg_replace_callback(
  1508. "/(\s+AS: )(\d+)/",
  1509. function ($matches) {
  1510. return $matches[1].link_as($matches[2]);
  1511. },
  1512. $output
  1513. );
  1514. $output = preg_replace_callback(
  1515. "/^( Active prefixes:\s+)(\d+)/",
  1516. function ($matches) use ($ip) {
  1517. return $matches[1].link_command("routes", $ip, $matches[2]);
  1518. },
  1519. $output
  1520. );
  1521. $output = preg_replace_callback(
  1522. "/^( Received prefixes:\s+)(\d+)/",
  1523. function ($matches) use ($ip) {
  1524. return $matches[1].link_command("bgp", "neighbors+".$ip."+routes+all", $matches[2]);
  1525. },
  1526. $output
  1527. );
  1528. $output = preg_replace_callback(
  1529. "/^( Advertised prefixes:\s+)(\d+)/",
  1530. function ($matches) use ($ip) {
  1531. return $matches[1].link_command("routes", "advertising-protocol+bgp+".$ip, $matches[2]);
  1532. },
  1533. $output
  1534. );
  1535. $output = preg_replace_callback(
  1536. "/^( Suppressed due to damping:\s+)(\d+)/",
  1537. function ($matches) use ($ip) {
  1538. return $matches[1].link_command("bgp", "neighbors+".$ip."+routes+damping+suppressed", $matches[2]);
  1539. },
  1540. $output
  1541. );
  1542. $output = preg_replace_callback(
  1543. "/^( )(Export)(: )/",
  1544. function ($matches) use ($ip) {
  1545. return $matches[1].link_command("advertised-routes", $ip, $matches[2]).$matches[3];
  1546. },
  1547. $output
  1548. );
  1549. $output = preg_replace_callback(
  1550. "/( )(Import)(: )/",
  1551. function ($matches) use ($ip) {
  1552. return $matches[1].link_command("bgp", "neighbors+".$ip."+routes+all", $matches[2]).$matches[3];
  1553. },
  1554. $output
  1555. );
  1556. return $output;
  1557. }
  1558. // JunOS
  1559. if (preg_match("/^show route protocol bgp .* terse/i", $exec))
  1560. {
  1561. $output = preg_replace_callback(
  1562. "/^([\* ] )([\d\.A-Fa-f:\/]+)(\s+)/",
  1563. function ($matches) {
  1564. return $matches[1].link_command("bgp", $matches[2]."+exact", $matches[2]).$matches[3];
  1565. },
  1566. $output
  1567. );
  1568. return $output;
  1569. }
  1570. // JunOS
  1571. if (preg_match("/^show route protocol bgp /i", $exec) OR preg_match("/^show route aspath-regex /i", $exec))
  1572. {
  1573. if (preg_match("/^ (.)BGP /", $output, $exp))
  1574. {
  1575. if ($exp[1] == '*')
  1576. {
  1577. $best = '#FF0000';
  1578. }
  1579. else
  1580. {
  1581. $best = '';
  1582. }
  1583. }
  1584. else if (preg_match("/^:?\n?[\n\d\.A-Fa-f:\/\s]{19}([\*\+\- ]{1})\[BGP\//", $output, $exp))
  1585. {
  1586. if ($exp[1] == '*' OR $exp[1] == '+')
  1587. {
  1588. $best = "#ff0000";
  1589. }
  1590. else if ($exp[1] == '-')
  1591. {
  1592. $best = "#008800";
  1593. }
  1594. else
  1595. {
  1596. $best = '';
  1597. }
  1598. }
  1599. else if (preg_match("/^[\n]+$/", $output))
  1600. {
  1601. $best = '';
  1602. }
  1603. $output = preg_replace_callback(
  1604. "/( from )([0-9\.A-Fa-f:]+)/",
  1605. function ($matches) {
  1606. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]);
  1607. },
  1608. $output
  1609. );
  1610. $output = preg_replace_callback(
  1611. "/( Source: )([0-9\.A-Fa-f:]+)/",
  1612. function ($matches) {
  1613. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]);
  1614. },
  1615. $output
  1616. );
  1617. $output = preg_replace_callback(
  1618. "/(\s+AS: )([\d ]+)/",
  1619. function ($matches) {
  1620. return link_as($matches[2]);
  1621. },
  1622. $output
  1623. );
  1624. $output = preg_replace_callback(
  1625. "/(Community: )([\d: ]+)/",
  1626. function ($matches) {
  1627. return $matches[1].link_community($matches[2]);
  1628. },
  1629. $output
  1630. );
  1631. $output = preg_replace_callback(
  1632. "/(Communities: )([\d: ]+)/",
  1633. function ($matches) {
  1634. return $matches[1].link_community($matches[2]);
  1635. },
  1636. $output
  1637. );
  1638. $output = preg_replace_callback(
  1639. "/(^\s+AS path: )([\d ]+)/",
  1640. function ($matches) {
  1641. return $matches[1].link_as($matches[2]);
  1642. },
  1643. $output
  1644. );
  1645. $output = preg_replace_callback(
  1646. "/^(:?\n?[\dA-Fa-f:]+[\d\.A-Fa-f:\/]+)(\s*)/",
  1647. function ($matches) {
  1648. return "<b>".link_command("bgp", $matches[1]."+exact", $matches[1])."</b>".$matches[2];
  1649. },
  1650. $output
  1651. );
  1652. if (isset($best) AND $best != '')
  1653. {
  1654. $output = '<span style="color:'.$best.'">'.$output.'</span>';
  1655. }
  1656. return $output;
  1657. }
  1658. if (preg_match("/bgp/", $exec))
  1659. {
  1660. $output = preg_replace("|^(BGP routing table entry for) (\S+)|", "\\1 <b>\\2</b>", $output);
  1661. if (preg_match("|^(Paths: .*) best #(\d+)|", $output, $best_exp))
  1662. {
  1663. $best = $best_exp[2];
  1664. $output = preg_replace("|^(Paths: .*) best #(\d+)|", '\\1 <span style="color:#ff0000">best #\\2</span>', $output);
  1665. }
  1666. // Fix for IPv6 route output where there are no addional 3 spaces before addresses
  1667. if (preg_match("/ Advertised to non peer-group peers:/", $output) AND preg_match("/ ipv6 /", $exec))
  1668. {
  1669. $count--;
  1670. }
  1671. if (( preg_match("/^ (\d+.*)/", $output) AND
  1672. !preg_match("/^ \d+\./", $output) AND
  1673. !preg_match("/[a-z\:\.]+/", $output)
  1674. ) OR
  1675. preg_match("/^ Local/", $output) OR
  1676. preg_match("/, \(aggregated by /", $output))
  1677. {
  1678. $count++;
  1679. $output = preg_replace_callback(
  1680. "/^([^\(A-z\n]+)/",
  1681. function ($matches) {
  1682. return link_as($matches[1]);
  1683. },
  1684. $output
  1685. );
  1686. $output = preg_replace_callback(
  1687. "/(, \(aggregated by )(\d+) ([^\)]+)/",
  1688. function ($matches) {
  1689. return $matches[1].link_as($matches[2])." ".link_whois($matches[3]);
  1690. },
  1691. $output
  1692. );
  1693. }
  1694. if (isset($best) AND $best == $count)
  1695. {
  1696. $output = '<span style="color:#ff0000">'.$output.'</span>';
  1697. }
  1698. $output = preg_replace_callback(
  1699. "/( from )([0-9\.A-Fa-f:]+)( )/",
  1700. function ($matches) {
  1701. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]).$matches[3];
  1702. },
  1703. $output
  1704. );
  1705. $output = preg_replace_callback(
  1706. "/(Community: )([\d: ]+)/",
  1707. function ($matches) {
  1708. return $matches[1].link_community($matches[2]);
  1709. },
  1710. $output
  1711. );
  1712. $output = preg_replace_callback(
  1713. "/(Communities: )([\d: ]+)/",
  1714. function ($matches) {
  1715. return $matches[1].link_community($matches[2]);
  1716. },
  1717. $output
  1718. );
  1719. $output = preg_replace_callback(
  1720. "/(^\s+AS path: )([\d ]+)/",
  1721. function ($matches) {
  1722. return link_as($matches[2]);
  1723. },
  1724. $output
  1725. );
  1726. return $output;
  1727. }
  1728. if (preg_match("/^trace/", $exec))
  1729. {
  1730. $output = preg_replace("/\[AS0\]\s(.*)/", "\\1", $output);
  1731. // IPv4
  1732. $output = preg_replace_callback(
  1733. "/(\[AS)(\d+)(\])\s(.*)(\))(.*)/",
  1734. function ($matches) {
  1735. return $matches[4].$matches[5]." ".$matches[1]." ".link_as($matches[2]).$matches[3].$matches[6];
  1736. },
  1737. $output
  1738. );
  1739. // IPv6
  1740. $output = preg_replace_callback(
  1741. "/(\[AS)(\d+)(\])\s([^\s]+)\s(.*)/",
  1742. function ($matches) {
  1743. return $matches[4]." ".$matches[1]." ".link_as($matches[2]).$matches[3].$matches[5];
  1744. },
  1745. $output
  1746. );
  1747. $output = preg_replace_callback(
  1748. "/\((.*)\) (\[AS\s+)(\d+)(\])/",
  1749. function ($matches) {
  1750. return get_as($matches[1], $matches[3]);
  1751. },
  1752. $output
  1753. );
  1754. return $output;
  1755. }
  1756. return $output;
  1757. }
  1758. /**
  1759. * Parse `bgp' output contents and return AS pathes
  1760. */
  1761. function parse_bgp_path($output)
  1762. {
  1763. global $os, $exec, $query, $count;
  1764. $best = FALSE;
  1765. $pathes = array();
  1766. $output = str_replace("\r\n", "\n", $output);
  1767. // MikroTik
  1768. if (preg_match("/^\/(ip|ipv6) route print detail/i", $exec) AND $os == 'mikrotik')
  1769. {
  1770. $output_parts = explode("\n" , trim($output), 4);
  1771. if (!isset($output_parts[3]))
  1772. {
  1773. return FALSE;
  1774. }
  1775. $summary_parts = explode("\n\n" , $output_parts[3]);
  1776. foreach ($summary_parts as $i => $summary_part)
  1777. {
  1778. $data_exp = explode(' ', trim($summary_part), 3);
  1779. if (strpos($data_exp[1], 'A') !== FALSE)
  1780. {
  1781. $best = $i;
  1782. }
  1783. if (preg_match("/bgp-as-path=\"([^\"]+)\"/", $summary_part, $exp))
  1784. {
  1785. if ($path = parse_as_path($exp[1]))
  1786. {
  1787. $pathes[] = $path;
  1788. }
  1789. }
  1790. }
  1791. return array
  1792. (
  1793. 'best' => $best,
  1794. 'pathes' => $pathes
  1795. );
  1796. }
  1797. // JunOS
  1798. if (preg_match("/^show route protocol bgp /i", $exec) OR preg_match("/^show route aspath-regex /i", $exec))
  1799. {
  1800. $lines = explode("\n", $output);
  1801. foreach ($lines as $line)
  1802. {
  1803. if (preg_match("/^ (.)BGP /", $line, $exp))
  1804. {
  1805. if ($exp[1] == '*')
  1806. {
  1807. if ($count == 0)
  1808. {
  1809. $count++;
  1810. }
  1811. }
  1812. }
  1813. else if (preg_match("/^:?\n?[\n\d\.A-Fa-f:\/\s]{19}([\*\+\- ]{1})\[BGP\//", $line, $exp))
  1814. {
  1815. if ($exp[1] == '*' OR $exp[1] == '+')
  1816. {
  1817. if ($count == 0)
  1818. {
  1819. $count++;
  1820. }
  1821. }
  1822. }
  1823. if (preg_match("/^\s+AS path: ([\d ]+)/", $line, $exp))
  1824. {
  1825. if ($path = parse_as_path($exp[1]))
  1826. {
  1827. $pathes[] = $path;
  1828. }
  1829. }
  1830. }
  1831. $best = $count - 1;
  1832. return array
  1833. (
  1834. 'best' => $best,
  1835. 'pathes' => $pathes
  1836. );
  1837. }
  1838. // Other OS
  1839. if (preg_match("/bgp/", $exec))
  1840. {
  1841. if (preg_match("|(Paths: .*) best #(\d+)|", $output, $best_exp))
  1842. {
  1843. $best = $best_exp[2] - 1;
  1844. }
  1845. $lines = explode("\n", $output);
  1846. foreach ($lines as $line)
  1847. {
  1848. if (( preg_match("/^ (\d+.*)/", $line) AND
  1849. !preg_match("/^ \d+\./", $line) AND
  1850. !preg_match("/[a-z\:\.]+/", $line)
  1851. ) OR
  1852. preg_match("/^ Local/", $line) OR
  1853. preg_match("/, \(aggregated by /", $line))
  1854. {
  1855. $line = preg_replace("/^([^\(A-z\n]+).*/", "\\1", $line);
  1856. if ($path = parse_as_path($line))
  1857. {
  1858. $pathes[] = $path;
  1859. }
  1860. }
  1861. }
  1862. return array
  1863. (
  1864. 'best' => $best,
  1865. 'pathes' => $pathes
  1866. );
  1867. }
  1868. return FALSE;
  1869. }
  1870. /**
  1871. * Parse list separated by spaces
  1872. */
  1873. function parse_list($array)
  1874. {
  1875. preg_match_all('/([^=]+)=([^\s]+)[\n\s]/is', $array, $out);
  1876. $array = array();
  1877. if (isset($out[1]))
  1878. {
  1879. foreach ($out[1] as $key => $val)
  1880. {
  1881. $array[trim($out[1][$key])] = trim($out[2][$key], '"');
  1882. }
  1883. }
  1884. return $array;
  1885. }
  1886. /**
  1887. * Parse AS path
  1888. */
  1889. function parse_as_path($line)
  1890. {
  1891. $path = preg_split('/([^\d]+)/', trim($line));
  1892. $return = array();
  1893. foreach ($path as $asn)
  1894. {
  1895. if ($asn != '')
  1896. {
  1897. $return[] = 'AS'.$asn;
  1898. }
  1899. }
  1900. return array_unique($return);
  1901. }
  1902. /**
  1903. * Build list table
  1904. */
  1905. function build_table($table_array)
  1906. {
  1907. $size_array = array();
  1908. foreach ($table_array as $priority => $data)
  1909. {
  1910. foreach ($data as $field => $value)
  1911. {
  1912. $size_array[$field][$priority] = $value;
  1913. }
  1914. }
  1915. $size_max = array();
  1916. foreach ($size_array as $field => $value)
  1917. {
  1918. $size_max[$field] = array_map('mb_strlen', array_map('strip_tags', $value));
  1919. }
  1920. $max = array_map('max', $size_max);
  1921. $return = '';
  1922. foreach ($table_array as $index => $data)
  1923. {
  1924. $line = array();
  1925. foreach ($data as $field => $value)
  1926. {
  1927. if (reset(array_keys($data)) == $field)
  1928. {
  1929. $line[] = $value.str_repeat(' ', $max[$field] - mb_strlen(strip_tags($value)));
  1930. }
  1931. else
  1932. {
  1933. $line[] = str_repeat(' ', $max[$field] - mb_strlen(strip_tags($value))).$value;
  1934. }
  1935. }
  1936. $return .= implode(' ', $line)."\n";
  1937. }
  1938. return $return;
  1939. }
  1940. /**
  1941. * Link to execute command
  1942. */
  1943. function link_command($command, $query, $name = '', $return_uri = FALSE)
  1944. {
  1945. global $router, $protocol;
  1946. if ($name == '')
  1947. {
  1948. $name = $query;
  1949. }
  1950. $uri = '?router='.$router.
  1951. '&amp;protocol='.$protocol.
  1952. '&amp;command='.$command.
  1953. '&amp;query='.$query;
  1954. if ($return_uri)
  1955. {
  1956. return $uri;
  1957. }
  1958. return '<a href="'.$uri.'">'.$name.'</a>';
  1959. }
  1960. /**
  1961. * Link to AS community
  1962. */
  1963. function link_community($line)
  1964. {
  1965. global $_CONFIG;
  1966. $communitylist = preg_split('/[^\d:]+/', $line);
  1967. foreach ($communitylist as $i => $community)
  1968. {
  1969. $communitylist[$i] = '<i>'.$community.'</i>';
  1970. }
  1971. return implode(' ', $communitylist);
  1972. }
  1973. /**
  1974. * Link to AS whois
  1975. */
  1976. function link_as($line, $word = FALSE)
  1977. {
  1978. global $_CONFIG;
  1979. //print_r($line);
  1980. return preg_replace("/(?:AS)?([\d]+)/is",
  1981. "<a href=\"".htmlspecialchars($_CONFIG['aswhois'])."AS\\1\" target=\"_blank\">".($word ? 'AS' : '')."\\1</a>", $line);
  1982. }
  1983. function get_as($ip, $original_as)
  1984. {
  1985. if ($original_as == 15835)
  1986. {
  1987. $as = 65535;
  1988. if($conn = fsockopen ('whois.cymru.com', 43))
  1989. {
  1990. fputs($conn, $ip."\r\n");
  1991. $output = '';
  1992. while(!feof($conn))
  1993. {
  1994. $output .= fgets($conn,128);
  1995. }
  1996. $output = explode("\n", $output);
  1997. if (isset($output[1]))
  1998. {
  1999. $_as = explode("|", $output[1]);
  2000. }
  2001. if (isset($_as[0]))
  2002. {
  2003. $as = trim($_as[0]);
  2004. if ($as == 'NA')
  2005. {
  2006. $as = 65535;
  2007. }
  2008. }
  2009. fclose($conn);
  2010. }
  2011. return '(' . $ip .') [AS ' . link_as($as) . ']';
  2012. }
  2013. else
  2014. {
  2015. return '(' . $ip .') [AS ' . link_as($original_as) . ']';
  2016. }
  2017. }
  2018. /**
  2019. * Link to whois IP
  2020. */
  2021. function link_whois($line, $name = '')
  2022. {
  2023. global $_CONFIG;
  2024. if ($name == '')
  2025. {
  2026. $name = $line;
  2027. }
  2028. return '<a href="'.htmlspecialchars($_CONFIG['ipwhois']).$line.'" target="_blank">'.$name.'</a>';
  2029. }
  2030. /**
  2031. * Get and print BGP path graph
  2032. */
  2033. function get_path_graph($router, $query, $as_pathes, $as_best_path, $format = 'svg')
  2034. {
  2035. global $_CONFIG, $_REQUEST;
  2036. $font_size = 9; // default font size
  2037. $graph = new Image_GraphViz();
  2038. $graph->addNode($router, array
  2039. (
  2040. 'label' => $_CONFIG['routers'][$router]['description'],
  2041. 'shape' => 'box',
  2042. 'style' => 'filled',
  2043. 'fillcolor' => '#FFCCCC',
  2044. 'fontsize' => $font_size + 2
  2045. ));
  2046. $query_ptr = get_ptr($query);
  2047. // Draw requested node
  2048. $graph->addNode($query, array
  2049. (
  2050. 'URL' => link_command('trace', $query, '', TRUE),
  2051. 'target' => '_blank',
  2052. 'label' => $query_ptr ? $query."\n".$query_ptr : $query,
  2053. 'shape' => 'box',
  2054. 'style' => 'filled',
  2055. 'fillcolor' => '#FFFFCC',
  2056. 'fontsize' => $font_size
  2057. ));
  2058. $as_pathes_best = $as_list = $as_peer_list = array();
  2059. // Draw path ASs
  2060. foreach ($as_pathes as $as_path_id => $as_path_array)
  2061. {
  2062. $peer_as = reset($as_path_array);
  2063. if (!isset($as_peer_list[$peer_as]) OR $as_peer_list[$peer_as] !== TRUE)
  2064. {
  2065. $as_peer_list[$peer_as] = ($as_best_path === $as_path_id);
  2066. }
  2067. $as_list = array_merge($as_list, $as_path_array);
  2068. }
  2069. $as_list = array_unique($as_list);
  2070. // Draw our AS
  2071. if (!in_array('AS'.$_CONFIG['asn'], $as_list))
  2072. {
  2073. $graph->addNode('AS'.$_CONFIG['asn'], array
  2074. (
  2075. 'URL' => $_CONFIG['aswhois'].'AS'.$_CONFIG['asn'],
  2076. 'target' => '_blank',
  2077. 'label' => 'AS'.$_CONFIG['asn']."\n".$_CONFIG['company'],
  2078. 'style' => 'filled',
  2079. 'fillcolor' => 'white',
  2080. 'fontsize' => $font_size
  2081. ));
  2082. $graph->addEdge(array('AS'.$_CONFIG['asn'] => $router), array
  2083. (
  2084. 'color' => 'red'
  2085. ));
  2086. }
  2087. foreach ($as_list as $as_id)
  2088. {
  2089. $color = isset($as_peer_list[$as_id]) ? ($as_peer_list[$as_id] ? '#CCFFCC' : '#CCCCFF') : 'white';
  2090. $asinfo = get_asinfo($as_id);
  2091. $graph->addNode($as_id, array
  2092. (
  2093. 'URL' => $_CONFIG['aswhois'].$as_id,
  2094. 'target' => '_blank',
  2095. 'label' => isset($asinfo['description']) ? $as_id."\n".$asinfo['description'] : $as_id,
  2096. 'style' => 'filled',
  2097. 'fillcolor' => $color,
  2098. 'fontsize' => $font_size
  2099. ));
  2100. }
  2101. // Draw pathes
  2102. foreach ($as_pathes as $as_path_id => $as_path_array)
  2103. {
  2104. $first = $last = FALSE;
  2105. foreach ($as_path_array as $as_path)
  2106. {
  2107. if (!$first)
  2108. {
  2109. $first = $last = $as_path;
  2110. continue;
  2111. }
  2112. if (!isset($as_pathes_best[$last.$as_path]))
  2113. {
  2114. $graph->addEdge(array($last => $as_path), array
  2115. (
  2116. 'color' => ($as_best_path === $as_path_id) ? 'red' : 'black'
  2117. ));
  2118. if ($as_best_path === $as_path_id)
  2119. {
  2120. $as_pathes_best[$last.$as_path] = TRUE;
  2121. }
  2122. }
  2123. $last = $as_path;
  2124. }
  2125. if (!isset($as_pathes_best[$router.$first]))
  2126. {
  2127. $graph->addEdge(array($router => $first), array
  2128. (
  2129. 'color' => ($as_best_path === $as_path_id) ? 'red' : 'black'
  2130. ));
  2131. if ($as_best_path === $as_path_id)
  2132. {
  2133. $as_pathes_best[$router.$first] = TRUE;
  2134. }
  2135. }
  2136. }
  2137. // Draw last path
  2138. $graph->addEdge(array($as_path => $query), array
  2139. (
  2140. 'color' => ($as_pathes_best) ? 'red' : 'black'
  2141. ));
  2142. $graph->image($format);
  2143. exit;
  2144. }
  2145. /**
  2146. * Get and print blank image
  2147. */
  2148. function get_blank_graph($string, $format = 'svg')
  2149. {
  2150. $graph = new Image_GraphViz();
  2151. $graph->addNode('error', array
  2152. (
  2153. 'label' => $string,
  2154. 'shape' => 'none',
  2155. 'fontcolor' => 'red',
  2156. 'fontsize' => 14
  2157. ));
  2158. $graph->image($format);
  2159. exit;
  2160. }
  2161. /**
  2162. * Get address information from RADb
  2163. */
  2164. function get_radb($request)
  2165. {
  2166. if (!$fp = @fsockopen('whois.radb.net', 43, $errnum, $errstr, 10))
  2167. {
  2168. return FALSE;
  2169. }
  2170. fputs($fp, $request."\r\n");
  2171. $data = '';
  2172. while (!feof($fp))
  2173. {
  2174. $data .= fgets($fp, 128);
  2175. }
  2176. fclose($fp);
  2177. $exp = explode("\n\n", $data);
  2178. if (!isset($exp[0]) OR empty($exp[0]))
  2179. {
  2180. return FALSE;
  2181. }
  2182. $lines = explode("\n", $exp[0]);
  2183. $return = array();
  2184. foreach ($lines as $line)
  2185. {
  2186. $line = explode(':', $line, 2);
  2187. if (isset($line[0]) AND isset($line[1]))
  2188. {
  2189. $return[$line[0]] = trim($line[1]);
  2190. }
  2191. }
  2192. if (sizeof($return) < 1)
  2193. {
  2194. return FALSE;
  2195. }
  2196. return $return;
  2197. }
  2198. /**
  2199. * Get AS name information from "Team Cymru - IP to ASN Mapping"
  2200. */
  2201. function get_asinfo($request)
  2202. {
  2203. if (!$dns = dns_get_record($request.'.asn.cymru.com', DNS_TXT) OR !isset($dns[0]['txt']))
  2204. {
  2205. return FALSE;
  2206. }
  2207. $segments = array_map('trim', explode('|', $dns[0]['txt'], 5));
  2208. if (sizeof($segments) != 5)
  2209. {
  2210. return FALSE;
  2211. }
  2212. list($segments[4], $segments[5]) = explode(' ', $segments[4], 2);
  2213. $segments[5] = str_replace('_', '"', $segments[5]);
  2214. return array
  2215. (
  2216. 'asn' => $segments[0],
  2217. 'country' => $segments[1],
  2218. 'registrar' => $segments[2],
  2219. 'regdate' => $segments[3],
  2220. 'asname' => $segments[4],
  2221. 'description' => $segments[5],
  2222. );
  2223. }
  2224. /**
  2225. * Get PTR record for IPv4/IPv6 address
  2226. */
  2227. function get_host($hostname)
  2228. {
  2229. global $protocol;
  2230. if (filter_var($hostname, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE))
  2231. {
  2232. return $hostname;
  2233. }
  2234. $dns_a = (($dns_a = dns_get_record($hostname, DNS_A)) !== FALSE) ? $dns_a : array();
  2235. $dns_aaaa = (($dns_aaaa = dns_get_record($hostname, DNS_AAAA)) !== FALSE) ? $dns_aaaa : array();
  2236. $ip_array = array();
  2237. foreach (array_merge($dns_aaaa, $dns_a) as $record)
  2238. {
  2239. switch ($record['type'])
  2240. {
  2241. case 'A':
  2242. $ip_array[] = $record['ip'];
  2243. break;
  2244. case 'AAAA':
  2245. $ip_array[] = $record['ipv6'];
  2246. break;
  2247. case 'CNAME':
  2248. $ip_array = array_push($ip_array, get_host($record['target']));
  2249. break;
  2250. }
  2251. }
  2252. $ipv4_array = $ipv6_array = array();
  2253. foreach ($ip_array as $ip)
  2254. {
  2255. if (strpos($ip, ':') !== FALSE)
  2256. {
  2257. $ipv6_array[] = $ip;
  2258. }
  2259. else
  2260. {
  2261. $ipv4_array[] = $ip;
  2262. }
  2263. }
  2264. $ip_array = ($protocol == 'ipv6')
  2265. ? $ipv6_array
  2266. : $ipv4_array;
  2267. if (!$ipv6_array OR !$ipv4_array)
  2268. {
  2269. $ip_array = array_merge($ipv6_array, $ipv4_array);
  2270. }
  2271. if (!$ip_array OR (!$ipv4_array AND $protocol != 'ipv6'))
  2272. {
  2273. return FALSE;
  2274. }
  2275. return end($ip_array);
  2276. }
  2277. /**
  2278. * Get PTR record for IPv4/IPv6 address
  2279. */
  2280. function get_ptr($ip)
  2281. {
  2282. if (preg_match("/:/", $ip))
  2283. {
  2284. $unpack = unpack('H*hex', @inet_pton($ip));
  2285. $arpa = implode('.', array_reverse(str_split($unpack['hex']))).'.ip6.arpa';
  2286. }
  2287. else
  2288. {
  2289. $arpa = implode('.', array_reverse(explode('.', $ip))).'.in-addr.arpa.';
  2290. }
  2291. if (!$arpa OR !$dns = dns_get_record($arpa, DNS_PTR))
  2292. {
  2293. return $ip;
  2294. }
  2295. $ptr = array();
  2296. foreach ($dns as $record)
  2297. {
  2298. if ($record['type'] == 'PTR')
  2299. {
  2300. $ptr[] = $record['target'];
  2301. }
  2302. }
  2303. if (!$ptr)
  2304. {
  2305. return $ip;
  2306. }
  2307. return reset($ptr);
  2308. }
  2309. /**
  2310. * Group router list
  2311. */
  2312. function group_routers($array)
  2313. {
  2314. $return = array();
  2315. foreach ($array as $key => $value)
  2316. {
  2317. if (isset($value['group']) AND $value['group'] != '')
  2318. {
  2319. $return[$value['group']][$key] = $value;
  2320. continue;
  2321. }
  2322. $return[''][$key] = $value;
  2323. }
  2324. return $return;
  2325. }
  2326. // ------------------------------------------------------------------------
  2327. /**
  2328. * Telnet class
  2329. *
  2330. * Used to execute remote commands via telnet connection
  2331. * Usess sockets functions and fgetc() to process result
  2332. *
  2333. * All methods throw Exceptions on error
  2334. *
  2335. * Written by Dalibor Andzakovic <dali@swerve.co.nz>
  2336. * Based on the code originally written by Marc Ennaji and extended by
  2337. * Matthias Blaser <mb@adfinis.ch>
  2338. *
  2339. * Modified by Dmitry Shin <dmitry.s@hsdn.org>, 2014
  2340. */
  2341. class Telnet
  2342. {
  2343. private $host;
  2344. private $port;
  2345. private $timeout;
  2346. private $socket = NULL;
  2347. private $buffer = NULL;
  2348. private $prompt;
  2349. private $errno;
  2350. private $errstr;
  2351. private $header1;
  2352. private $header2;
  2353. public $NULL;
  2354. public $DC1;
  2355. public $WILL;
  2356. public $WONT;
  2357. public $DO;
  2358. public $DONT;
  2359. public $IAC;
  2360. public $LINEMODE;
  2361. const TELNET_ERROR = FALSE;
  2362. const TELNET_OK = TRUE;
  2363. /**
  2364. * Constructor. Initialises host, port and timeout parameters
  2365. * defaults to localhost port 23 (standard telnet port)
  2366. *
  2367. * @access public
  2368. * @param string $host Host name or IP addres
  2369. * @param int $port TCP port number
  2370. * @param int $timeout Connection timeout in seconds
  2371. * @return void
  2372. */
  2373. public function __construct($host = '127.0.0.1', $port = '23', $timeout = 10, $prompt = '/[^\s]{2,}[\$%>] {0,1}$/')
  2374. {
  2375. $this->default_prompt = $prompt;
  2376. $this->setPrompt();
  2377. $this->host = $host;
  2378. $this->port = $port;
  2379. $this->timeout = $timeout;
  2380. $this->header1 =
  2381. chr(0xFF).chr(0xFB).chr(0x1F). // 0xFF 0xFB 0x1F - WILL command - NEGOTIATE-WINDOW-SIZE
  2382. chr(0xFF).chr(0xFB).chr(0x20). // 0xFF 0xFB 0x20 - WILL command - TERMINAL-SPEED
  2383. chr(0xFF).chr(0xFB).chr(0x18). // 0xFF 0xFB 0x18 - WILL command - TERMINAL-TYPE
  2384. chr(0xFF).chr(0xFB).chr(0x27). // 0xFF 0xFB 0x27 - WILL command - NEW-ENVIRON
  2385. chr(0xFF).chr(0xFD).chr(0x01). // 0xFF 0xFD 0x01 - DO command - ECHO
  2386. chr(0xFF).chr(0xFB).chr(0x03). // 0xFF 0xFB 0x03 - WILL command - SUPPRESS-GO-AHEAD
  2387. chr(0xFF).chr(0xFD).chr(0x03). // 0xFF 0xFD 0x03 - DO command - SUPPRESS-GO-AHEAD
  2388. chr(0xFF).chr(0xFC).chr(0x23). // 0xFF 0xFC 0x23 - WON'T command - X-DISPLAY-LOCATION
  2389. chr(0xFF).chr(0xFC).chr(0x24). // 0xFF 0xFC 0x24 - WON'T command - ENVIRONMENT
  2390. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2391. chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18). // NEGOTIATE-WINDOW-SIZE
  2392. // <Width1>=0 <Width0>=80 <Height1>=0 <Height0>=24
  2393. chr(0xFF).chr(0xF0). // 0xFF 0xF0 - SE command
  2394. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2395. chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).
  2396. chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).
  2397. chr(0x34).chr(0x30).chr(0x30). // TERMINAL-SPEED - 38400,38400
  2398. chr(0xFF).chr(0xF0). // 0xFF 0xF0 - SE command
  2399. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2400. chr(0x27).chr(0x00). // NEW-ENVIRON <IS> <empty>
  2401. chr(0xFF).chr(0xF0). // 0xFF 0xF0 - SE command
  2402. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2403. chr(0x18).chr(0x00).chr(0x58).chr(0x54).chr(0x45).
  2404. chr(0x52).chr(0x4D). // TERMINAL-TYPE: <IS> XTERM
  2405. chr(0xFF).chr(0xF0); // 0xFF 0xF0 - SE command
  2406. $this->header2 =
  2407. chr(0xFF).chr(0xFC).chr(0x01). // 0xFF 0xFC 0x01 - WON'T command - ECHO
  2408. chr(0xFF).chr(0xFC).chr(0x22). // 0xFF 0xFC 0x22 - WON'T command - LINEMODE
  2409. chr(0xFF).chr(0xFE).chr(0x05). // 0xFF 0xFE 0x05 - DON'T command - STATUS
  2410. chr(0xFF).chr(0xFC).chr(0x21); // 0xFF 0xFC 0x21 - WON'T command - TOGGLE-FLOW-CONTROL
  2411. $this->NULL = chr(0);
  2412. $this->DC1 = chr(17);
  2413. $this->WILL = chr(251);
  2414. $this->WONT = chr(252);
  2415. $this->DO = chr(253);
  2416. $this->DONT = chr(254);
  2417. $this->IAC = chr(255);
  2418. $this->LINEMODE = chr(34);
  2419. $this->connect();
  2420. }
  2421. /**
  2422. * Destructor. Cleans up socket connection and command buffer
  2423. *
  2424. * @access public
  2425. * @return void
  2426. */
  2427. public function __destruct()
  2428. {
  2429. $this->disconnect();
  2430. $this->buffer = NULL;
  2431. }
  2432. /**
  2433. * Attempts connection to remote host. Returns TRUE if sucessful.
  2434. *
  2435. * @access public
  2436. * @return bool
  2437. */
  2438. public function connect()
  2439. {
  2440. if (!preg_match('/([0-9]{1,3}\\.){3,3}[0-9]{1,3}/', $this->host))
  2441. {
  2442. $ip = gethostbyname($this->host);
  2443. if ($this->host == $ip)
  2444. {
  2445. throw new Exception("Cannot resolve ".$this->host.".");
  2446. }
  2447. else
  2448. {
  2449. $this->host = $ip;
  2450. }
  2451. }
  2452. $this->socket = @fsockopen($this->host, $this->port, $this->errno, $this->errstr, $this->timeout);
  2453. $this->write($this->header1, FALSE);
  2454. usleep(100800);
  2455. $this->write($this->header2, FALSE);
  2456. usleep(100800);
  2457. if (!$this->socket)
  2458. {
  2459. throw new Exception("Cannot connect to ".$this->host." on port ".$this->port.".");
  2460. }
  2461. return self::TELNET_OK;
  2462. }
  2463. /**
  2464. * Closes IP socket
  2465. *
  2466. * @access public
  2467. * @return bool
  2468. */
  2469. public function disconnect()
  2470. {
  2471. if ($this->socket)
  2472. {
  2473. $this->write('quit');
  2474. if (!fclose($this->socket))
  2475. {
  2476. throw new Exception("Error while closing telnet socket.");
  2477. }
  2478. $this->socket = NULL;
  2479. }
  2480. return self::TELNET_OK;
  2481. }
  2482. /**
  2483. * Executes command and returns a string with result.
  2484. * This method is a wrapper for lower level private methods
  2485. *
  2486. * @access public
  2487. * @param string $command Command to execute
  2488. * @return string Command result
  2489. */
  2490. public function exec($command)
  2491. {
  2492. $this->write($command);
  2493. $this->waitPrompt();
  2494. return $this->getBuffer();
  2495. }
  2496. /**
  2497. * Attempts login to remote host.
  2498. * This method is a wrapper for lower level private methods and should be
  2499. * modified to reflect telnet implementation details like login/password
  2500. * and line prompts. Defaults to standard unix non-root prompts
  2501. *
  2502. * @access public
  2503. * @param string $username Username
  2504. * @param string $password Password
  2505. * @return bool
  2506. */
  2507. public function login($username = FALSE, $password = FALSE)
  2508. {
  2509. try
  2510. {
  2511. if ($username)
  2512. {
  2513. $this->setPrompt('/(ogin|name|word):.*$/');
  2514. $this->waitPrompt();
  2515. $this->write($username);
  2516. }
  2517. if ($password)
  2518. {
  2519. $this->setPrompt('/word:.*$/');
  2520. $this->waitPrompt();
  2521. $this->write($password);
  2522. }
  2523. $this->setPrompt();
  2524. $this->waitPrompt();
  2525. }
  2526. catch (Exception $e)
  2527. {
  2528. throw new Exception("Login failed.");
  2529. }
  2530. return self::TELNET_OK;
  2531. }
  2532. /**
  2533. * Sets the string of characters to respond to.
  2534. * This should be set to the last character of the command line prompt
  2535. *
  2536. * @access public
  2537. * @param string $s String to respond to
  2538. * @return bool
  2539. */
  2540. public function setPrompt($s = '')
  2541. {
  2542. $this->prompt = $this->default_prompt;
  2543. if ($s != '')
  2544. {
  2545. $this->prompt = $s;
  2546. }
  2547. return self::TELNET_OK;
  2548. }
  2549. /**
  2550. * Gets character from the socket
  2551. *
  2552. * @access public
  2553. * @return void
  2554. */
  2555. public function getc()
  2556. {
  2557. @socket_set_timeout($this->socket, $this->timeout);
  2558. return fgetc($this->socket);
  2559. }
  2560. /**
  2561. * Clears internal command buffer
  2562. *
  2563. * @access public
  2564. * @return void
  2565. */
  2566. public function clearBuffer()
  2567. {
  2568. $this->buffer = '';
  2569. }
  2570. /**
  2571. * Reads characters from the socket and adds them to command buffer.
  2572. * Handles telnet control characters. Stops when prompt is ecountered.
  2573. *
  2574. * @access public
  2575. * @param string $prompt
  2576. * @return bool
  2577. */
  2578. public function readTo($prompt)
  2579. {
  2580. if (!$this->socket)
  2581. {
  2582. throw new Exception("Telnet connection closed.");
  2583. }
  2584. $this->clearBuffer();
  2585. do
  2586. {
  2587. $c = $this->getc();
  2588. if ($c === false)
  2589. {
  2590. throw new Exception("Couldn't find the requested : '".$prompt."', it was not in the data returned from server.");
  2591. }
  2592. if ($c == $this->IAC)
  2593. {
  2594. if ($this->negotiateTelnetOptions())
  2595. {
  2596. continue;
  2597. }
  2598. }
  2599. $this->buffer .= $c;
  2600. if (@preg_match($prompt, $this->buffer))
  2601. {
  2602. return self::TELNET_OK;
  2603. }
  2604. }
  2605. while ($c != $this->NULL OR $c != $this->DC1);
  2606. }
  2607. /**
  2608. * Write command to a socket
  2609. *
  2610. * @access public
  2611. * @param string $buffer Stuff to write to socket
  2612. * @param bool $addNewLine Default true, adds newline to the command
  2613. * @return bool
  2614. */
  2615. public function write($buffer = '', $addNewLine = TRUE)
  2616. {
  2617. if (!$this->socket)
  2618. {
  2619. throw new Exception("Telnet connection closed.");
  2620. }
  2621. // clear buffer from last command
  2622. $this->clearBuffer();
  2623. if ($addNewLine == true)
  2624. {
  2625. $buffer .= "\r\n";
  2626. }
  2627. if (!fwrite($this->socket, $buffer) < 0)
  2628. {
  2629. throw new Exception("Error writing to socket.");
  2630. }
  2631. return self::TELNET_OK;
  2632. }
  2633. /**
  2634. * Returns the content of the command buffer
  2635. *
  2636. * @access public
  2637. * @return string Content of the command buffer
  2638. */
  2639. public function getBuffer()
  2640. {
  2641. return $this->buffer;
  2642. }
  2643. /**
  2644. * Telnet control character magic
  2645. *
  2646. * @access public
  2647. * @param string $command Character to check
  2648. * @return bool
  2649. */
  2650. public function negotiateTelnetOptions()
  2651. {
  2652. $c = $this->getc();
  2653. if ($c != $this->IAC)
  2654. {
  2655. if (($c == $this->DO) OR ($c == $this->DONT))
  2656. {
  2657. $opt = $this->getc();
  2658. fwrite($this->socket, $this->IAC.$this->WONT.$opt);
  2659. }
  2660. else if (($c == $this->WILL) OR ($c == $this->WONT))
  2661. {
  2662. $opt = $this->getc();
  2663. fwrite($this->socket, $this->IAC.$this->DONT.$opt);
  2664. }
  2665. }
  2666. else
  2667. {
  2668. throw new Exception('Error: Something Wicked Happened.');
  2669. }
  2670. return self::TELNET_OK;
  2671. }
  2672. /**
  2673. * Reads socket until prompt is encountered
  2674. *
  2675. * @access public
  2676. */
  2677. public function waitPrompt()
  2678. {
  2679. return $this->readTo($this->prompt);
  2680. }
  2681. } // class Telnet
  2682. /* End of file */