index.php 77 KB

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