-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtunnel.ts
More file actions
170 lines (145 loc) · 6.26 KB
/
tunnel.ts
File metadata and controls
170 lines (145 loc) · 6.26 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
import * as net from 'net';
import { activeConnections, serverIp } from './state';
export const TUNNEL_SERVER_PORT = 13337;
interface TunnelEntry {
targetSocket: net.Socket;
connectionId: string;
remotePort: number;
}
export interface LocalTunnel {
server: net.Server;
localPort: number;
connectionId: string;
remotePort: number;
}
const waitingTargetSockets: TunnelEntry[] = [];
export const activeTunnels = new Map<string, LocalTunnel>();
const tunnelServer = net.createServer((targetSocket) => {
console.log(`[tunnel] target connected from ${targetSocket.remoteAddress}:${targetSocket.remotePort}`);
let headerBuf = '';
// Send READY signal so client knows it can send the TUNNEL header
targetSocket.write('READY\n');
const onData = (chunk: Buffer) => {
console.log(`[tunnel] onData ${chunk.length} bytes, hex: ${chunk.toString('hex')}`);
headerBuf += chunk.toString();
const nlIdx = headerBuf.indexOf('\n');
console.log(`[tunnel] nlIdx=${nlIdx} headerBuf.length=${headerBuf.length}`);
if (nlIdx === -1) return;
targetSocket.off('data', onData);
const line = headerBuf.slice(0, nlIdx).trim();
const parts = line.split(' ');
console.log(`[tunnel] parsed: parts=${JSON.stringify(parts)} keys=${[...activeTunnels.keys()]}`);
if (parts.length < 3 || parts[0] !== 'TUNNEL') {
console.log(`[tunnel] bad header: ${line}`);
targetSocket.destroy();
return;
}
const connectionId = parts[1];
const remotePort = parseInt(parts[2]);
if (!activeTunnels.has(`${connectionId}:${remotePort}`)) {
console.log(`[tunnel] no active tunnel for ${connectionId}:${remotePort}`);
targetSocket.destroy();
return;
}
console.log(`[tunnel] target registered: ${connectionId}:${remotePort}`);
waitingTargetSockets.push({ targetSocket, connectionId, remotePort });
targetSocket.on('close', () => {
console.log(`[tunnel] target socket closed: ${connectionId}:${remotePort}`);
const idx = waitingTargetSockets.findIndex((e) => e.targetSocket === targetSocket);
if (idx !== -1) waitingTargetSockets.splice(idx, 1);
});
targetSocket.on('error', (err) => { console.log(`[tunnel] target socket error: ${err.message}`); });
};
targetSocket.on('data', onData);
targetSocket.on('error', () => {});
});
tunnelServer.listen(TUNNEL_SERVER_PORT, '0.0.0.0', () => {
console.log(`[*] Tunnel server listening on port ${TUNNEL_SERVER_PORT}`);
});
function popWaitingSocket(connectionId: string, remotePort: number): net.Socket | null {
const idx = waitingTargetSockets.findIndex(
(e) => e.connectionId === connectionId && e.remotePort === remotePort,
);
if (idx === -1) return null;
const [entry] = waitingTargetSockets.splice(idx, 1);
return entry.targetSocket;
}
function bridge(a: net.Socket, b: net.Socket) {
a.pipe(b);
b.pipe(a);
const destroy = () => { try { a.destroy(); } catch {} try { b.destroy(); } catch {} };
a.on('close', destroy);
b.on('close', destroy);
a.on('error', destroy);
b.on('error', destroy);
}
export function requestTargetTunnel(connectionId: string, remotePort: number) {
const connInfo = activeConnections.get(connectionId);
if (!connInfo) { console.log(`[tunnel] requestTargetTunnel: no connection ${connectionId}`); return; }
console.log(`[tunnel] requesting client tunnel: remote=${remotePort} server=${serverIp}:${TUNNEL_SERVER_PORT} conn=${connectionId}`);
connInfo.socket.write(`\x1b[9;${remotePort};${TUNNEL_SERVER_PORT};${serverIp};${connectionId}t`);
}
export function findAvailablePort(start: number): Promise<number> {
const port = start > 65535 ? 40000 : start;
return new Promise((resolve, reject) => {
const probe = net.createServer();
probe.listen(port, '127.0.0.1', () => {
probe.close(() => resolve(port));
});
probe.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'EADDRINUSE' && port < 65534) {
resolve(findAvailablePort(port + 1));
} else {
reject(new Error(`No available port starting from ${start}`));
}
});
});
}
export function registerTunnel(
connectionId: string,
remotePort: number,
localPort: number,
): Promise<void> {
const key = `${connectionId}:${remotePort}`;
if (activeTunnels.has(key)) {
return Promise.reject(new Error(`Tunnel ${key} already active`));
}
const bindHost = '0.0.0.0';
return new Promise((resolve, reject) => {
const localServer = net.createServer((localSocket) => {
console.log(`[tunnel] local connection on port ${localPort} for ${connectionId}:${remotePort}`);
const tryBridge = (attempts: number) => {
const ts = popWaitingSocket(connectionId, remotePort);
if (ts) {
console.log(`[tunnel] bridged ${connectionId}:${remotePort}`);
bridge(localSocket, ts);
requestTargetTunnel(connectionId, remotePort);
return;
}
if (attempts <= 0) {
console.log(`[tunnel] bridge timeout ${connectionId}:${remotePort}, no target socket arrived`);
localSocket.destroy();
return;
}
requestTargetTunnel(connectionId, remotePort);
setTimeout(() => tryBridge(attempts - 1), 200);
};
tryBridge(25);
});
localServer.listen(localPort, bindHost, () => {
activeTunnels.set(key, { server: localServer, localPort, connectionId, remotePort });
resolve();
});
localServer.on('error', reject);
});
}
export function unregisterTunnel(connectionId: string, remotePort: number) {
const key = `${connectionId}:${remotePort}`;
const tunnel = activeTunnels.get(key);
if (!tunnel) return;
tunnel.server.close();
activeTunnels.delete(key);
waitingTargetSockets
.filter((e) => e.connectionId === connectionId && e.remotePort === remotePort)
.forEach((e) => e.targetSocket.destroy());
}