-
Notifications
You must be signed in to change notification settings - Fork 22
/
traceroute.js
129 lines (88 loc) · 2.64 KB
/
traceroute.js
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
'use strict';
const Child = require('child_process');
const Dns = require('dns');
const EventEmitter = require('events');
const Net = require('net');
const Os = require('os');
const Util = require('util');
const internals = {};
internals.isWin = /^win/.test(Os.platform());
module.exports = internals.Traceroute = {};
internals.Traceroute.trace = function (host, callback) {
const Emitter = function () {
EventEmitter.call(this);
};
Util.inherits(Emitter, EventEmitter);
const emitter = new Emitter();
Dns.lookup(host.toUpperCase(), (err) => {
if (err && Net.isIP(host) === 0) {
return callback(new Error('Invalid host'));
}
const command = (internals.isWin ? 'tracert' : 'traceroute');
const args = internals.isWin ? ['-d', host] : ['-q', 1, '-n', host];
const traceroute = Child.spawn(command, args);
const hops = [];
let counter = 0;
traceroute.stdout.on('data', (data) => {
++counter;
if ((!internals.isWin && counter < 2) || (internals.isWin && counter < 5)) {
return null;
}
const result = data.toString().replace(/\n$/,'');
if (!result) {
return null;
}
const hop = internals.parseHop(result);
hops.push(hop);
emitter.emit('hop', hop);
});
traceroute.on('close', (code) => {
if (callback) {
callback(null, hops);
}
emitter.emit('done', hops);
});
});
return emitter;
};
internals.parseHop = function (hop) {
let line = hop.replace(/\*/g,'0');
if (internals.isWin) {
line = line.replace(/\</g,'');
}
const s = line.split(' ');
for (let i = s.length - 1; i > -1; --i) {
if (s[i] === '' || s[i] === 'ms') {
s.splice(i,1);
}
}
return internals.isWin ? internals.parseHopWin(s) : internals.parseHopNix(s);
};
internals.parseHopWin = function (line) {
if (line[4] === 'Request') {
return false;
}
const hop = {};
hop[line[4]] = [+line[1], +line[2], +line[3]];
return hop;
};
internals.parseHopNix = function (line) {
if (line[1] === '0') {
return false;
}
const hop = {};
let lastip = line[1];
hop[line[1]] = [+line[2]];
for (let i = 3; i < line.length; ++i) {
if (Net.isIP(line[i])) {
lastip = line[i];
if (!hop[lastip]) {
hop[lastip] = [];
}
}
else {
hop[lastip].push(+line[i]);
}
}
return hop;
};