index.php 72 KB

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