index.php 75 KB

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