-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
77 lines (63 loc) · 1.88 KB
/
Copy pathindex.js
File metadata and controls
77 lines (63 loc) · 1.88 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
'use strict'
const net = require('net');
const WebSocketServer = require('ws').Server;
const log = msg => console.log(new Date(), msg);
module.exports = (server, sockets) => {
let targets = [];
if(typeof(sockets) == "object"){
sockets.forEach(t => {
targets.push({
host: t.target.split(':')[0],
port: t.target.split(':')[1],
connection: {},
path: t.path
});
});
};
let clientAddr = null;
for(let target of targets){
target.ws = new WebSocketServer({ noServer: true, ...target.path });
target.ws.on('connection', (client, req) => {
let cId = Date.now();
if(!clientAddr) clientAddr = client._socket.remoteAddress;
target.connection[cId] = net.createConnection(target.port, target.host, () => {
log(`${clientAddr} -> Connected to target on ${target.host}:${target.port}`)
});
target.connection[cId].on('data', data => {
try {
client.send(data)
} catch (e) {
log(`${clientAddr} -> Client closed, cleaning up target`)
target.connection[cId].end()
};
});
target.connection[cId].on('end', () => {
log(`${clientAddr} -> Target disconnected`)
client.close()
});
target.connection[cId].on('error', () => {
log(`${clientAddr} -> Connection error`)
target.connection[cId].end()
client.close()
});
client.on('message', msg => {
target.connection[cId].write(msg)
});
client.on('close', (code, reason) => {
log(`WebSocket client disconnected: ${code} [ ${reason} ]`);
target.connection[cId].end();
});
client.on('error', error => {
log(`${clientAddr} -> WS Client error`);
target.connection[cId].end();
});
});
server.on('upgrade', (request, socket, head) => {
if(request.url == target.path){
target.ws.handleUpgrade(request, socket, head, (ws) => {
target.ws.emit('connection', ws, request);
});
};
});
}
}