index.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101
  1. <?php
  2. /**
  3. * HSDN Looking Glass version 1.2.2b
  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 protocol bgp %s terse',
  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 protocol bgp %s terse',
  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; // terse
  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">
  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 ($return_buffer)
  748. {
  749. return $lines;
  750. }
  751. if ($lines AND ($line = parse_out($lines)))
  752. {
  753. print $line;
  754. }
  755. if (empty($line) AND $is_exception == FALSE)
  756. {
  757. print '<p class="error">Command failed.</p>';
  758. }
  759. flush();
  760. }
  761. /**
  762. * Parse output contents
  763. */
  764. function parse_out($output, $check = FALSE)
  765. {
  766. global $_CONFIG, $router, $protocol, $os, $command, $exec, $query, $index, $lastip, $best, $count, $str_in, $ros;
  767. $output = str_replace("\r\n", "\n", $output);
  768. // MikroTik
  769. if (preg_match("/^\/(ip|ipv6) route print detail/i", $exec) AND $os == 'mikrotik')
  770. {
  771. if ($check)
  772. {
  773. return FALSE;
  774. }
  775. $output_parts = explode("\n" , trim($output), ($protocol != 'ipv6' ? 4 : 3));
  776. if (!isset($output_parts[2]))
  777. {
  778. return 'Records for '.strip_tags($query).' is not found';
  779. }
  780. $summary_parts = explode("\n\n" , $output_parts[($protocol != 'ipv6' ? 3 : 2)]);
  781. $output = implode("\n", array_slice($output_parts, 0, ($protocol != 'ipv6' ? 3 : 2)))."\n\n";
  782. foreach ($summary_parts as $summary_part)
  783. {
  784. $data_exp = explode(' ', trim($summary_part), 3);
  785. $summary_part = preg_replace_callback(
  786. "/bgp-as-path=\"([^\"]+)\"/x",
  787. function ($matches) {
  788. return stripslashes('bgp-as-path=\"'.link_as($matches[1]).'\"');
  789. },
  790. $summary_part
  791. );
  792. if (strpos($data_exp[1], 'A') !== FALSE)
  793. {
  794. $output .= '<span style="color:#ff0000">'.$summary_part."</span>\n\n";
  795. }
  796. else
  797. {
  798. $output .= $summary_part."\n\n";
  799. }
  800. }
  801. return $output;
  802. }
  803. // MikroTik
  804. if (preg_match("/^\/routing bgp advertisements print/i", $exec) AND $os == 'mikrotik')
  805. {
  806. return preg_replace_callback(
  807. "/^(.{8}\s)([\d\.A-Fa-f:\/]+)(\s+)/",
  808. function ($matches) {
  809. return $matches[1].link_command("bgp", $matches[2]).$matches[3];
  810. },
  811. $output
  812. );
  813. }
  814. // MikroTik
  815. if (preg_match("/^\/(ip|ipv6) route print/i", $exec) AND $os == 'mikrotik')
  816. {
  817. return preg_replace_callback(
  818. "/(^[\s\d]+)(\s+[A-z]+\s+)([\d\.A-Fa-f:\/]+)(\s+)/",
  819. function ($matches) {
  820. return $matches[1].$matches[2].link_command("bgp", $matches[3]).$matches[4];
  821. },
  822. $output
  823. );
  824. }
  825. // MikroTik
  826. if (preg_match("/^\/routing bgp peer print status/i", $exec) AND $os == 'mikrotik')
  827. {
  828. if ($check)
  829. {
  830. return FALSE;
  831. }
  832. $output_parts = explode("\n" , trim($output), 2);
  833. if (!isset($output_parts[1]))
  834. {
  835. return 'Records for '.strip_tags($query).' is not found';
  836. }
  837. $summary_parts = explode("\n\n" , $output_parts[1]);
  838. $table_array[] = array
  839. (
  840. 'remote-address' => 'Neighbor',
  841. 'name' => 'PeerName',
  842. 'remote-id' => 'RemoteID',
  843. 'remote-as' => 'AS',
  844. 'withdrawn-received' => 'MsgRcvd',
  845. 'updates-received' => 'MsgSent',
  846. 'uptime' => 'Up/Down',
  847. 'state' => 'State',
  848. 'prefix-count' => 'PfxRcd',
  849. 'updates-sent' => 'PfxSnd',
  850. );
  851. foreach ($summary_parts as $summary_part)
  852. {
  853. $data_exp = explode(' ', trim($summary_part), 3);
  854. if (sizeof($data_exp) != 3)
  855. {
  856. continue;
  857. }
  858. $data = parse_list($data_exp[2]);
  859. $table_array[] = array
  860. (
  861. 'remote-address' => isset($data['remote-address']) ? link_whois($data['remote-address']) : '',
  862. 'name' => isset($data['name']) ? $data['name'] : '',
  863. 'remote-id' => isset($data['remote-id']) ? $data['remote-id'] : '',
  864. 'remote-as' => isset($data['remote-as']) ? link_as($data['remote-as']) : '',
  865. 'withdrawn-received' => isset($data['withdrawn-received']) ? $data['withdrawn-received'] : '',
  866. 'updates-received' => isset($data['updates-received']) ? $data['updates-received'] : '',
  867. 'uptime' => isset($data['uptime']) ? $data['uptime'] : '',
  868. 'state' => $data_exp[1],
  869. 'prefix-count' => (isset($data['remote-address']) AND isset($data['prefix-count']))
  870. ? link_command('routes', $data['remote-address'], $data['prefix-count'])
  871. : '',
  872. 'updates-sent' => (isset($data['name']) AND isset($data['updates-sent']))
  873. ? link_command('advertised-routes', $data['name'], $data['updates-sent'])
  874. : '',
  875. );
  876. }
  877. return
  878. str_replace('Flags', 'State', $output_parts[0])."\n\n".
  879. build_table($table_array)."\n\n".
  880. 'Total number of neighbors '.(sizeof($table_array) - 1);
  881. }
  882. // MikroTik
  883. if (preg_match("/^\/ping/i", $exec) AND $os == 'mikrotik')
  884. {
  885. if (preg_match('/^HOST/', $output) AND $index == 0)
  886. {
  887. $index++;
  888. return 'PING '.$query.' ('.get_ptr($query).'): 56 data bytes'."\n";
  889. }
  890. if ($index > 0)
  891. {
  892. $exp = explode(' ', preg_replace('/[\s\t]+/', ' ', trim($output)));
  893. $exp = array_slice($exp, 0, 4);
  894. if (!$exp OR $exp[0] == '' OR $exp[0] == 'HOST' OR (isset($exp[1]) AND $exp[1] == 'timeout'))
  895. {
  896. return;
  897. }
  898. if (preg_match('/sent=([0-9]+) received=([0-9]+) packet-loss=([^ ]+)/', $output, $stat))
  899. {
  900. $return = "\n".'--- '.$query.' ping statistics ---'."\n".
  901. $stat[1].' packets transmitted, '.$stat[2].' packets received, '.trim($stat[3]).' packet loss'."\n";
  902. if (preg_match('/min-rtt=([0-9]+)ms avg-rtt=([0-9]+)ms/', $output, $stat2))
  903. {
  904. $return .= 'round-trip min/avg/max = '.$stat2[1].'/'.$stat2[2];
  905. }
  906. if (preg_match('/max-rtt=([0-9]+)ms/', $output, $stat3))
  907. {
  908. $return .= '/'.$stat3[1];
  909. }
  910. return $return;
  911. }
  912. // Пинг больше 99, отдача max-rtt отдельной строкой
  913. if (preg_match('/max-rtt=([0-9]+)ms/', $output, $stat3))
  914. {
  915. $return = '/'.$stat3[1];
  916. return $return;
  917. }
  918. $index++;
  919. return $exp[1].' bytes from '.$exp[0].': icmp_seq='.intval($index-1).' ttl='.$exp[2].' time='.$exp[3]."\n";
  920. }
  921. }
  922. // MikroTik
  923. if (preg_match("/^\/tool trace/i", $exec) AND $os == 'mikrotik' AND $ros >= 6)
  924. {
  925. if (preg_match('/^ # ADDRESS/', $output) AND $index == 0)
  926. {
  927. $index++;
  928. return 'traceroute to '.$query.' ('.get_ptr($query).'), 64 hops max, 60 byte packets'."\n";
  929. }
  930. if ($index > 0)
  931. {
  932. $exp = explode(' ', preg_replace('/[\s\t]+/', ' ', trim($output)));
  933. $exp = array_slice($exp, 0, 9);
  934. if (!$exp OR empty($exp[0]) OR (sizeof($exp) == 4 AND isset($exp[3]) AND $exp[3] != 'timeout'))
  935. {
  936. return;
  937. }
  938. $new_exp[0] = (strlen($exp[0]) < 2) ? ' '.$exp[0] : $exp[0];
  939. if ($exp[3] == 'timeout')
  940. {
  941. $new_exp[1] = '* * *';
  942. $new_exp = array_slice($new_exp, 0, 2);
  943. }
  944. else
  945. {
  946. $radb = get_radb($exp[1]);
  947. $new_exp[1] = get_ptr($exp[1]);
  948. $new_exp[2] = '('.$exp[1].')';
  949. $new_exp[3] = '['.(isset($radb['origin']) ? 'AS '.link_as($radb['origin']) : '').']';
  950. $new_exp[4] = $exp[5].'ms';
  951. $new_exp[5] = $exp[6].'ms';
  952. $new_exp[6] = $exp[7].'ms';
  953. }
  954. if ($index >= 64)
  955. {
  956. return TRUE;
  957. }
  958. $str = implode(' ', $new_exp)."\r\n";
  959. if (@in_array($str, $str_in))
  960. {
  961. return;
  962. }
  963. $str_in[] = $str;
  964. $index++;
  965. return $str;
  966. }
  967. }
  968. // MikroTik
  969. if (preg_match("/^\/tool trace/i", $exec) AND $os == 'mikrotik' AND $ros <= 5)
  970. {
  971. if (preg_match('/^ # ADDRESS/', $output) AND $index == 0)
  972. {
  973. $index++;
  974. return 'traceroute to '.$query.' ('.get_ptr($query).'), 64 hops max, 60 byte packets'."\n";
  975. }
  976. if ($index > 0)
  977. {
  978. $exp = explode(' ', preg_replace('/[\s\t]+/', ' ', trim($output)));
  979. $exp = array_slice($exp, 0, 5);
  980. if (!$exp OR empty($exp[0]))
  981. {
  982. return;
  983. }
  984. $exp[0] = (strlen($exp[0]) < 2) ? ' '.$exp[0] : $exp[0];
  985. if ($exp[1] == '0.0.0.0' OR $exp[1] = '::')
  986. {
  987. $exp[1] = '* * *';
  988. $exp = array_slice($exp, 0, 2);
  989. }
  990. else
  991. {
  992. $radb = get_radb($exp[1]);
  993. $exp[6] = $exp[4];
  994. $exp[5] = $exp[3];
  995. $exp[4] = $exp[2];
  996. $exp[3] = '['.(isset($radb['origin']) ? 'AS '.link_as($radb['origin']) : '').']';
  997. $exp[2] = '('.$exp[1].')';
  998. $exp[1] = get_ptr($exp[1]);
  999. }
  1000. if ($index >= 64)
  1001. {
  1002. return TRUE;
  1003. }
  1004. $index++;
  1005. return implode(' ', $exp)."\r\n";
  1006. }
  1007. }
  1008. // Other OS parsers
  1009. if (preg_match('/^show bgp ipv6 unicast/i', $exec) AND $os = 'ios')
  1010. {
  1011. $output = str_replace('% Incomplete command.', '<p class="error">Please use network prefix in Parameter.</p>', $output);
  1012. }
  1013. if ($exec == 'show ip bgp summary')
  1014. {
  1015. $output = preg_replace_callback(
  1016. "/( local AS number )(\d+)/",
  1017. function ($matches) {
  1018. return $matches[1].link_as($matches[2]);
  1019. },
  1020. $output
  1021. );
  1022. // JunOS
  1023. if ($os == 'junos')
  1024. {
  1025. $output = preg_replace_callback(
  1026. "/^([\dA-Fa-f:\.]+\s+)(\d+)/",
  1027. function ($matches) {
  1028. return $matches[1].link_as($matches[2]);
  1029. },
  1030. $output
  1031. );
  1032. }
  1033. else
  1034. {
  1035. $output = preg_replace_callback(
  1036. "/^([\d\.]+\s+\d+\s+)(\d+)/",
  1037. function ($matches) {
  1038. return $matches[1].link_as($matches[2]);
  1039. },
  1040. $output
  1041. );
  1042. }
  1043. $output = preg_replace_callback(
  1044. "/^(\d+\.\d+\.\d+\.\d+)(\s+.*\s+)([1-9]\d*)\n$/",
  1045. function ($matches) {
  1046. return $matches[1].$matches[2].link_command("routes", $matches[1], $matches[3])."\n";
  1047. },
  1048. $output
  1049. );
  1050. $output = preg_replace_callback(
  1051. "/^(\d+\.\d+\.\d+\.\d+)(\s+)/",
  1052. function ($matches) {
  1053. return link_command("bgp", "neighbors+".$matches[1], $matches[1]).$matches[2];
  1054. },
  1055. $output
  1056. );
  1057. // IPv6 neighbours
  1058. $output = preg_replace_callback(
  1059. "/^(.{15} 4\s+)(\d+)/",
  1060. function ($matches) {
  1061. return $matches[1].link_as($matches[2]);
  1062. },
  1063. $output
  1064. );
  1065. $output = preg_replace_callback(
  1066. "/^([\dA-Fa-f]*:[\dA-Fa-f:]*)(\s+)/",
  1067. function ($matches) {
  1068. return link_command("bgp", "neighbors+".$matches[1], $matches[1]).$matches[2];
  1069. },
  1070. $output
  1071. );
  1072. $output = preg_replace_callback(
  1073. "/^([\dA-Fa-f]*:[\dA-Fa-f:]*)\n$/",
  1074. function ($matches) {
  1075. return link_command("bgp", "neighbors+".$matches[1], $matches[1])."\n";
  1076. },
  1077. $output
  1078. );
  1079. return $output;
  1080. }
  1081. if ($exec == 'show ipv6 bgp summary' OR $exec == 'show bgp ipv6 unicast summary')
  1082. {
  1083. $output = preg_replace_callback(
  1084. "/^(.{15} 4\s+)(\d+)/",
  1085. function ($matches) {
  1086. return $matches[1].link_as($matches[2]);
  1087. },
  1088. $output
  1089. );
  1090. if (preg_match("/^([\dA-Fa-f]*:[\dA-Fa-f:]*)\s+4\s+/", $output, $lastip_exp))
  1091. {
  1092. $lastip = $lastip_exp[1];
  1093. $output = preg_replace_callback(
  1094. "/^(.{15} 4\s+)(\d+)/",
  1095. function ($matches) {
  1096. return $matches[1].link_as($matches[2]);
  1097. },
  1098. $output
  1099. );
  1100. $output = preg_replace_callback(
  1101. "/^([\dA-Fa-f:]+)(\s+.*\s+)([1-9]\d*)$/",
  1102. function ($matches) {
  1103. global $lastip;
  1104. return link_command("routes", $lastip, $matches[3]);
  1105. },
  1106. $output
  1107. );
  1108. $output = preg_replace_callback(
  1109. "/^([\dA-Fa-f:]+)(\s+)/",
  1110. function ($matches) {
  1111. return link_command("routes", $matches[1]).$matches[2];
  1112. },
  1113. $output
  1114. );
  1115. unset($lastip);
  1116. }
  1117. if (preg_match("/^([\dA-Fa-f:]+)\n$/", $output, $lastip_exp))
  1118. {
  1119. $lastip = $lastip_exp[1];
  1120. $output = preg_replace_callback(
  1121. "/^([\dA-Fa-f:]+)/",
  1122. function ($matches) {
  1123. return link_command("routes", $matches[1]);
  1124. },
  1125. $output
  1126. );
  1127. }
  1128. if (isset($lastip) AND preg_match("/^(\s+.*\s+)([1-9]\d*)\n$/", $output))
  1129. {
  1130. $output = preg_replace_callback(
  1131. "/^(\s+.*\s+)([1-9]\d*)\n$/",
  1132. function ($matches) {
  1133. global $lastip;
  1134. return $matches[1].link_command("routes", $lastip, $matches[2])."\n";
  1135. },
  1136. $output
  1137. );
  1138. unset($lastip);
  1139. }
  1140. return $output;
  1141. }
  1142. if ($exec == 'show bgp summary')
  1143. {
  1144. // JunOS
  1145. if (preg_match("/^([\dA-Fa-f:][\d\.A-Fa-f:]+)\s+/", $output, $lastip_exp))
  1146. {
  1147. $lastip = $lastip_exp[1];
  1148. // IPv4
  1149. $output = preg_replace_callback(
  1150. "/^(\d+\.\d+\.\d+\.\d+)(\s+.*\s+)([1-9]\d*)(\s+\d+\s+\d+\s+\d+\s+\d+\s+[\d:]+\s+)(\d+)\/(\d+)\/(\d+)(\s+)/",
  1151. function ($matches) {
  1152. return $matches[1].$matches[2].
  1153. link_command("routes", $matches[1], $matches[3]).$matches[4].
  1154. link_command("routes", $matches[1], $matches[5])."/".
  1155. link_command("routes", $matches[1], $matches[6])."/".
  1156. link_command("routes", $matches[1], $matches[7]).$matches[8];
  1157. },
  1158. $output
  1159. );
  1160. // IPv4/IPv6
  1161. $output = preg_replace_callback(
  1162. "/^([\dA-Fa-f:][\d\.A-Fa-f:]+\s+)(\d+)(\s+)/",
  1163. function ($matches) {
  1164. return $matches[1].link_as($matches[2]).$matches[3];
  1165. },
  1166. $output
  1167. );
  1168. $output = preg_replace_callback(
  1169. "/^([\dA-Fa-f:][\d\.A-Fa-f:]+)(\s+)/",
  1170. function ($matches) {
  1171. return link_command("bgp", "neighbors+".$matches[1], $matches[1]).$matches[2];
  1172. },
  1173. $output
  1174. );
  1175. }
  1176. if (isset($lastip) AND preg_match("/( [^:]+: )(\d+)\/(\d+)\/(\d+)$/", $output))
  1177. {
  1178. $output = preg_replace_callback(
  1179. "/^( [^:]+: )(\d+)\/(\d+)\/(\d+)\n$/",
  1180. function ($matches) {
  1181. global $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) {
  1340. global $ip;
  1341. return $matches[1].link_command("bgp", "neighbors+".$ip."+advertised-routes+".$matches[2], $matches[2]).$matches[3];
  1342. },
  1343. $output
  1344. );
  1345. return $output;
  1346. }
  1347. if (preg_match("/^show ip bgp n\w*\s+([\d\.]+)/i", $exec) OR
  1348. preg_match("/^show ip bgp n\w*$/i", $exec))
  1349. {
  1350. if (!isset($lastip) AND preg_match("/^BGP neighbor is ([\d\.]+),/", $output, $lastip_exp))
  1351. {
  1352. $lastip = $lastip_exp[1];
  1353. }
  1354. $output = preg_replace_callback(
  1355. "/(Prefix )(advertised)( [1-9]\d*)/",
  1356. function ($matches) {
  1357. global $lastip;
  1358. return $matches[1].link_command("advertised-routes", $lastip, $matches[2]).$matches[3];
  1359. },
  1360. $output
  1361. );
  1362. $output = preg_replace_callback(
  1363. "/( Prefixes Total: )(\d+)( )/",
  1364. function ($matches) {
  1365. global $lastip;
  1366. return $matches[1].link_command("advertised-routes", $lastip, $matches[2]).$matches[3];
  1367. },
  1368. $output
  1369. );
  1370. $output = preg_replace_callback(
  1371. "/(prefixes )(received)( [1-9]\d*)/",
  1372. function ($matches) {
  1373. global $lastip;
  1374. return $matches[1].link_command("routes", $lastip, $matches[2]).$matches[3];
  1375. },
  1376. $output
  1377. );
  1378. $output = preg_replace_callback(
  1379. "/( Prefixes Current: \s+)(\d+)(\s+)(\d+)/",
  1380. function ($matches) {
  1381. global $lastip;
  1382. return $matches[1].
  1383. link_command("advertised-routes", $lastip, $matches[2]).$matches[3].
  1384. link_command("routes", $lastip, $matches[4]);
  1385. },
  1386. $output
  1387. );
  1388. $output = preg_replace_callback(
  1389. "/(\s+)(Received)( prefixes:\s+[1-9]\d*)/",
  1390. function ($matches) {
  1391. global $lastip;
  1392. return $matches[1].link_command("routes", $lastip, $matches[2]).$matches[3];
  1393. },
  1394. $output
  1395. );
  1396. $output = preg_replace_callback(
  1397. "/( Saved \(soft-reconfig\):\s+)(\d+|n\/a)(\s+)(\d+)/",
  1398. function ($matches) {
  1399. global $lastip;
  1400. return $matches[1].$matches[2].$matches[3].link_command("received-routes", $lastip, $matches[4]);
  1401. },
  1402. $output
  1403. );
  1404. $output = preg_replace_callback(
  1405. "/( [1-9]\d* )(accepted)( prefixes)/",
  1406. function ($matches) {
  1407. global $lastip;
  1408. return $matches[1].link_command("routes", $lastip, $matches[2]).$matches[3];
  1409. },
  1410. $output
  1411. );
  1412. $output = preg_replace_callback(
  1413. "/^( [1-9]\d* )(accepted|denied but saved)( prefixes consume \d+ bytes)/",
  1414. function ($matches) {
  1415. global $lastip;
  1416. return $matches[1].link_command("received-routes", $lastip, $matches[2]).$matches[3];
  1417. },
  1418. $output
  1419. );
  1420. $output = preg_replace_callback(
  1421. "/^(BGP neighbor is )(\d+\.\d+\.\d+\.\d+)(,)/",
  1422. function ($matches) {
  1423. return $matches[1].link_whois($matches[2]).$matches[3];
  1424. },
  1425. $output
  1426. );
  1427. $output = preg_replace("/^( Description: )(.*)$/", '\\1<b>\\2</b>', $output);
  1428. $output = preg_replace_callback(
  1429. "/(,\s+remote AS )(\d+)(,)/",
  1430. function ($matches) {
  1431. return $matches[1].link_as($matches[2]).$matches[3];
  1432. },
  1433. $output
  1434. );
  1435. $output = preg_replace_callback(
  1436. "/(, local AS )(\d+)(,)/",
  1437. function ($matches) {
  1438. return $matches[1].link_as($matches[2]).$matches[3];
  1439. },
  1440. $output
  1441. );
  1442. $output = preg_replace_callback(
  1443. "/( update prefix filter list is )(\S+)/",
  1444. function ($matches) {
  1445. return $matches[1].link_command("bgp", "prefix-list+".$matches[2], $matches[2]);
  1446. },
  1447. $output
  1448. );
  1449. $output = preg_replace_callback(
  1450. "/(Route map for \S+ advertisements is\s+:?\*?)(\S+)/",
  1451. function ($matches) {
  1452. return $matches[1].link_command("bgp", "route-map+".$matches[2], $matches[2]);
  1453. },
  1454. $output
  1455. );
  1456. return $output;
  1457. }
  1458. if (preg_match("/^show (ipv6 bgp|bgp ipv6) n\w*\s+([\dA-Fa-f:]+)/i", $exec, $ip_exp))
  1459. {
  1460. $ip = $ip_exp[1];
  1461. $output = preg_replace_callback(
  1462. "/(Prefix )(advertised)( [1-9]\d*)/",
  1463. function ($matches) {
  1464. global $ip;
  1465. return $matches[1].link_command("advertised-routes", "'.$ip.'", $matches[2]).$matches[3];
  1466. },
  1467. $output
  1468. );
  1469. $output = preg_replace_callback(
  1470. "/( [1-9]\d* )(accepted)( prefixes)/",
  1471. function ($matches) {
  1472. global $ip;
  1473. return $matches[1].link_command("routes", $ip, $matches[2]).$matches[3];
  1474. },
  1475. $output
  1476. );
  1477. $output = preg_replace("/^( Description: )(.*)$/", '\\1<b>\\2</b>', $output);
  1478. $output = preg_replace_callback(
  1479. "/(\s+remote AS )(\d+)(,)/",
  1480. function ($matches) {
  1481. return $matches[1].link_as($matches[2]).$matches[3];
  1482. },
  1483. $output
  1484. );
  1485. $output = preg_replace_callback(
  1486. "/(\s+local AS )(\d+)(,)/",
  1487. function ($matches) {
  1488. return $matches[1].link_as($matches[2]).$matches[3];
  1489. },
  1490. $output
  1491. );
  1492. $output = preg_replace_callback(
  1493. "/( update prefix filter list is )(\S+)/",
  1494. function ($matches) {
  1495. return $matches[1].link_command("bgp", "prefix-list+".$matches[2], $matches[2]);
  1496. },
  1497. $output
  1498. );
  1499. $output = preg_replace_callback(
  1500. "/(Route map for \S+ advertisements is\s+:?\*?)(\S+)/",
  1501. function ($matches) {
  1502. return $matches[1].link_command("bgp", "route-map+".$matches[2], $matches[2]);
  1503. },
  1504. $output
  1505. );
  1506. return $output;
  1507. }
  1508. if (preg_match("/^show bgp n\w*\s+([\d\.A-Fa-f:]+)/i", $exec, $ip_exp))
  1509. {
  1510. $ip = $ip_exp[1];
  1511. $output = preg_replace_callback(
  1512. "/(\s+AS )(\d+)/",
  1513. function ($matches) {
  1514. return $matches[1].link_as($matches[2]);
  1515. },
  1516. $output
  1517. );
  1518. $output = preg_replace_callback(
  1519. "/(\s+AS: )(\d+)/",
  1520. function ($matches) {
  1521. return $matches[1].link_as($matches[2]);
  1522. },
  1523. $output
  1524. );
  1525. $output = preg_replace_callback(
  1526. "/^( Active prefixes:\s+)(\d+)/",
  1527. function ($matches) {
  1528. global $ip;
  1529. return $matches[1].link_command("routes", $ip, $matches[2]);
  1530. },
  1531. $output
  1532. );
  1533. $output = preg_replace_callback(
  1534. "/^( Received prefixes:\s+)(\d+)/",
  1535. function ($matches) {
  1536. global $ip;
  1537. return $matches[1].link_command("bgp", "neighbors+".$ip."+routes+all", $matches[2]);
  1538. },
  1539. $output
  1540. );
  1541. $output = preg_replace_callback(
  1542. "/^( Suppressed due to damping:\s+)(\d+)/",
  1543. function ($matches) {
  1544. global $ip;
  1545. return $matches[1].link_command("bgp", "neighbors+".$ip."+routes+damping+suppressed", $matches[2]);
  1546. },
  1547. $output
  1548. );
  1549. $output = preg_replace_callback(
  1550. "/^( )(Export)(: )/",
  1551. function ($matches) {
  1552. global $ip;
  1553. return $matches[1].link_command("advertised-routes", $ip, $matches[2]).$matches[3];
  1554. },
  1555. $output
  1556. );
  1557. $output = preg_replace_callback(
  1558. "/( )(Import)(: )/",
  1559. function ($matches) {
  1560. global $ip;
  1561. return $matches[1].link_command("bgp", "neighbors+".$ip."+routes+all", $matches[2]).$matches[3];
  1562. },
  1563. $output
  1564. );
  1565. return $output;
  1566. }
  1567. // JunOS
  1568. if (preg_match("/^show route protocol bgp .* terse/i", $exec))
  1569. {
  1570. $output = preg_replace_callback(
  1571. "/^([\* ] )([\d\.A-Fa-f:\/]+)(\s+)/",
  1572. function ($matches) {
  1573. return $matches[1].link_command("bgp", $matches[2]."+exact", $matches[2]).$matches[3];
  1574. },
  1575. $output
  1576. );
  1577. return $output;
  1578. }
  1579. // JunOS
  1580. if (preg_match("/^show route protocol bgp /i", $exec) OR preg_match("/^show route aspath-regex /i", $exec))
  1581. {
  1582. if (preg_match("/^ (.)BGP /", $output, $exp))
  1583. {
  1584. if ($exp[1] == '*')
  1585. {
  1586. $best = '#FF0000';
  1587. }
  1588. else
  1589. {
  1590. $best = '';
  1591. }
  1592. }
  1593. else if (preg_match("/^:?\n?[\n\d\.A-Fa-f:\/\s]{19}([\*\+\- ]{1})\[BGP\//", $output, $exp))
  1594. {
  1595. if ($exp[1] == '*' OR $exp[1] == '+')
  1596. {
  1597. $best = "#ff0000";
  1598. }
  1599. else if ($exp[1] == '-')
  1600. {
  1601. $best = "#008800";
  1602. }
  1603. else
  1604. {
  1605. $best = '';
  1606. }
  1607. }
  1608. else if (preg_match("/^[\n]+$/", $output))
  1609. {
  1610. $best = '';
  1611. }
  1612. $output = preg_replace_callback(
  1613. "/( from )([0-9\.A-Fa-f:]+)/",
  1614. function ($matches) {
  1615. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]);
  1616. },
  1617. $output
  1618. );
  1619. $output = preg_replace_callback(
  1620. "/( Source: )([0-9\.A-Fa-f:]+)/",
  1621. function ($matches) {
  1622. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]);
  1623. },
  1624. $output
  1625. );
  1626. $output = preg_replace_callback(
  1627. "/(\s+AS: )([\d ]+)/",
  1628. function ($matches) {
  1629. return link_as($matches[2]);
  1630. },
  1631. $output
  1632. );
  1633. $output = preg_replace_callback(
  1634. "/(Community: )([\d: ]+)/",
  1635. function ($matches) {
  1636. return $matches[1].link_community($matches[2]);
  1637. },
  1638. $output
  1639. );
  1640. $output = preg_replace_callback(
  1641. "/(Communities: )([\d: ]+)/",
  1642. function ($matches) {
  1643. return $matches[1].link_community($matches[2]);
  1644. },
  1645. $output
  1646. );
  1647. $output = preg_replace_callback(
  1648. "/(^\s+AS path: )([\d ]+)/",
  1649. function ($matches) {
  1650. return $matches[1].link_as($matches[2]);
  1651. },
  1652. $output
  1653. );
  1654. $output = preg_replace_callback(
  1655. "/^(:?\n?[\dA-Fa-f:]+[\d\.A-Fa-f:\/]+)(\s*)/",
  1656. function ($matches) {
  1657. return "<b>".link_command("bgp", $matches[1]."+exact", $matches[1])."</b>".$matches[2];
  1658. },
  1659. $output
  1660. );
  1661. if (isset($best) AND $best != '')
  1662. {
  1663. $output = '<span style="color:'.$best.'">'.$output.'</span>';
  1664. }
  1665. return $output;
  1666. }
  1667. if (preg_match("/bgp/", $exec))
  1668. {
  1669. $output = preg_replace("|^(BGP routing table entry for) (\S+)|", "\\1 <b>\\2</b>", $output);
  1670. if (preg_match("|^(Paths: .*) best #(\d+)|", $output, $best_exp))
  1671. {
  1672. $best = $best_exp[2];
  1673. $output = preg_replace("|^(Paths: .*) best #(\d+)|", '\\1 <span style="color:#ff0000">best #\\2</span>', $output);
  1674. }
  1675. // Fix for IPv6 route output where there are no addional 3 spaces before addresses
  1676. if (preg_match("/ Advertised to non peer-group peers:/", $output) AND preg_match("/ ipv6 /", $exec))
  1677. {
  1678. $count--;
  1679. }
  1680. if (( preg_match("/^ (\d+.*)/", $output) AND
  1681. !preg_match("/^ \d+\./", $output) AND
  1682. !preg_match("/[a-z\:\.]+/", $output)
  1683. ) OR
  1684. preg_match("/^ Local/", $output) OR
  1685. preg_match("/, \(aggregated by /", $output))
  1686. {
  1687. $count++;
  1688. $output = preg_replace_callback(
  1689. "/^([^\(A-z\n]+)/",
  1690. function ($matches) {
  1691. return link_as($matches[1]);
  1692. },
  1693. $output
  1694. );
  1695. $output = preg_replace_callback(
  1696. "/(, \(aggregated by )(\d+) ([^\)]+)/",
  1697. function ($matches) {
  1698. return $matches[1].link_as($matches[2])." ".link_whois($matches[3]);
  1699. },
  1700. $output
  1701. );
  1702. }
  1703. if (isset($best) AND $best == $count)
  1704. {
  1705. $output = '<span style="color:#ff0000">'.$output.'</span>';
  1706. }
  1707. $output = preg_replace_callback(
  1708. "/( from )([0-9\.A-Fa-f:]+)( )/",
  1709. function ($matches) {
  1710. return $matches[1].link_command("bgp", "neighbors+".$matches[2], $matches[2]).$matches[3];
  1711. },
  1712. $output
  1713. );
  1714. $output = preg_replace_callback(
  1715. "/(Community: )([\d: ]+)/",
  1716. function ($matches) {
  1717. return $matches[1].link_community($matches[2]);
  1718. },
  1719. $output
  1720. );
  1721. $output = preg_replace_callback(
  1722. "/(Communities: )([\d: ]+)/",
  1723. function ($matches) {
  1724. return $matches[1].link_community($matches[2]);
  1725. },
  1726. $output
  1727. );
  1728. $output = preg_replace_callback(
  1729. "/(^\s+AS path: )([\d ]+)/",
  1730. function ($matches) {
  1731. return link_as($matches[2]);
  1732. },
  1733. $output
  1734. );
  1735. return $output;
  1736. }
  1737. if (preg_match("/^trace/", $exec))
  1738. {
  1739. $output = preg_replace("/\[AS0\]\s(.*)/", "\\1", $output);
  1740. // IPv4
  1741. $output = preg_replace_callback(
  1742. "/(\[AS)(\d+)(\])\s(.*)(\))(.*)/",
  1743. function ($matches) {
  1744. return $matches[4].$matches[5]." ".$matches[1]." ".link_as($matches[2]).$matches[3].$matches[6];
  1745. },
  1746. $output
  1747. );
  1748. // IPv6
  1749. $output = preg_replace_callback(
  1750. "/(\[AS)(\d+)(\])\s([^\s]+)\s(.*)/",
  1751. function ($matches) {
  1752. return $matches[4]." ".$matches[1]." ".link_as($matches[2]).$matches[3].$matches[5];
  1753. },
  1754. $output
  1755. );
  1756. $output = preg_replace_callback(
  1757. "/\((.*)\) (\[AS\s+)(\d+)(\])/",
  1758. function ($matches) {
  1759. return get_as($matches[1], $matches[3]);
  1760. },
  1761. $output
  1762. );
  1763. return $output;
  1764. }
  1765. return $output;
  1766. }
  1767. /**
  1768. * Parse `bgp' output contents and return AS pathes
  1769. */
  1770. function parse_bgp_path($output)
  1771. {
  1772. global $os, $exec, $query, $count;
  1773. $best = FALSE;
  1774. $pathes = array();
  1775. $output = str_replace("\r\n", "\n", $output);
  1776. // MikroTik
  1777. if (preg_match("/^\/(ip|ipv6) route print detail/i", $exec) AND $os == 'mikrotik')
  1778. {
  1779. $output_parts = explode("\n" , trim($output), 4);
  1780. if (!isset($output_parts[3]))
  1781. {
  1782. return FALSE;
  1783. }
  1784. $summary_parts = explode("\n\n" , $output_parts[3]);
  1785. foreach ($summary_parts as $i => $summary_part)
  1786. {
  1787. $data_exp = explode(' ', trim($summary_part), 3);
  1788. if (strpos($data_exp[1], 'A') !== FALSE)
  1789. {
  1790. $best = $i;
  1791. }
  1792. if (preg_match("/bgp-as-path=\"([^\"]+)\"/", $summary_part, $exp))
  1793. {
  1794. if ($path = parse_as_path($exp[1]))
  1795. {
  1796. $pathes[] = $path;
  1797. }
  1798. }
  1799. }
  1800. return array
  1801. (
  1802. 'best' => $best,
  1803. 'pathes' => $pathes
  1804. );
  1805. }
  1806. // JunOS
  1807. if (preg_match("/^show route protocol bgp /i", $exec) OR preg_match("/^show route aspath-regex /i", $exec))
  1808. {
  1809. $lines = explode("\n", $output);
  1810. foreach ($lines as $line)
  1811. {
  1812. if (preg_match("/^ (.)BGP /", $line, $exp))
  1813. {
  1814. if ($exp[1] == '*')
  1815. {
  1816. if ($count == 0)
  1817. {
  1818. $count++;
  1819. }
  1820. }
  1821. }
  1822. else if (preg_match("/^:?\n?[\n\d\.A-Fa-f:\/\s]{19}([\*\+\- ]{1})\[BGP\//", $line, $exp))
  1823. {
  1824. if ($exp[1] == '*' OR $exp[1] == '+')
  1825. {
  1826. if ($count == 0)
  1827. {
  1828. $count++;
  1829. }
  1830. }
  1831. }
  1832. if (preg_match("/^\s+AS path: ([\d ]+)/", $line, $exp))
  1833. {
  1834. if ($path = parse_as_path($exp[1]))
  1835. {
  1836. $pathes[] = $path;
  1837. }
  1838. }
  1839. }
  1840. $best = $count - 1;
  1841. return array
  1842. (
  1843. 'best' => $best,
  1844. 'pathes' => $pathes
  1845. );
  1846. }
  1847. // Other OS
  1848. if (preg_match("/bgp/", $exec))
  1849. {
  1850. if (preg_match("|(Paths: .*) best #(\d+)|", $output, $best_exp))
  1851. {
  1852. $best = $best_exp[2] - 1;
  1853. }
  1854. $lines = explode("\n", $output);
  1855. foreach ($lines as $line)
  1856. {
  1857. if (( preg_match("/^ (\d+.*)/", $line) AND
  1858. !preg_match("/^ \d+\./", $line) AND
  1859. !preg_match("/[a-z\:\.]+/", $line)
  1860. ) OR
  1861. preg_match("/^ Local/", $line) OR
  1862. preg_match("/, \(aggregated by /", $line))
  1863. {
  1864. $line = preg_replace("/^([^\(A-z\n]+).*/", "\\1", $line);
  1865. if ($path = parse_as_path($line))
  1866. {
  1867. $pathes[] = $path;
  1868. }
  1869. }
  1870. }
  1871. return array
  1872. (
  1873. 'best' => $best,
  1874. 'pathes' => $pathes
  1875. );
  1876. }
  1877. return FALSE;
  1878. }
  1879. /**
  1880. * Parse list separated by spaces
  1881. */
  1882. function parse_list($array)
  1883. {
  1884. preg_match_all('/([^=]+)=([^\s]+)[\n\s]/is', $array, $out);
  1885. $array = array();
  1886. if (isset($out[1]))
  1887. {
  1888. foreach ($out[1] as $key => $val)
  1889. {
  1890. $array[trim($out[1][$key])] = trim($out[2][$key], '"');
  1891. }
  1892. }
  1893. return $array;
  1894. }
  1895. /**
  1896. * Parse AS path
  1897. */
  1898. function parse_as_path($line)
  1899. {
  1900. $path = preg_split('/([^\d]+)/', trim($line));
  1901. $return = array();
  1902. foreach ($path as $asn)
  1903. {
  1904. if ($asn != '')
  1905. {
  1906. $return[] = 'AS'.$asn;
  1907. }
  1908. }
  1909. return array_unique($return);
  1910. }
  1911. /**
  1912. * Build list table
  1913. */
  1914. function build_table($table_array)
  1915. {
  1916. $size_array = array();
  1917. foreach ($table_array as $priority => $data)
  1918. {
  1919. foreach ($data as $field => $value)
  1920. {
  1921. $size_array[$field][$priority] = $value;
  1922. }
  1923. }
  1924. $size_max = array();
  1925. foreach ($size_array as $field => $value)
  1926. {
  1927. $size_max[$field] = array_map('mb_strlen', array_map('strip_tags', $value));
  1928. }
  1929. $max = array_map('max', $size_max);
  1930. $return = '';
  1931. foreach ($table_array as $index => $data)
  1932. {
  1933. $line = array();
  1934. foreach ($data as $field => $value)
  1935. {
  1936. if (reset(array_keys($data)) == $field)
  1937. {
  1938. $line[] = $value.str_repeat(' ', $max[$field] - mb_strlen(strip_tags($value)));
  1939. }
  1940. else
  1941. {
  1942. $line[] = str_repeat(' ', $max[$field] - mb_strlen(strip_tags($value))).$value;
  1943. }
  1944. }
  1945. $return .= implode(' ', $line)."\n";
  1946. }
  1947. return $return;
  1948. }
  1949. /**
  1950. * Link to execute command
  1951. */
  1952. function link_command($command, $query, $name = '', $return_uri = FALSE)
  1953. {
  1954. global $router, $protocol;
  1955. if ($name == '')
  1956. {
  1957. $name = $query;
  1958. }
  1959. $uri = '?router='.$router.
  1960. '&amp;protocol='.$protocol.
  1961. '&amp;command='.$command.
  1962. '&amp;query='.$query;
  1963. if ($return_uri)
  1964. {
  1965. return $uri;
  1966. }
  1967. return '<a href="'.$uri.'">'.$name.'</a>';
  1968. }
  1969. /**
  1970. * Link to AS community
  1971. */
  1972. function link_community($line)
  1973. {
  1974. global $_CONFIG;
  1975. $communitylist = preg_split('/[^\d:]+/', $line);
  1976. foreach ($communitylist as $i => $community)
  1977. {
  1978. $communitylist[$i] = '<i>'.$community.'</i>';
  1979. }
  1980. return implode(' ', $communitylist);
  1981. }
  1982. /**
  1983. * Link to AS whois
  1984. */
  1985. function link_as($line, $word = FALSE)
  1986. {
  1987. global $_CONFIG;
  1988. //print_r($line);
  1989. return preg_replace("/(?:AS)?([\d]+)/is",
  1990. "<a href=\"".htmlspecialchars($_CONFIG['aswhois'])."AS\\1\" target=\"_blank\">".($word ? 'AS' : '')."\\1</a>", $line);
  1991. }
  1992. function get_as($ip, $original_as)
  1993. {
  1994. if ($original_as == 15835)
  1995. {
  1996. $as = 65535;
  1997. if($conn = fsockopen ('whois.cymru.com', 43))
  1998. {
  1999. fputs($conn, $ip."\r\n");
  2000. $output = '';
  2001. while(!feof($conn))
  2002. {
  2003. $output .= fgets($conn,128);
  2004. }
  2005. $output = explode("\n", $output);
  2006. if (isset($output[1]))
  2007. {
  2008. $_as = explode("|", $output[1]);
  2009. }
  2010. if (isset($_as[0]))
  2011. {
  2012. $as = trim($_as[0]);
  2013. if ($as == 'NA')
  2014. {
  2015. $as = 65535;
  2016. }
  2017. }
  2018. fclose($conn);
  2019. }
  2020. return '(' . $ip .') [AS ' . link_as($as) . ']';
  2021. }
  2022. else
  2023. {
  2024. return '(' . $ip .') [AS ' . link_as($original_as) . ']';
  2025. }
  2026. }
  2027. /**
  2028. * Link to whois IP
  2029. */
  2030. function link_whois($line, $name = '')
  2031. {
  2032. global $_CONFIG;
  2033. if ($name == '')
  2034. {
  2035. $name = $line;
  2036. }
  2037. return '<a href="'.htmlspecialchars($_CONFIG['ipwhois']).$line.'" target="_blank">'.$name.'</a>';
  2038. }
  2039. /**
  2040. * Get and print BGP path graph
  2041. */
  2042. function get_path_graph($router, $query, $as_pathes, $as_best_path, $format = 'svg')
  2043. {
  2044. global $_CONFIG, $_REQUEST;
  2045. $font_size = 9; // default font size
  2046. $graph = new Image_GraphViz();
  2047. $graph->addNode($router, array
  2048. (
  2049. 'label' => $_CONFIG['routers'][$router]['description'],
  2050. 'shape' => 'box',
  2051. 'style' => 'filled',
  2052. 'fillcolor' => '#FFCCCC',
  2053. 'fontsize' => $font_size + 2
  2054. ));
  2055. $query_ptr = get_ptr($query);
  2056. // Draw requested node
  2057. $graph->addNode($query, array
  2058. (
  2059. 'URL' => link_command('trace', $query, '', TRUE),
  2060. 'target' => '_blank',
  2061. 'label' => $query_ptr ? $query."\n".$query_ptr : $query,
  2062. 'shape' => 'box',
  2063. 'style' => 'filled',
  2064. 'fillcolor' => '#FFFFCC',
  2065. 'fontsize' => $font_size
  2066. ));
  2067. $as_pathes_best = $as_list = $as_peer_list = array();
  2068. // Draw path ASs
  2069. foreach ($as_pathes as $as_path_id => $as_path_array)
  2070. {
  2071. $peer_as = reset($as_path_array);
  2072. if (!isset($as_peer_list[$peer_as]) OR $as_peer_list[$peer_as] !== TRUE)
  2073. {
  2074. $as_peer_list[$peer_as] = ($as_best_path === $as_path_id);
  2075. }
  2076. $as_list = array_merge($as_list, $as_path_array);
  2077. }
  2078. $as_list = array_unique($as_list);
  2079. // Draw our AS
  2080. if (!in_array('AS'.$_CONFIG['asn'], $as_list))
  2081. {
  2082. $graph->addNode('AS'.$_CONFIG['asn'], array
  2083. (
  2084. 'URL' => $_CONFIG['aswhois'].'AS'.$_CONFIG['asn'],
  2085. 'target' => '_blank',
  2086. 'label' => 'AS'.$_CONFIG['asn']."\n".$_CONFIG['company'],
  2087. 'style' => 'filled',
  2088. 'fillcolor' => 'white',
  2089. 'fontsize' => $font_size
  2090. ));
  2091. $graph->addEdge(array('AS'.$_CONFIG['asn'] => $router), array
  2092. (
  2093. 'color' => 'red'
  2094. ));
  2095. }
  2096. foreach ($as_list as $as_id)
  2097. {
  2098. $color = isset($as_peer_list[$as_id]) ? ($as_peer_list[$as_id] ? '#CCFFCC' : '#CCCCFF') : 'white';
  2099. $asinfo = get_asinfo($as_id);
  2100. $graph->addNode($as_id, array
  2101. (
  2102. 'URL' => $_CONFIG['aswhois'].$as_id,
  2103. 'target' => '_blank',
  2104. 'label' => isset($asinfo['description']) ? $as_id."\n".$asinfo['description'] : $as_id,
  2105. 'style' => 'filled',
  2106. 'fillcolor' => $color,
  2107. 'fontsize' => $font_size
  2108. ));
  2109. }
  2110. // Draw pathes
  2111. foreach ($as_pathes as $as_path_id => $as_path_array)
  2112. {
  2113. $first = $last = FALSE;
  2114. foreach ($as_path_array as $as_path)
  2115. {
  2116. if (!$first)
  2117. {
  2118. $first = $last = $as_path;
  2119. continue;
  2120. }
  2121. if (!isset($as_pathes_best[$last.$as_path]))
  2122. {
  2123. $graph->addEdge(array($last => $as_path), array
  2124. (
  2125. 'color' => ($as_best_path === $as_path_id) ? 'red' : 'black'
  2126. ));
  2127. if ($as_best_path === $as_path_id)
  2128. {
  2129. $as_pathes_best[$last.$as_path] = TRUE;
  2130. }
  2131. }
  2132. $last = $as_path;
  2133. }
  2134. if (!isset($as_pathes_best[$router.$first]))
  2135. {
  2136. $graph->addEdge(array($router => $first), array
  2137. (
  2138. 'color' => ($as_best_path === $as_path_id) ? 'red' : 'black'
  2139. ));
  2140. if ($as_best_path === $as_path_id)
  2141. {
  2142. $as_pathes_best[$router.$first] = TRUE;
  2143. }
  2144. }
  2145. }
  2146. // Draw last path
  2147. $graph->addEdge(array($as_path => $query), array
  2148. (
  2149. 'color' => ($as_pathes_best) ? 'red' : 'black'
  2150. ));
  2151. $graph->image($format);
  2152. exit;
  2153. }
  2154. /**
  2155. * Get and print blank image
  2156. */
  2157. function get_blank_graph($string, $format = 'svg')
  2158. {
  2159. $graph = new Image_GraphViz();
  2160. $graph->addNode('error', array
  2161. (
  2162. 'label' => $string,
  2163. 'shape' => 'none',
  2164. 'fontcolor' => 'red',
  2165. 'fontsize' => 14
  2166. ));
  2167. $graph->image($format);
  2168. exit;
  2169. }
  2170. /**
  2171. * Get address information from RADb
  2172. */
  2173. function get_radb($request)
  2174. {
  2175. if (!$fp = @fsockopen('whois.radb.net', 43, $errnum, $errstr, 10))
  2176. {
  2177. return FALSE;
  2178. }
  2179. fputs($fp, $request."\r\n");
  2180. $data = '';
  2181. while (!feof($fp))
  2182. {
  2183. $data .= fgets($fp, 128);
  2184. }
  2185. fclose($fp);
  2186. $exp = explode("\n\n", $data);
  2187. if (!isset($exp[0]) OR empty($exp[0]))
  2188. {
  2189. return FALSE;
  2190. }
  2191. $lines = explode("\n", $exp[0]);
  2192. $return = array();
  2193. foreach ($lines as $line)
  2194. {
  2195. $line = explode(':', $line, 2);
  2196. if (isset($line[0]) AND isset($line[1]))
  2197. {
  2198. $return[$line[0]] = trim($line[1]);
  2199. }
  2200. }
  2201. if (sizeof($return) < 1)
  2202. {
  2203. return FALSE;
  2204. }
  2205. return $return;
  2206. }
  2207. /**
  2208. * Get AS name information from "Team Cymru - IP to ASN Mapping"
  2209. */
  2210. function get_asinfo($request)
  2211. {
  2212. if (!$dns = dns_get_record($request.'.asn.cymru.com', DNS_TXT) OR !isset($dns[0]['txt']))
  2213. {
  2214. return FALSE;
  2215. }
  2216. $segments = array_map('trim', explode('|', $dns[0]['txt'], 5));
  2217. if (sizeof($segments) != 5)
  2218. {
  2219. return FALSE;
  2220. }
  2221. list($segments[4], $segments[5]) = explode(' ', $segments[4], 2);
  2222. $segments[5] = str_replace('_', '"', $segments[5]);
  2223. return array
  2224. (
  2225. 'asn' => $segments[0],
  2226. 'country' => $segments[1],
  2227. 'registrar' => $segments[2],
  2228. 'regdate' => $segments[3],
  2229. 'asname' => $segments[4],
  2230. 'description' => $segments[5],
  2231. );
  2232. }
  2233. /**
  2234. * Get PTR record for IPv4/IPv6 address
  2235. */
  2236. function get_host($hostname)
  2237. {
  2238. global $protocol;
  2239. if (filter_var($hostname, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE))
  2240. {
  2241. return $hostname;
  2242. }
  2243. $dns_a = (($dns_a = dns_get_record($hostname, DNS_A)) !== FALSE) ? $dns_a : array();
  2244. $dns_aaaa = (($dns_aaaa = dns_get_record($hostname, DNS_AAAA)) !== FALSE) ? $dns_aaaa : array();
  2245. $ip_array = array();
  2246. foreach (array_merge($dns_aaaa, $dns_a) as $record)
  2247. {
  2248. switch ($record['type'])
  2249. {
  2250. case 'A':
  2251. $ip_array[] = $record['ip'];
  2252. break;
  2253. case 'AAAA':
  2254. $ip_array[] = $record['ipv6'];
  2255. break;
  2256. case 'CNAME':
  2257. $ip_array = array_push($ip_array, get_host($record['target']));
  2258. break;
  2259. }
  2260. }
  2261. $ipv4_array = $ipv6_array = array();
  2262. foreach ($ip_array as $ip)
  2263. {
  2264. if (strpos($ip, ':') !== FALSE)
  2265. {
  2266. $ipv6_array[] = $ip;
  2267. }
  2268. else
  2269. {
  2270. $ipv4_array[] = $ip;
  2271. }
  2272. }
  2273. $ip_array = ($protocol == 'ipv6')
  2274. ? $ipv6_array
  2275. : $ipv4_array;
  2276. if (!$ipv6_array OR !$ipv4_array)
  2277. {
  2278. $ip_array = array_merge($ipv6_array, $ipv4_array);
  2279. }
  2280. if (!$ip_array OR (!$ipv4_array AND $protocol != 'ipv6'))
  2281. {
  2282. return FALSE;
  2283. }
  2284. return end($ip_array);
  2285. }
  2286. /**
  2287. * Get PTR record for IPv4/IPv6 address
  2288. */
  2289. function get_ptr($ip)
  2290. {
  2291. if (preg_match("/:/", $ip))
  2292. {
  2293. $unpack = unpack('H*hex', @inet_pton($ip));
  2294. $arpa = implode('.', array_reverse(str_split($unpack['hex']))).'.ip6.arpa';
  2295. }
  2296. else
  2297. {
  2298. $arpa = implode('.', array_reverse(explode('.', $ip))).'.in-addr.arpa.';
  2299. }
  2300. if (!$arpa OR !$dns = dns_get_record($arpa, DNS_PTR))
  2301. {
  2302. return $ip;
  2303. }
  2304. $ptr = array();
  2305. foreach ($dns as $record)
  2306. {
  2307. if ($record['type'] == 'PTR')
  2308. {
  2309. $ptr[] = $record['target'];
  2310. }
  2311. }
  2312. if (!$ptr)
  2313. {
  2314. return $ip;
  2315. }
  2316. return reset($ptr);
  2317. }
  2318. /**
  2319. * Group router list
  2320. */
  2321. function group_routers($array)
  2322. {
  2323. $return = array();
  2324. foreach ($array as $key => $value)
  2325. {
  2326. if (isset($value['group']) AND $value['group'] != '')
  2327. {
  2328. $return[$value['group']][$key] = $value;
  2329. continue;
  2330. }
  2331. $return[''][$key] = $value;
  2332. }
  2333. return $return;
  2334. }
  2335. // ------------------------------------------------------------------------
  2336. /**
  2337. * Telnet class
  2338. *
  2339. * Used to execute remote commands via telnet connection
  2340. * Usess sockets functions and fgetc() to process result
  2341. *
  2342. * All methods throw Exceptions on error
  2343. *
  2344. * Written by Dalibor Andzakovic <dali@swerve.co.nz>
  2345. * Based on the code originally written by Marc Ennaji and extended by
  2346. * Matthias Blaser <mb@adfinis.ch>
  2347. *
  2348. * Modified by Dmitry Shin <dmitry.s@hsdn.org>, 2014
  2349. */
  2350. class Telnet
  2351. {
  2352. private $host;
  2353. private $port;
  2354. private $timeout;
  2355. private $socket = NULL;
  2356. private $buffer = NULL;
  2357. private $prompt;
  2358. private $errno;
  2359. private $errstr;
  2360. private $header1;
  2361. private $header2;
  2362. public $NULL;
  2363. public $DC1;
  2364. public $WILL;
  2365. public $WONT;
  2366. public $DO;
  2367. public $DONT;
  2368. public $IAC;
  2369. public $LINEMODE;
  2370. const TELNET_ERROR = FALSE;
  2371. const TELNET_OK = TRUE;
  2372. /**
  2373. * Constructor. Initialises host, port and timeout parameters
  2374. * defaults to localhost port 23 (standard telnet port)
  2375. *
  2376. * @access public
  2377. * @param string $host Host name or IP addres
  2378. * @param int $port TCP port number
  2379. * @param int $timeout Connection timeout in seconds
  2380. * @return void
  2381. */
  2382. public function __construct($host = '127.0.0.1', $port = '23', $timeout = 10, $prompt = '/[^\s]{2,}[\$%>] {0,1}$/')
  2383. {
  2384. $this->default_prompt = $prompt;
  2385. $this->setPrompt();
  2386. $this->host = $host;
  2387. $this->port = $port;
  2388. $this->timeout = $timeout;
  2389. $this->header1 =
  2390. chr(0xFF).chr(0xFB).chr(0x1F). // 0xFF 0xFB 0x1F - WILL command - NEGOTIATE-WINDOW-SIZE
  2391. chr(0xFF).chr(0xFB).chr(0x20). // 0xFF 0xFB 0x20 - WILL command - TERMINAL-SPEED
  2392. chr(0xFF).chr(0xFB).chr(0x18). // 0xFF 0xFB 0x18 - WILL command - TERMINAL-TYPE
  2393. chr(0xFF).chr(0xFB).chr(0x27). // 0xFF 0xFB 0x27 - WILL command - NEW-ENVIRON
  2394. chr(0xFF).chr(0xFD).chr(0x01). // 0xFF 0xFD 0x01 - DO command - ECHO
  2395. chr(0xFF).chr(0xFB).chr(0x03). // 0xFF 0xFB 0x03 - WILL command - SUPPRESS-GO-AHEAD
  2396. chr(0xFF).chr(0xFD).chr(0x03). // 0xFF 0xFD 0x03 - DO command - SUPPRESS-GO-AHEAD
  2397. chr(0xFF).chr(0xFC).chr(0x23). // 0xFF 0xFC 0x23 - WON'T command - X-DISPLAY-LOCATION
  2398. chr(0xFF).chr(0xFC).chr(0x24). // 0xFF 0xFC 0x24 - WON'T command - ENVIRONMENT
  2399. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2400. chr(0x1F).chr(0x00).chr(0x50).chr(0x00).chr(0x18). // NEGOTIATE-WINDOW-SIZE
  2401. // <Width1>=0 <Width0>=80 <Height1>=0 <Height0>=24
  2402. chr(0xFF).chr(0xF0). // 0xFF 0xF0 - SE command
  2403. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2404. chr(0x20).chr(0x00).chr(0x33).chr(0x38).chr(0x34).
  2405. chr(0x30).chr(0x30).chr(0x2C).chr(0x33).chr(0x38).
  2406. chr(0x34).chr(0x30).chr(0x30). // TERMINAL-SPEED - 38400,38400
  2407. chr(0xFF).chr(0xF0). // 0xFF 0xF0 - SE command
  2408. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2409. chr(0x27).chr(0x00). // NEW-ENVIRON <IS> <empty>
  2410. chr(0xFF).chr(0xF0). // 0xFF 0xF0 - SE command
  2411. chr(0xFF).chr(0xFA). // 0xFF 0xFA ... - SB command
  2412. chr(0x18).chr(0x00).chr(0x58).chr(0x54).chr(0x45).
  2413. chr(0x52).chr(0x4D). // TERMINAL-TYPE: <IS> XTERM
  2414. chr(0xFF).chr(0xF0); // 0xFF 0xF0 - SE command
  2415. $this->header2 =
  2416. chr(0xFF).chr(0xFC).chr(0x01). // 0xFF 0xFC 0x01 - WON'T command - ECHO
  2417. chr(0xFF).chr(0xFC).chr(0x22). // 0xFF 0xFC 0x22 - WON'T command - LINEMODE
  2418. chr(0xFF).chr(0xFE).chr(0x05). // 0xFF 0xFE 0x05 - DON'T command - STATUS
  2419. chr(0xFF).chr(0xFC).chr(0x21); // 0xFF 0xFC 0x21 - WON'T command - TOGGLE-FLOW-CONTROL
  2420. $this->NULL = chr(0);
  2421. $this->DC1 = chr(17);
  2422. $this->WILL = chr(251);
  2423. $this->WONT = chr(252);
  2424. $this->DO = chr(253);
  2425. $this->DONT = chr(254);
  2426. $this->IAC = chr(255);
  2427. $this->LINEMODE = chr(34);
  2428. $this->connect();
  2429. }
  2430. /**
  2431. * Destructor. Cleans up socket connection and command buffer
  2432. *
  2433. * @access public
  2434. * @return void
  2435. */
  2436. public function __destruct()
  2437. {
  2438. $this->disconnect();
  2439. $this->buffer = NULL;
  2440. }
  2441. /**
  2442. * Attempts connection to remote host. Returns TRUE if sucessful.
  2443. *
  2444. * @access public
  2445. * @return bool
  2446. */
  2447. public function connect()
  2448. {
  2449. if (!preg_match('/([0-9]{1,3}\\.){3,3}[0-9]{1,3}/', $this->host))
  2450. {
  2451. $ip = gethostbyname($this->host);
  2452. if ($this->host == $ip)
  2453. {
  2454. throw new Exception("Cannot resolve ".$this->host.".");
  2455. }
  2456. else
  2457. {
  2458. $this->host = $ip;
  2459. }
  2460. }
  2461. $this->socket = @fsockopen($this->host, $this->port, $this->errno, $this->errstr, $this->timeout);
  2462. $this->write($this->header1, FALSE);
  2463. usleep(100800);
  2464. $this->write($this->header2, FALSE);
  2465. usleep(100800);
  2466. if (!$this->socket)
  2467. {
  2468. throw new Exception("Cannot connect to ".$this->host." on port ".$this->port.".");
  2469. }
  2470. return self::TELNET_OK;
  2471. }
  2472. /**
  2473. * Closes IP socket
  2474. *
  2475. * @access public
  2476. * @return bool
  2477. */
  2478. public function disconnect()
  2479. {
  2480. if ($this->socket)
  2481. {
  2482. $this->write('quit');
  2483. if (!fclose($this->socket))
  2484. {
  2485. throw new Exception("Error while closing telnet socket.");
  2486. }
  2487. $this->socket = NULL;
  2488. }
  2489. return self::TELNET_OK;
  2490. }
  2491. /**
  2492. * Executes command and returns a string with result.
  2493. * This method is a wrapper for lower level private methods
  2494. *
  2495. * @access public
  2496. * @param string $command Command to execute
  2497. * @return string Command result
  2498. */
  2499. public function exec($command)
  2500. {
  2501. $this->write($command);
  2502. $this->waitPrompt();
  2503. return $this->getBuffer();
  2504. }
  2505. /**
  2506. * Attempts login to remote host.
  2507. * This method is a wrapper for lower level private methods and should be
  2508. * modified to reflect telnet implementation details like login/password
  2509. * and line prompts. Defaults to standard unix non-root prompts
  2510. *
  2511. * @access public
  2512. * @param string $username Username
  2513. * @param string $password Password
  2514. * @return bool
  2515. */
  2516. public function login($username = FALSE, $password = FALSE)
  2517. {
  2518. try
  2519. {
  2520. if ($username)
  2521. {
  2522. $this->setPrompt('/(ogin|name|word):.*$/');
  2523. $this->waitPrompt();
  2524. $this->write($username);
  2525. }
  2526. if ($password)
  2527. {
  2528. $this->setPrompt('/word:.*$/');
  2529. $this->waitPrompt();
  2530. $this->write($password);
  2531. }
  2532. $this->setPrompt();
  2533. $this->waitPrompt();
  2534. }
  2535. catch (Exception $e)
  2536. {
  2537. throw new Exception("Login failed.");
  2538. }
  2539. return self::TELNET_OK;
  2540. }
  2541. /**
  2542. * Sets the string of characters to respond to.
  2543. * This should be set to the last character of the command line prompt
  2544. *
  2545. * @access public
  2546. * @param string $s String to respond to
  2547. * @return bool
  2548. */
  2549. public function setPrompt($s = '')
  2550. {
  2551. $this->prompt = $this->default_prompt;
  2552. if ($s != '')
  2553. {
  2554. $this->prompt = $s;
  2555. }
  2556. return self::TELNET_OK;
  2557. }
  2558. /**
  2559. * Gets character from the socket
  2560. *
  2561. * @access public
  2562. * @return void
  2563. */
  2564. public function getc()
  2565. {
  2566. @socket_set_timeout($this->socket, $this->timeout);
  2567. return fgetc($this->socket);
  2568. }
  2569. /**
  2570. * Clears internal command buffer
  2571. *
  2572. * @access public
  2573. * @return void
  2574. */
  2575. public function clearBuffer()
  2576. {
  2577. $this->buffer = '';
  2578. }
  2579. /**
  2580. * Reads characters from the socket and adds them to command buffer.
  2581. * Handles telnet control characters. Stops when prompt is ecountered.
  2582. *
  2583. * @access public
  2584. * @param string $prompt
  2585. * @return bool
  2586. */
  2587. public function readTo($prompt)
  2588. {
  2589. if (!$this->socket)
  2590. {
  2591. throw new Exception("Telnet connection closed.");
  2592. }
  2593. $this->clearBuffer();
  2594. do
  2595. {
  2596. $c = $this->getc();
  2597. if ($c === false)
  2598. {
  2599. throw new Exception("Couldn't find the requested : '".$prompt."', it was not in the data returned from server.");
  2600. }
  2601. if ($c == $this->IAC)
  2602. {
  2603. if ($this->negotiateTelnetOptions())
  2604. {
  2605. continue;
  2606. }
  2607. }
  2608. $this->buffer .= $c;
  2609. if (@preg_match($prompt, $this->buffer))
  2610. {
  2611. return self::TELNET_OK;
  2612. }
  2613. }
  2614. while ($c != $this->NULL OR $c != $this->DC1);
  2615. }
  2616. /**
  2617. * Write command to a socket
  2618. *
  2619. * @access public
  2620. * @param string $buffer Stuff to write to socket
  2621. * @param bool $addNewLine Default true, adds newline to the command
  2622. * @return bool
  2623. */
  2624. public function write($buffer = '', $addNewLine = TRUE)
  2625. {
  2626. if (!$this->socket)
  2627. {
  2628. throw new Exception("Telnet connection closed.");
  2629. }
  2630. // clear buffer from last command
  2631. $this->clearBuffer();
  2632. if ($addNewLine == true)
  2633. {
  2634. $buffer .= "\r\n";
  2635. }
  2636. if (!fwrite($this->socket, $buffer) < 0)
  2637. {
  2638. throw new Exception("Error writing to socket.");
  2639. }
  2640. return self::TELNET_OK;
  2641. }
  2642. /**
  2643. * Returns the content of the command buffer
  2644. *
  2645. * @access public
  2646. * @return string Content of the command buffer
  2647. */
  2648. public function getBuffer()
  2649. {
  2650. return $this->buffer;
  2651. }
  2652. /**
  2653. * Telnet control character magic
  2654. *
  2655. * @access public
  2656. * @param string $command Character to check
  2657. * @return bool
  2658. */
  2659. public function negotiateTelnetOptions()
  2660. {
  2661. $c = $this->getc();
  2662. if ($c != $this->IAC)
  2663. {
  2664. if (($c == $this->DO) OR ($c == $this->DONT))
  2665. {
  2666. $opt = $this->getc();
  2667. fwrite($this->socket, $this->IAC.$this->WONT.$opt);
  2668. }
  2669. else if (($c == $this->WILL) OR ($c == $this->WONT))
  2670. {
  2671. $opt = $this->getc();
  2672. fwrite($this->socket, $this->IAC.$this->DONT.$opt);
  2673. }
  2674. }
  2675. else
  2676. {
  2677. throw new Exception('Error: Something Wicked Happened.');
  2678. }
  2679. return self::TELNET_OK;
  2680. }
  2681. /**
  2682. * Reads socket until prompt is encountered
  2683. *
  2684. * @access public
  2685. */
  2686. public function waitPrompt()
  2687. {
  2688. return $this->readTo($this->prompt);
  2689. }
  2690. } // class Telnet
  2691. /* End of file */