index.php 73 KB

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