index.php 77 KB

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