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