index.php 74 KB

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