index.php 74 KB

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