index.php 77 KB

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