index.php 75 KB

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