index.php 77 KB

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