index.php 72 KB

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