-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
executable file
·63 lines (51 loc) · 1.61 KB
/
index.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
let net = require('net');
let EventEmitter = require('events').EventEmitter;
const DEFAULT_PORT = 41144;
const TIMEOUT = 1000;
class TSDNS extends EventEmitter {
constructor(port, host) {
super();
this.server = net.createServer().listen(port || DEFAULT_PORT, host);
this.server.on('listening', this.emit.bind(this, 'listening'));
this.server.on('error', this.emit.bind(this, 'error'));
this.server.on('close', this.emit.bind(this, 'close'));
this.server.on('connection', this._onConnection.bind(this));
}
address() {
return this.server.address();
}
close(cb) {
this.on('close', cb);
this.server.close();
}
_onConnection(socket) {
socket.setEncoding('utf8');
socket.setNoDelay(true);
socket.setTimeout(TIMEOUT);
socket.unref();
socket.on('error', this.emit.bind(this, 'socket-error', socket));
socket.on('close', this.emit.bind(this, 'socket-close', socket));
socket.on('timeout', this.emit.bind(this, 'socket-timeout', socket));
socket.on('timeout', _ => socket.destroy());
socket.once('data', this.emit.bind('socket-data', socket));
socket.once('data', this._onData.bind(this, socket));
}
_onData(socket, data) {
let responded = false;
function respond(address, port) {
if (responded) return;
if (address && port) {
socket.end(`${address}:${port}`);
} else {
socket.end('404');
}
responded = true;
}
this.emit('request',
data.toLowerCase(), respond,
socket.remoteAddress, socket.remotePort,
socket
);
}
}
module.exports = TSDNS;