Repository navigation
Expand file tree
/
Copy pathLookingGlass.php
More file actions
885 lines (790 loc) · 28.2 KB
/
Copy pathLookingGlass.php
File metadata and controls
885 lines (790 loc) · 28.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
<?php
declare(strict_types=1);
/**
* Hybula Looking Glass
*
* The LookingGlass class provides all functionality.
*
* @copyright 2025 Hybula B.V.
* @license Mozilla Public License 2.0
* @version 1.3.6
* @since File available since release 0.1
* @link https://github.com/hybula/lookingglass
*/
namespace Hybula;
class LookingGlass
{
public const IPV4 = 'ipv4';
public const IPV6 = 'ipv6';
public const SESSION_TARGET_HOST = 'target_host';
public const SESSION_TARGET_METHOD = 'target_method';
public const SESSION_TOS_CHECKED = 'tos_checked';
public const SESSION_CALL_BACKEND = 'call_backend';
public const SESSION_ERROR_MESSAGE = 'error_message';
public const SESSION_CSRF = 'CSRF';
public const METHOD_PING = 'ping';
public const METHOD_PING6 = 'ping6';
public const METHOD_MTR = 'mtr';
public const METHOD_MTR6 = 'mtr6';
public const METHOD_TRACEROUTE = 'traceroute';
public const METHOD_TRACEROUTE6 = 'traceroute6';
private const MTR_COUNT = 10;
/**
* Validates the config.php file for required constants.
*
* @return void
*/
public static function validateConfig(): void
{
//@formatter:off
if (!defined('LG_TITLE')) {
die('LG_TITLE not found in config.php');
}
if (!defined('LG_LOGO')) {
die('LG_LOGO not found in config.php');
}
if (!defined('LG_LOGO_DARK')) {
die('LG_LOGO_DARK not found in config.php');
}
if (!defined('LG_LOGO_URL')) {
die('LG_LOGO_URL not found in config.php');
}
if (!defined('LG_CSS_OVERRIDES')) {
die('LG_CSS_OVERRIDES not found in config.php');
}
if (!defined('LG_BLOCK_NETWORK')) {
die('LG_BLOCK_NETWORK not found in config.php');
}
if (!defined('LG_BLOCK_LOOKINGGLASS')) {
die('LG_BLOCK_LOOKINGGLASS not found in config.php');
}
if (!defined('LG_BLOCK_SPEEDTEST')) {
die('LG_BLOCK_SPEEDTEST not found in config.php');
}
if (!defined('LG_BLOCK_CUSTOM')) {
die('LG_BLOCK_CUSTOM not found in config.php');
}
if (!defined('LG_CUSTOM_HTML')) {
die('LG_CUSTOM_HTML not found in config.php');
}
if (!defined('LG_CUSTOM_PHP')) {
die('LG_CUSTOM_PHP not found in config.php');
}
if (!defined('LG_LOCATION')) {
die('LG_LOCATION not found in config.php');
}
if (!defined('LG_MAPS_QUERY')) {
die('LG_MAPS_QUERY not found in config.php');
}
if (!defined('LG_FACILITY')) {
die('LG_FACILITY not found in config.php');
}
if (!defined('LG_FACILITY_URL')) {
die('LG_FACILITY_URL not found in config.php');
}
if (!defined('LG_IPV4')) {
die('LG_IPV4 not found in config.php');
}
if (!defined('LG_IPV6')) {
die('LG_IPV6 not found in config.php');
}
if (!defined('LG_METHODS')) {
die('LG_METHODS not found in config.php');
}
if (!defined('LG_LOCATIONS')) {
die('LG_LOCATIONSnot found in config.php');
}
if (!defined('LG_SPEEDTEST_IPERF')) {
die('LG_SPEEDTEST_IPERF not found in config.php');
}
if (!defined('LG_SPEEDTEST_LABEL_INCOMING')) {
die('LG_SPEEDTEST_LABEL_INCOMING not found in config.php');
}
if (!defined('LG_SPEEDTEST_CMD_INCOMING')) {
die('LG_SPEEDTEST_CMD_INCOMING not found in config.php');
}
if (!defined('LG_SPEEDTEST_LABEL_OUTGOING')) {
die('LG_SPEEDTEST_LABEL_OUTGOING not found in config.php');
}
if (!defined('LG_SPEEDTEST_CMD_OUTGOING')) {
die('LG_SPEEDTEST_CMD_OUTGOING not found in config.php');
}
if (!defined('LG_SPEEDTEST_FILES')) {
die('LG_SPEEDTEST_FILES not found in config.php');
}
if (!defined('LG_TERMS')) {
die('LG_TERMS not found in config.php');
}
if (!defined('LG_CHECK_LATENCY')) {
die('LG_CHECK_LATENCY not found in config.php');
}
if (!defined('LG_THEME')) {
die('LG_THEME not found in config.php');
}
//@formatter:on
}
/**
* Starts a PHP session and sets security tokens.
*
* @return void
*/
public static function startSession(): void
{
session_name('HYLOOKINGLASS');
@session_start([
'cookie_httponly' => true,
'cookie_secure' => true,
'cookie_samesite' => 'Strict',
]) or die('Could not start session!');
}
/**
* Validates and checks an IPv4 address.
*
* @param string $ip The IPv4 address to validate.
* @return bool True or false depending on validation.
*/
public static function isValidIpv4(string $ip): bool
{
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return true;
}
return false;
}
/**
* Validates and checks an IPv6 address.
*
* @param string $ip The IPv6 address to validate.
* @return bool True or false depending on validation.
*/
public static function isValidIpv6(string $ip): bool
{
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
return false;
}
$binary = inet_pton($ip);
if ($binary === false) {
return false;
}
$hex = bin2hex($binary);
// Block 6to4 (2002::/16) — embeds arbitrary IPv4 in bytes 3-6
if (str_starts_with($hex, '2002')) {
return false;
}
// Block Teredo (2001:0000::/32) — embeds arbitrary IPv4 in bytes 13-16
if (str_starts_with($hex, '20010000')) {
return false;
}
// Block documentation (2001:db8::/32) — not routable
if (str_starts_with($hex, '20010db8')) {
return false;
}
return true;
}
/**
* Validates and checks a host address.
* Differs from isValidIpvX because it also extracts the host.
*
* @param string $host The host to validate.
* @return string Actual hostname or empty if none found.
*/
public static function isValidHost(string $host, string $type): string
{
$host = str_replace(['http://', 'https://', ';', ',', '\\'], '', $host);
if (!substr_count($host, '.')) {
return '';
}
if (filter_var('https://'.$host, FILTER_VALIDATE_URL)) {
if ($host = parse_url('https://'.$host, PHP_URL_HOST)) {
if ($type === self::IPV4) {
$resolved = dns_get_record($host, DNS_A)[0]['ip'] ?? '';
if ($resolved && self::isValidIpv4($resolved)) {
return $resolved;
}
}
if ($type === self::IPV6) {
$resolved = dns_get_record($host, DNS_AAAA)[0]['ipv6'] ?? '';
if ($resolved && self::isValidIpv6($resolved)) {
return $resolved;
}
}
return '';
}
}
return '';
}
/**
* Determine the IP address of the client.
* Also supports clients behind a proxy, however we need to validate this as this header can be spoofed.
* The REMOTE_ADDR header is secure because it's populated by the webserver (extracted from TCP packets).
*
* @return string The IP address of the client.
*/
public static function detectIpAddress(): string
{
if (php_sapi_name() === 'cli') {
return '127.0.0.1';
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && filter_var($_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)) {
return $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
return $_SERVER['REMOTE_ADDR'];
}
}
/**
* Executes a ping command.
*
* @param string $host The target host.
* @param int $count Number of requests.
* @return bool True on success.
*/
public static function ping(string $host, int $count = 4): bool
{
return self::procExecute(['ping', '-4', '-c', $count, '-w15'], $host);
}
/**
* Executes a ping6 command.
*
* @param string $host The target host.
* @param int $count Number of requests.
* @return bool True on success.
*/
public static function ping6(string $host, int $count = 4): bool
{
return self::procExecute(['ping', '-6', '-c', $count, '-w15'], $host);
}
/**
* Executes a mtr command.
*
* @param string $host The target host.
* @return bool True on success.
*/
public static function mtr(string $host): bool
{
return self::procExecute(['mtr', '--raw', '-4', '--mpls', '-c', self::MTR_COUNT], $host);
}
/**
* Executes a mtr6 command.
*
* @param string $host The target host.
* @return bool True on success.
*/
public static function mtr6(string $host): bool
{
return self::procExecute(['mtr', '--raw', '-6', '--mpls', '-c', self::MTR_COUNT], $host);
}
/**
* Executes a traceroute command.
*
* @param string $host The target host.
* @param int $failCount Number of failed hops.
* @return bool True on success.
*/
public static function traceroute(string $host, int $failCount = 4): bool
{
return self::procExecute(['traceroute', '-4', '-w2'], $host, $failCount);
}
/**
* Executes a traceroute6 command.
*
* @param string $host The target host.
* @param int $failCount Number of failed hops.
* @return bool True on success.
*/
public static function traceroute6(string $host, int $failCount = 4): bool
{
return self::procExecute(['traceroute', '-6', '-w2'], $host, $failCount);
}
/**
* Executes a command and opens pipe for input/output.
* Directly taken from telephone/LookingGlass (MIT License)
*
* @param array $cmd The command to execute.
* @param string $host The host that is used as param.
* @param int $failCount Number of consecutive failed hops.
* @return boolean True on success.
* @link https://github.com/telephone/LookingGlass/blob/master/LookingGlass/LookingGlass.php#L172
* @license https://github.com/telephone/LookingGlass/blob/master/LICENCE.txt
*/
private static function procExecute(array $cmd, string $host, int $failCount = 2): bool
{
// define output pipes
$spec = [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w']
];
// sanitize + remove single quotes
$cmd[] = str_replace('\'', '', filter_var($host, FILTER_SANITIZE_URL));
// execute command
$process = proc_open($cmd, $spec, $pipes, null);
// check pipe exists
if (!is_resource($process)) {
return false;
}
$family = self::IPV4;
if (in_array('-6', $cmd)) {
$family = self::IPV6;
}
// check for mtr/traceroute
if ($cmd[0] == 'mtr') {
$type = 'mtr';
$parser = new Parser($host, $family);
} elseif ($cmd[0] == 'traceroute') {
$type = 'traceroute';
} else {
$type = '';
}
$fail = 0;
$match = 0;
$traceCount = 0;
$lastFail = 'start';
// iterate stdout
while (($str = fgets($pipes[1], 4096)) != null) {
// check for output buffer
if (ob_get_level() == 0) {
ob_start();
}
// fix RDNS XSS (outputs non-breakble space correctly)
$str = htmlspecialchars(trim($str));
// correct output for mtr
if ($type === 'mtr') {
// correct output for mtr
$parser->update($str);
echo '@@@'.PHP_EOL.$parser->__toString().PHP_EOL.str_pad('', 4096).PHP_EOL;
// flush output buffering
@ob_flush();
flush();
continue;
} // correct output for traceroute
elseif ($type === 'traceroute') {
if ($match < 10 && preg_match('/^[0-9] /', $str, $string)) {
$str = preg_replace('/^[0-9] /', ' '.$string[0], $str);
$match++;
}
// check for consecutive failed hops
if (strpos($str, '* * *') !== false) {
$fail++;
if ($lastFail !== 'start'
&& ($traceCount - 1) === $lastFail
&& $fail >= $failCount
) {
echo str_pad($str.'<br />-- Traceroute timed out --<br />', 4096, ' ', STR_PAD_RIGHT);
break;
}
$lastFail = $traceCount;
}
$traceCount++;
}
// pad string for live output
echo str_pad($str.'<br />', 4096, ' ', STR_PAD_RIGHT);
// flush output buffering
@ob_flush();
flush();
}
// iterate stderr
while (($err = fgets($pipes[2], 4096)) != null) {
// check for IPv6 hostname passed to IPv4 command, and vice versa
if (strpos($err, 'Name or service not known') !== false || strpos($err, 'unknown host') !== false) {
echo 'Unauthorized request';
break;
}
}
$status = proc_get_status($process);
if ($status['running']) {
// close pipes that are still open
foreach ($pipes as $pipe) {
fclose($pipe);
}
if ($status['pid']) {
// use ps to get all the children of this process
$psOutput = shell_exec('ps -o pid= --no-heading --ppid ' . (int)$status['pid']);
if ($psOutput !== null) {
// Split the output into lines and filter numeric PIDs
$pids = preg_split('/\s+/', trim($psOutput));
foreach ($pids as $pid) {
if (is_numeric($pid)) {
posix_kill((int)$pid, 9);
}
}
}
}
proc_close($process);
}
return true;
}
public static function getLatency(): float
{
$getLatency = self::getLatencyFromSs(self::detectIpAddress());
if (isset($getLatency[0])) {
return round((float)$getLatency[0]['latency']);
} else {
return 0.00;
}
}
/**
* This uses the command 'ss' in order to find out latency.
* A clever way coded by @ayyylias, so please keep credits and do not just steal.
*
* @param string $ip The command to execute.
* @return array Returns an array with results.
*/
private static function getLatencyFromSs(string $ip): array
{
$ssPath = exec('which ss 2>/dev/null');
if (empty($ssPath)) {
// RHEL based systems;
$ssPath = '/usr/sbin/ss';
}
if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$ipSs = '['.$ip.']';
} else {
$ipSs = $ip;
}
$lines = shell_exec($ssPath.' -Hintp state established dst '.$ipSs);
$ss = [];
$i = 0;
$j = 0;
foreach (explode(PHP_EOL, $lines ?? '') as $line) {
if ($i > 1) {
$i = 0;
$j++;
}
if ($line !== '') {
@$ss[$j] .= $line;
$i++;
}
}
$output = [];
foreach ($ss as $socket) {
$socket = preg_replace('!\s+!', ' ', $socket);
$explodedsocket = explode(' ', $socket);
$temp = [];
if (strpos($explodedsocket[3], ']') !== false && strpos($explodedsocket[3], '::ffff') === false) {
// IPv6 address
preg_match('/\[(.*?)\]/', $explodedsocket[2], $temp);
$sock['local'] = $temp[1];
preg_match('/\[(.*?)\]/', $explodedsocket[3], $temp);
$sock['remote'] = $temp[1];
} else {
// IPv4 address
preg_match('/(\d+\.\d+\.\d+\.\d+)(:\d+)?/', $explodedsocket[2], $temp);
$sock['local'] = $temp[1];
preg_match('/(\d+\.\d+\.\d+\.\d+)(:\d+)?/', $explodedsocket[3], $temp);
$sock['remote'] = $temp[1];
}
preg_match('/segs_out:(\d+)/', $socket, $temp);
$sock['segs_out'] = $temp[1];
preg_match('/segs_in:(\d+)/', $socket, $temp);
$sock['segs_in'] = $temp[1];
preg_match_all('/rtt:(\d+\.\d+)\/(\d+\.\d+)/', $socket, $temp);
$sock['latency'] = $temp[1][0];
$sock['jitter'] = $temp[2][0];
preg_match_all('/retrans:\d+\/(\d+)/', $socket, $temp);
$sock['retransmissions'] = (isset($temp[1][0]) ? $temp[1][0] : 0);
if ($sock['remote'] == $ip || $sock['local'] == $ip) {
$output[] = $sock;
}
}
return $output;
}
}
class Hop
{
/** @var int */
public $idx;
/** @var string */
public $asn = null;
/** @var float */
public $avg = 0.0;
/** @var int */
public $loss = 0;
/** @var float */
public $stdev = 0.0;
/** @var int */
public $sent = 0;
/** @var int */
public $recieved = 0;
/** @var float */
public $last = 0.0;
/** @var float */
public $best = 0.0;
/** @var float */
public $worst = 0.0;
/** @var string[] */
public $ips = [];
/** @var string[] */
public $hosts = [];
/** @var float[] */
public $timings = [];
/** @var MplsInfo[] */
public $mplsInfo = [];
}
class RawHop
{
/** @var string */
public $dataType;
/** @var int */
public $idx;
/** @var string */
public $value;
/** @var string[] */
public $rawValue;
}
class MplsInfo
{
/** @var int */
public $label;
/** @var int */
public $trafficClass;
/** @var int */
public $bottomStack;
/** @var int */
public $ttl;
public function __construct(int $label, int $trafficClass, int $bottomStack, int $ttl)
{
$this->label = $label;
$this->trafficClass = $trafficClass;
$this->bottomStack = $bottomStack;
$this->ttl = $ttl;
}
public function __toString(): string
{
$str = sprintf('[MPLS: Lbl %d TC %d S %d TTL %d]',
$this->label, $this->trafficClass, $this->bottomStack, $this->ttl);
return $str;
}
}
class Parser
{
/** @var Hop[] */
protected $hopsCollection = [];
/** @var int */
private $hopCount = 0;
/** @var int */
private $outputWidth = 38;
/** @var string */
private $targetIp = '';
/** @var int */
private $targetIndex = null;
public function __construct(string $target, string $family)
{
if (LookingGlass::isValidIpv4($target) || LookingGlass::isValidIpv6($target)) {
$this->targetIp = $target;
} else {
$rrType = ($family === LookingGlass::IPV6 ? DNS_AAAA : DNS_A);
$key = ($family === LookingGlass::IPV6 ? 'ipv6' : 'ip');
$this->targetIp = @dns_get_record($target, $rrType)[0][$key] ?? '';
if ($family === LookingGlass::IPV6 && !empty($this->targetIp)) {
// Transform DNS result to standard inet_ntop representation, otherwise it wouldn't match.
$ipv6Binary = inet_pton($this->targetIp);
$this->targetIp = inet_ntop($ipv6Binary);
}
}
putenv('RES_OPTIONS=retrans:1 retry:1 timeout:1 attempts:1');
}
public function __toString(): string
{
$str = '';
$filteredHops = $this->filterLastDupeHop();
foreach ($filteredHops as $index => $hop) {
// Show first hop as 1 instead of 0
$index++;
$asn = '';
$hostAndIp = '';
if ($hop->recieved > 0) {
$asn = 'AS';
if (isset($hop->asn) && $hop->asn !== 0) {
$asn .= $hop->asn;
} else {
$asn .= '???';
}
if (isset($hop->hosts[0]) && !in_array($hop->hosts[0], $hop->ips)) {
// Show "example.com (192.0.2.234)" if there's a hostname
$hostAndIp = $hop->hosts[0] . ' (' . $hop->ips[0] . ')';
} else {
$hostAndIp = $hop->ips[0];
}
} else {
$hostAndIp = '(waiting for reply)';
}
$currentWidth = strlen($asn) + strlen($hostAndIp);
if ($currentWidth > $this->outputWidth) {
$this->outputWidth = $currentWidth;
}
if ($hop->recieved > 0) {
$hop->last = $hop->timings[count($hop->timings) - 1];
$hop->best = $hop->timings[0];
$hop->worst = $hop->timings[0];
$hop->avg = array_sum($hop->timings) / count($hop->timings);
if ($hop->recieved > 1) {
$hop->stdev = $this->stDev($hop->timings);
}
foreach ($hop->timings as $time) {
if ($hop->best > $time) {
$hop->best = $time;
}
if ($hop->worst < $time) {
$hop->worst = $time;
}
}
$hop->loss = $hop->sent ? (100 * ($hop->sent - $hop->recieved)) / $hop->sent : 100;
$hop->loss = max(0, $hop->loss);
$mplsInfoString = '';
if (!empty($hop->mplsInfo)) {
foreach ($hop->mplsInfo as $mplsInfo) {
$mplsInfoString .= "\n " . $mplsInfo->__toString();
}
}
}
$str = sprintf(
"%s%2d. %s%s%s%s",
$str,
$index,
$asn,
$asn ? ' ' : '',
str_pad($hostAndIp, $this->outputWidth - strlen($asn), ' ', STR_PAD_RIGHT),
$hop->recieved > 0 ? '' : "\n",
);
if ($hop->recieved > 0) {
$str .= sprintf(
"%3d.0%% %3d %5.1f %5.1f %5.1f %5.1f %5.1f%s\n",
$hop->loss,
$hop->sent,
$hop->last,
$hop->avg,
$hop->best,
$hop->worst,
$hop->stdev,
$mplsInfoString,
);
}
}
return sprintf(" Host%sLoss%% Snt Last Avg Best Wrst StDev\n%s",
str_pad('', $this->outputWidth + 1, ' ', STR_PAD_RIGHT), $str);
// +1 above ($this->outputWidth + 1) is to account for the space between $asn and $hostAndIp.
}
// Function to calculate standard deviation (uses sd_square)
private function stDev(array $array): float
{
$sdSquare = function ($x, $mean) {
return pow($x - $mean, 2);
};
// square root of sum of squares devided by N-1
return sqrt(array_sum(array_map($sdSquare, $array, array_fill(0, count($array), (array_sum($array) / count($array))))) / (count($array) - 1));
}
public function update($rawMtrInput)
{
//Store each line of output in rawhop structure
$things = explode(' ', $rawMtrInput);
if (count($things) !== 3 &&
(count($things) !== 4 && $things[0] === 'p') &&
(count($things) !== 6 && $things[0] === 'm')) {
return;
}
$rawHop = new RawHop();
$rawHop->dataType = $things[0];
$rawHop->idx = (int)$things[1];
$rawHop->value = $things[2];
$rawHop->rawValue = array_slice($things, 2);
if ($this->targetIndex !== null && $this->targetIndex < $rawHop->idx) {
// Reached target already
return;
}
if ($this->hopCount < $rawHop->idx + 1) {
$this->hopCount = $rawHop->idx + 1;
}
if (!isset($this->hopsCollection[$rawHop->idx])) {
$this->hopsCollection[$rawHop->idx] = new Hop();
}
$hop = $this->hopsCollection[$rawHop->idx];
$hop->idx = $rawHop->idx;
switch ($rawHop->dataType) {
// See: https://github.com/traviscross/mtr/blob/master/FORMATS
// dnsline – d <pos> <hostname>
case 'd':
$hop->hosts[] = $rawHop->value;
break;
// hostline – h <pos> <host IP>
case 'h':
$hop->ips[] = $rawHop->value;
$hop->ips = array_unique($hop->ips);
if (!isset($hop->asn)) {
$suffix = 'origin.asn.cymru.com';
if (filter_var($hop->ips[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$suffix = 'origin6.asn.cymru.com';
}
$reversedIp = $this->reverseIp($hop->ips[0]);
$qname = $reversedIp . '.' . $suffix;
$dnsResult = @dns_get_record($qname, DNS_TXT)[0]['txt'] ?? '';
// See: https://www.team-cymru.com/ip-asn-mapping ("DNS" section).
// Set to 0 in case of errors so we avoid querying again.
$hop->asn = explode(' ', $dnsResult)[0] ?: 0;
}
if (in_array($this->targetIp, $hop->ips)) {
if (!isset($this->targetIndex) || $this->targetIndex > $hop->idx) {
$this->targetIndex = $hop->idx;
foreach ($this->hopsCollection as $key => $hop) {
if ($key > $this->targetIndex) {
unset($this->hopsCollection[$key]);
}
}
}
}
break;
// mplsline – m <pos> <label> <traffic_class> <bottom_stack> <ttl>
case 'm':
$hop->mplsInfo[] = new MplsInfo(...array_map('intval', $rawHop->rawValue));
$hop->mplsInfo = array_unique($hop->mplsInfo);
break;
// pingline – p <pos> <pingtime (usec)> <seqnum>
case 'p':
$hop->recieved++;
$hop->timings[] = (float)$rawHop->value / 1000;
break;
// xmitline – x <pos> <seqnum>
case 'x':
$hop->sent++;
break;
}
$this->hopsCollection[$rawHop->idx] = $hop;
}
// filter dupe last hop
private function filterLastDupeHop(): array
{
$finalIdx = 0;
$previousIp = '';
$newHops = [];
$hops = $this->hopsCollection;
foreach ($hops as $key => $hop) {
if (count($hop->ips) && $hop->ips[0] !== $previousIp) {
$previousIp = $hop->ips[0];
$finalIdx = $key + 1;
}
}
$newHops = $hops;
foreach ($hops as $key => $hop) {
if ($key >= $finalIdx) {
unset($newHops[$key]);
}
}
if (!isset($this->targetIndex)) {
// Show one "waiting for reply" hop it we haven't reached target yet.
$waitingHop = new Hop();
$newHops[$finalIdx++] = $waitingHop;
}
return $newHops;
}
private function reverseIp(string $ip): string
{
$reversed = '';
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
$reversed = implode('.', array_reverse(explode('.', $ip)));
}
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$ipBinary = inet_pton($ip);
$ipHex = bin2hex($ipBinary);
$reversed = implode('.', array_reverse(str_split($ipHex)));
}
return $reversed;
}
}