-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
57 lines (50 loc) · 1.25 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
const url = require('url'),
net = require('net'),
events = require('events'),
{safe} = require('./src/util.js'),
Tunnel = require('./src/tunnel.js');
class Proxy extends events {
constructor(host, to) {
super();
this.uri = {
host: url.parse((host.match(/^.*?:\/\//)) ? host : 'tcp://' + host),
to: url.parse((to.match(/^.*?:\/\//)) ? to : 'tcp://' + to)
};
this.alive = false;
this.tunnel = {};
this.server = net.createServer((socket) => {
let t = new Tunnel(socket, this.uri.to);
t.on('connect', () => {
this.emit('connect', t);
});
t.on('close', () => this.tunnel[t.key] = null);
this.tunnel[t.key] = t;
});
this.server.on('error', (e) => {
this.emit('error', e);
}).on('close', (e) => {
this.emit('close', e);
this.close();
}).listen({host: this.uri.host.hostname, port: this.uri.host.port}, () => {
this.alive = true;
this.emit('open');
});
}
close() {
if (!this.alive) {
return Promise.resolve();
}
this.alive = false;
for (let i in this.tunnel) {
if (this.tunnel[i]) {
this.tunnel[i].close();
}
}
safe(() => this.server.close());
safe(() => this.server.destroy());
return Promise.resolve();
}
}
Proxy.RX = 'recieved';
Proxy.TX = 'transmitted';
module.exports = Proxy;