index.php 67 KB

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