index.php 73 KB

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