index.php 67 KB

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