-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathtcp_tunnel_tools.ts
More file actions
139 lines (110 loc) · 4.07 KB
/
tcp_tunnel_tools.ts
File metadata and controls
139 lines (110 loc) · 4.07 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
import { randomUUID } from 'node:crypto';
import net from 'node:net';
import { URL } from 'node:url';
import { chain } from './chain';
import { nodeify } from './utils/nodeify';
const runningServers: Record<string, { server: net.Server, connections: Set<net.Socket> }> = {};
const getAddress = (server: net.Server) => {
const { address: host, port, family } = server.address() as net.AddressInfo;
if (family === 'IPv6') {
return `[${host}]:${port}`;
}
return `${host}:${port}`;
};
export async function createTunnel(
proxyUrl: string,
targetHost: string,
options?: {
verbose?: boolean;
ignoreProxyCertificate?: boolean;
},
callback?: (error: Error | null, result?: string) => void,
): Promise<string> {
const parsedProxyUrl = new URL(proxyUrl);
if (!['http:', 'https:'].includes(parsedProxyUrl.protocol)) {
throw new Error(`The proxy URL must have the "http" or "https" protocol (was "${proxyUrl}")`);
}
const url = new URL(`connect://${targetHost || ''}`);
if (!url.hostname) {
throw new Error('Missing target hostname');
}
if (!url.port) {
throw new Error('Missing target port');
}
const verbose = options && options.verbose;
const server: net.Server & { log?: (...args: unknown[]) => void } = net.createServer();
const log = (...args: unknown[]): void => {
// eslint-disable-next-line no-console
if (verbose) console.log(...args);
};
server.log = log;
server.on('connection', (sourceSocket) => {
const remoteAddress = `${sourceSocket.remoteAddress}:${sourceSocket.remotePort}`;
const { connections } = runningServers[getAddress(server)];
log(`new client connection from ${remoteAddress}`);
sourceSocket.on('close', (hadError) => {
connections.delete(sourceSocket);
log(`connection from ${remoteAddress} closed, hadError=${hadError}`);
});
connections.add(sourceSocket);
chain({
request: { url: targetHost },
sourceSocket,
handlerOpts: {
upstreamProxyUrlParsed: parsedProxyUrl,
ignoreUpstreamProxyCertificate: options?.ignoreProxyCertificate ?? false,
requestId: randomUUID(),
customTag: undefined,
id: -1,
},
server: server as net.Server & { log: typeof log },
isPlain: true,
});
});
const promise = new Promise<string>((resolve, reject) => {
server.once('error', reject);
// Let the system pick a random listening port
server.listen(0, () => {
const address = getAddress(server);
server.off('error', reject);
runningServers[address] = { server, connections: new Set() };
log('server listening to ', address);
resolve(address);
});
});
return nodeify(promise, callback);
}
export async function closeTunnel(
serverPath: string,
closeConnections: boolean | undefined,
callback: (error: Error | null, result?: boolean) => void,
): Promise<boolean> {
const { hostname, port } = new URL(`tcp://${serverPath}`);
if (!hostname) throw new Error('serverPath must contain hostname');
if (!port) throw new Error('serverPath must contain port');
const promise = new Promise((resolve) => {
if (!runningServers[serverPath]) {
resolve(false);
return;
}
if (!closeConnections) {
resolve(true);
return;
}
for (const connection of runningServers[serverPath].connections) {
connection.destroy();
}
resolve(true);
})
.then(async (serverExists) => new Promise<boolean>((resolve) => {
if (!serverExists) {
resolve(false);
return;
}
runningServers[serverPath].server.close(() => {
delete runningServers[serverPath];
resolve(true);
});
}));
return nodeify(promise, callback);
}