@johnhenry/wsh 0.35.0 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +453 -21
- package/package.json +18 -1
- package/src/bridge-seal.mjs +77 -0
- package/src/channel-binding.mjs +124 -0
- package/src/client.mjs +351 -62
- package/src/e2e-exchange.mjs +51 -1
- package/src/features.mjs +28 -0
- package/src/forward-node.mjs +118 -0
- package/src/gateway-channel.mjs +250 -0
- package/src/gateway-client.mjs +252 -0
- package/src/host-backends.mjs +100 -0
- package/src/host.d.ts +146 -0
- package/src/host.mjs +30 -0
- package/src/index.d.ts +114 -0
- package/src/index.mjs +13 -0
- package/src/memory-host.d.ts +34 -3
- package/src/memory-host.mjs +57 -13
- package/src/messages.gen.mjs +59 -7
- package/src/operator-proof.mjs +135 -0
- package/src/pipe-relay.d.ts +49 -0
- package/src/pipe-relay.mjs +274 -0
- package/src/reverse-host.d.ts +25 -0
- package/src/reverse-host.mjs +339 -0
- package/src/server/address-guard.mjs +164 -0
- package/src/server/backends.mjs +10 -16
- package/src/server/client-env.mjs +60 -0
- package/src/server/connection.mjs +100 -23
- package/src/server/constants.mjs +3 -0
- package/src/server/fs.mjs +2 -3
- package/src/server/gateway-core.mjs +188 -0
- package/src/server/gateway.mjs +483 -80
- package/src/server/index.d.ts +103 -5
- package/src/server/index.mjs +25 -4
- package/src/server/pty.mjs +1 -0
- package/src/server/relay.mjs +45 -2
- package/src/server/reverse-host.mjs +7 -213
- package/src/server/socket.mjs +25 -4
- package/src/server/unix-policy.mjs +120 -0
- package/src/server/webtransport.mjs +2 -0
- package/src/transport-ws.mjs +16 -0
- package/src/transport.mjs +11 -0
package/src/server/gateway.mjs
CHANGED
|
@@ -1,44 +1,62 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Gateway for the Node server: the TCP and DNS half of the wire protocol's
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* `GatewayBackend` from `@johnhenry/browsermesh-netway`) open TCP connections
|
|
6
|
-
*
|
|
7
|
-
* (an MQTT broker, a database) that a browser cannot.
|
|
2
|
+
* Gateway for the Node server: the TCP and DNS half of the wire protocol's gateway opcodes (0x70-0x7f), which until
|
|
3
|
+
* now only the Rust `wsh-server` answered, plus unix-domain socket forwarding (`OpenUnix`, `ListenUnix`) and named
|
|
4
|
+
* virtual endpoints (`OpenEndpoint`). It lets an authenticated client (typically a browser tab running
|
|
5
|
+
* `GatewayBackend` from `@johnhenry/browsermesh-netway`) open TCP connections and resolve names FROM THE HOST, so a
|
|
6
|
+
* page can reach a plain-TCP service (an MQTT broker, a database) that a browser cannot.
|
|
8
7
|
*
|
|
9
|
-
* Off unless `createWshServer({ gateway })` is given, and then default-deny:
|
|
10
|
-
*
|
|
11
|
-
* `"
|
|
12
|
-
*
|
|
13
|
-
*
|
|
8
|
+
* Off unless `createWshServer({ gateway })` is given, and then default-deny: a destination must match `allow`.
|
|
9
|
+
* Pattern forms (the same as the Rust policy): `"*"` any host and port, `"host"` that name on any port,
|
|
10
|
+
* `"host:port"`. The pattern is matched against the NAME the client asked for, case-insensitively, and then the
|
|
11
|
+
* ADDRESS it resolves to is checked as well: the host resolves the name once, refuses every address that is not
|
|
12
|
+
* globally routable (loopback, private, link-local, CGNAT, ULA, multicast, reserved, and IPv4 wrapped in IPv6 as
|
|
13
|
+
* mapped, NAT64 or 6to4 forms) unless a rule says otherwise, and connects to that same address, so a name that
|
|
14
|
+
* resolves differently a moment later cannot redirect the connection. Rules that say otherwise: `allowPrivate`
|
|
15
|
+
* (CIDR blocks or addresses the host may dial even though they are not public), and an allow entry that is itself
|
|
16
|
+
* an IP literal (`"127.0.0.1:1883"`), which permits exactly that address. `ResolveDns` answers are filtered with
|
|
17
|
+
* the same rule. With `socks` set the name is handed to the proxy unresolved, so the host never looks it up and
|
|
18
|
+
* cannot check what it resolves to (the proxy's network is then the egress); IP literals are still checked.
|
|
14
19
|
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
20
|
+
* Flow control: with "gateway-credit" negotiated each direction of each connection is metered (see
|
|
21
|
+
* `src/gateway-channel.mjs`); with an older peer the host bounds its buffering by `maxBufferedBytes` per connection
|
|
22
|
+
* and `maxClientBufferedBytes` per client and closes a connection that exceeds them.
|
|
17
23
|
*
|
|
18
|
-
* `
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
24
|
+
* `OpenUdp` is served over the same reliable control stream (one GatewayData = one datagram; same destination policy;
|
|
25
|
+
* a datagram the client cannot take fast enough is dropped; idle flows are closed after `udpIdleMs`). WebTransport
|
|
26
|
+
* datagrams are not used yet (#124). Not implemented, and answered with a clean ListenFail rather than silence: TCP
|
|
27
|
+
* reverse tunnels (`ListenRequest`).
|
|
28
|
+
*
|
|
29
|
+
* `socks`: dial through a SOCKS5 proxy (`'host:port'`, `socks5://host:port` or `{ host, port }`), e.g. a local Tor
|
|
30
|
+
* client (`127.0.0.1:9050`). Commands carry the destination as a domain name (ATYP 3), so name resolution happens at
|
|
31
|
+
* the proxy (no DNS leak) and `.onion` names work. In that mode `ResolveDns` is refused.
|
|
32
|
+
*
|
|
33
|
+
* `unix: { connect, listen, replaceStale }` (Node only): sockets in the host's file system a client may connect to
|
|
34
|
+
* or create. Off unless given. See `unix-policy.mjs`. `endpoints: { name: handler }`: named virtual endpoints.
|
|
23
35
|
*/
|
|
24
36
|
|
|
25
|
-
import { MSG, gatewayOk,
|
|
37
|
+
import { MSG, gatewayOk, dnsResult, listenOk, listenFail, inboundOpen } from '../messages.gen.mjs';
|
|
38
|
+
import {
|
|
39
|
+
GATEWAY_FAIL, HALF_CLOSE_GRACE_MS, gatewayFeatures, createGatewayCore, normalizeGatewayLimits, normalizeEndpoints,
|
|
40
|
+
} from './gateway-core.mjs';
|
|
41
|
+
import { isPublicAddress, parseCidr, addressInCidr, parseIp, sameAddress } from './address-guard.mjs';
|
|
26
42
|
|
|
27
43
|
// Loaded on first use so that importing the connection handler (which serves the gateway opcodes)
|
|
28
44
|
// does not pull `node:net` into a browser bundle (see `src/memory-host.mjs`).
|
|
29
45
|
let netModule = null;
|
|
30
46
|
let dnsModule = null;
|
|
47
|
+
let unixModule = null;
|
|
31
48
|
const loadNet = async () => (netModule ??= (await import('node:net')).default);
|
|
32
49
|
const loadDns = async () => (dnsModule ??= (await import('node:dns/promises')).default);
|
|
50
|
+
const loadUnix = async () => (unixModule ??= await import('./unix-policy.mjs'));
|
|
33
51
|
|
|
34
|
-
|
|
35
|
-
export const GATEWAY_FAIL = Object.freeze({
|
|
36
|
-
CONNECTION_REFUSED: 1, HOST_UNREACHABLE: 2, DNS_FAILED: 3, POLICY_DENIED: 4, TIMEOUT: 5, CLOSED: 6, QUEUE_FULL: 7,
|
|
37
|
-
});
|
|
52
|
+
export { GATEWAY_FAIL, gatewayFeatures };
|
|
38
53
|
|
|
39
|
-
const DEFAULT_MAX_CONNECTIONS = 32;
|
|
40
54
|
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
|
|
41
|
-
const
|
|
55
|
+
const MAX_PENDING_INBOUND = 16;
|
|
56
|
+
const INBOUND_ACCEPT_TIMEOUT_MS = 30_000;
|
|
57
|
+
const DEFAULT_UDP_IDLE_MS = 60_000;
|
|
58
|
+
const MAX_DATAGRAM = 65507;
|
|
59
|
+
const UDP_OUTBOX_BYTES = 256 * 1024;
|
|
42
60
|
|
|
43
61
|
/** @param {string|{host:string,port:number}} socks */
|
|
44
62
|
export function parseSocks(socks) {
|
|
@@ -52,7 +70,7 @@ export function parseSocks(socks) {
|
|
|
52
70
|
return { host: m[1].replace(/^\[|\]$/g, ''), port: Number(m[2]) };
|
|
53
71
|
}
|
|
54
72
|
|
|
55
|
-
/** Does `host:port` match one of the allow patterns? */
|
|
73
|
+
/** Does `host:port` match one of the allow patterns? (The NAME check only; see `addressPermitted` for the address.) */
|
|
56
74
|
export function destinationAllowed(allow, host, port) {
|
|
57
75
|
const h = String(host).toLowerCase();
|
|
58
76
|
for (const raw of allow) {
|
|
@@ -62,6 +80,33 @@ export function destinationAllowed(allow, host, port) {
|
|
|
62
80
|
return false;
|
|
63
81
|
}
|
|
64
82
|
|
|
83
|
+
/**
|
|
84
|
+
* The name rule: does any allow entry match, and does a matching entry name the requested host as an IP literal
|
|
85
|
+
* (`explicit`: that entry is then allowed to reach exactly that address even if it is not public)?
|
|
86
|
+
*/
|
|
87
|
+
function nameDecision(allow, host, port) {
|
|
88
|
+
const h = String(host).toLowerCase();
|
|
89
|
+
let allowed = false;
|
|
90
|
+
let explicit = false;
|
|
91
|
+
for (const raw of allow) {
|
|
92
|
+
const p = String(raw).toLowerCase();
|
|
93
|
+
if (p === '*') allowed = true;
|
|
94
|
+
else if (p === h || p === `${h}:${port}`) { allowed = true; if (parseIp(h)) explicit = true; }
|
|
95
|
+
}
|
|
96
|
+
return { allowed, explicit };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* May the host dial this resolved address? Public addresses, addresses in `allowPrivate`, and the literal address of
|
|
101
|
+
* an explicit IP rule.
|
|
102
|
+
* @param {{ allowPrivate: Array<object> }} cfg
|
|
103
|
+
*/
|
|
104
|
+
export function addressPermitted(cfg, address, { explicitLiteral = null } = {}) {
|
|
105
|
+
if (explicitLiteral && sameAddress(address, explicitLiteral)) return true;
|
|
106
|
+
if (isPublicAddress(address)) return true;
|
|
107
|
+
return cfg.allowPrivate.some((c) => addressInCidr(address, c));
|
|
108
|
+
}
|
|
109
|
+
|
|
65
110
|
/**
|
|
66
111
|
* SOCKS5 CONNECT (RFC 1928) with no authentication, destination as a domain name.
|
|
67
112
|
* Resolves with the connected socket, or rejects with an Error carrying `.code`
|
|
@@ -114,12 +159,81 @@ export async function socksConnect(proxy, host, port, { timeoutMs = DEFAULT_CONN
|
|
|
114
159
|
});
|
|
115
160
|
}
|
|
116
161
|
|
|
162
|
+
const connectError = (e) => {
|
|
163
|
+
const code = e.code === 'ECONNREFUSED' ? GATEWAY_FAIL.CONNECTION_REFUSED : e.code === 'ENOTFOUND' || e.code === 'EAI_AGAIN' ? GATEWAY_FAIL.DNS_FAILED : GATEWAY_FAIL.HOST_UNREACHABLE;
|
|
164
|
+
const err = new Error(e.code === 'ENOTFOUND' ? 'name not found' : e.message);
|
|
165
|
+
err.code = code;
|
|
166
|
+
return err;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Connect to ONE address (no name lookup happens: the caller already resolved and checked it).
|
|
171
|
+
* @returns {Promise<import('node:net').Socket>}
|
|
172
|
+
*/
|
|
173
|
+
async function connectAddress(address, port, timeoutMs) {
|
|
174
|
+
const net = await loadNet();
|
|
175
|
+
return new Promise((resolve, reject) => {
|
|
176
|
+
const s = net.connect({ host: address, port });
|
|
177
|
+
const t = setTimeout(() => { s.destroy(); const e = new Error('connect timed out'); e.code = GATEWAY_FAIL.TIMEOUT; reject(e); }, timeoutMs);
|
|
178
|
+
s.once('connect', () => { clearTimeout(t); s.removeAllListeners('error'); resolve(s); });
|
|
179
|
+
s.once('error', (e) => { clearTimeout(t); reject(connectError(e)); });
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Resolve `host` ONCE and return only the addresses `cfg` permits (an empty answer after filtering is POLICY_DENIED).
|
|
185
|
+
* Everything that then connects does so to one of these addresses, never to the name.
|
|
186
|
+
* @returns {Promise<string[]>}
|
|
187
|
+
*/
|
|
188
|
+
export async function resolveChecked(cfg, host, explicitLiteral, timeoutMs = cfg.connectTimeoutMs) {
|
|
189
|
+
const dns = await loadDns();
|
|
190
|
+
let found;
|
|
191
|
+
try {
|
|
192
|
+
found = await Promise.race([
|
|
193
|
+
dns.lookup(host, { all: true, verbatim: true }),
|
|
194
|
+
new Promise((_, rej) => { const t = setTimeout(() => { const e = new Error('name lookup timed out'); e.code = GATEWAY_FAIL.TIMEOUT; rej(e); }, timeoutMs); t.unref?.(); }),
|
|
195
|
+
]);
|
|
196
|
+
} catch (e) { throw typeof e.code === 'number' ? e : connectError(e); }
|
|
197
|
+
const addresses = found.map((a) => a.address);
|
|
198
|
+
const usable = addresses.filter((a) => addressPermitted(cfg, a, { explicitLiteral }));
|
|
199
|
+
if (usable.length === 0) {
|
|
200
|
+
const e = new Error('the address this name resolves to is not permitted by the gateway policy');
|
|
201
|
+
e.code = GATEWAY_FAIL.POLICY_DENIED;
|
|
202
|
+
e.refusedAddresses = addresses;
|
|
203
|
+
throw e;
|
|
204
|
+
}
|
|
205
|
+
return usable;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Resolve `host` once, keep only the addresses `cfg` permits, and connect to the first that answers. A refusal of
|
|
210
|
+
* every address is POLICY_DENIED; the connect uses the address that was checked, never the name.
|
|
211
|
+
* @returns {Promise<{ sock: import('node:net').Socket, address: string }>}
|
|
212
|
+
*/
|
|
213
|
+
export async function dialChecked(cfg, host, port, explicitLiteral, timeoutMs = cfg.connectTimeoutMs) {
|
|
214
|
+
const deadline = Date.now() + timeoutMs;
|
|
215
|
+
const usable = await resolveChecked(cfg, host, explicitLiteral, timeoutMs);
|
|
216
|
+
let last;
|
|
217
|
+
for (const address of usable) {
|
|
218
|
+
const left = deadline - Date.now();
|
|
219
|
+
if (left <= 0) break;
|
|
220
|
+
try { return { sock: await connectAddress(address, port, left), address }; } catch (e) { last = e; }
|
|
221
|
+
}
|
|
222
|
+
throw last ?? Object.assign(new Error('connect timed out'), { code: GATEWAY_FAIL.TIMEOUT });
|
|
223
|
+
}
|
|
224
|
+
|
|
117
225
|
/**
|
|
118
226
|
* @param {object} opts
|
|
119
227
|
* @param {string[]} [opts.allow=[]] destination patterns; empty = nothing is reachable
|
|
228
|
+
* @param {string[]} [opts.allowPrivate=[]] CIDR blocks or addresses (`"10.0.0.0/8"`, `"127.0.0.1"`, `"fd00::/8"`) the host may dial even though they are not globally routable
|
|
120
229
|
* @param {number} [opts.maxConnections=32] concurrent gateway sockets per client connection
|
|
121
230
|
* @param {number} [opts.connectTimeoutMs=15000]
|
|
231
|
+
* @param {number} [opts.maxBufferedBytes=4194304] bytes received from a client for one connection and not yet taken by its origin
|
|
232
|
+
* @param {number} [opts.maxClientBufferedBytes=33554432] the same, summed over one client's connections
|
|
122
233
|
* @param {string|{host:string,port:number}} [opts.socks] dial through this SOCKS5 proxy (Tor)
|
|
234
|
+
* @param {{ connect?: string[], listen?: string[], replaceStale?: boolean, maxListeners?: number }} [opts.unix] unix-domain sockets (see unix-policy.mjs)
|
|
235
|
+
* @param {Record<string, Function | { open: Function, authorize?: Function }>} [opts.endpoints] named virtual endpoints
|
|
236
|
+
* @param {boolean} [opts.tcp=true] false: no TCP or DNS at all (an endpoints-only host such as the memory host)
|
|
123
237
|
* @param {(line: string) => void} [opts.log]
|
|
124
238
|
*/
|
|
125
239
|
export function normalizeGateway(opts) {
|
|
@@ -127,14 +241,52 @@ export function normalizeGateway(opts) {
|
|
|
127
241
|
if (!opts || typeof opts !== 'object') return null;
|
|
128
242
|
const allow = opts.allow ?? [];
|
|
129
243
|
if (!Array.isArray(allow) || allow.some((a) => typeof a !== 'string' || !a)) throw new TypeError('gateway.allow must be an array of non-empty strings');
|
|
130
|
-
const
|
|
131
|
-
if (!
|
|
244
|
+
const privateRules = opts.allowPrivate ?? [];
|
|
245
|
+
if (!Array.isArray(privateRules)) throw new TypeError('gateway.allowPrivate must be an array of CIDR blocks or addresses');
|
|
246
|
+
const allowPrivate = privateRules.map((r) => {
|
|
247
|
+
const c = parseCidr(r);
|
|
248
|
+
if (!c) throw new TypeError(`gateway.allowPrivate: ${JSON.stringify(r)} is not an address or CIDR block`);
|
|
249
|
+
return c;
|
|
250
|
+
});
|
|
251
|
+
const { maxConnections, maxBufferedBytes, maxClientBufferedBytes } = normalizeGatewayLimits(opts);
|
|
252
|
+
let unix = null;
|
|
253
|
+
if (opts.unix !== undefined && opts.unix !== null && opts.unix !== false) {
|
|
254
|
+
if (opts.unix === true || typeof opts.unix !== 'object') throw new TypeError('gateway.unix needs explicit paths (default deny): { connect: [...], listen: [...] }');
|
|
255
|
+
// The policy module touches the file system; validate its shape here without loading `node:fs`.
|
|
256
|
+
unix = normalizeUnixShape(opts.unix);
|
|
257
|
+
}
|
|
258
|
+
const endpoints = normalizeEndpoints(opts.endpoints);
|
|
132
259
|
return {
|
|
133
260
|
allow: [...allow],
|
|
261
|
+
allowPrivate,
|
|
134
262
|
maxConnections,
|
|
263
|
+
maxBufferedBytes,
|
|
264
|
+
maxClientBufferedBytes,
|
|
135
265
|
connectTimeoutMs: opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
|
|
266
|
+
udpIdleMs: opts.udpIdleMs ?? DEFAULT_UDP_IDLE_MS,
|
|
136
267
|
socks: parseSocks(opts.socks),
|
|
268
|
+
tcp: opts.tcp !== false,
|
|
269
|
+
unix,
|
|
270
|
+
endpoints,
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The shape check of `normalizeUnixPolicy`, without importing it (it needs `node:fs`). */
|
|
275
|
+
function normalizeUnixShape(u) {
|
|
276
|
+
const list = (v, what) => {
|
|
277
|
+
if (v === undefined) return [];
|
|
278
|
+
if (!Array.isArray(v) || v.some((p) => typeof p !== 'string' || !p)) throw new TypeError(`gateway.unix.${what} must be an array of non-empty strings`);
|
|
279
|
+
for (const p of v) {
|
|
280
|
+
if (p.includes('\0') || p.length > 4096) throw new TypeError(`gateway.unix.${what}: bad pattern ${JSON.stringify(p.slice(0, 80))}`);
|
|
281
|
+
if (!p.startsWith('/') && !p.startsWith('@')) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must be an absolute path or an abstract name starting with "@"`);
|
|
282
|
+
if (p === '/' || p === '@' || p === '@/') throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} would allow everything; list a specific path or directory`);
|
|
283
|
+
if (p.split('/').includes('..')) throw new TypeError(`gateway.unix.${what}: ${JSON.stringify(p)} must not contain ".."`);
|
|
284
|
+
}
|
|
285
|
+
return [...v];
|
|
137
286
|
};
|
|
287
|
+
const maxListeners = u.maxListeners ?? 4;
|
|
288
|
+
if (!Number.isInteger(maxListeners) || maxListeners < 0) throw new TypeError('gateway.unix.maxListeners must be a non-negative integer');
|
|
289
|
+
return { connect: list(u.connect, 'connect'), listen: list(u.listen, 'listen'), replaceStale: u.replaceStale === true, maxListeners };
|
|
138
290
|
}
|
|
139
291
|
|
|
140
292
|
/**
|
|
@@ -142,65 +294,90 @@ export function normalizeGateway(opts) {
|
|
|
142
294
|
* @param {ReturnType<typeof normalizeGateway>} cfg
|
|
143
295
|
* @param {(msg: object) => unknown} send
|
|
144
296
|
* @param {(line: string) => void} log
|
|
297
|
+
* @param {{ who?: () => { username: string | null, fingerprint: string | null } }} [ctx]
|
|
145
298
|
*/
|
|
146
|
-
export function createGatewaySession(cfg, send, log = () => {}) {
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
|
|
150
|
-
|
|
299
|
+
export function createGatewaySession(cfg, send, log = () => {}, ctx = {}) {
|
|
300
|
+
// The connection table, credit negotiation, the per-client budget and the endpoint opcodes are the browser-safe core.
|
|
301
|
+
const core = createGatewayCore(cfg, send, log, ctx);
|
|
302
|
+
const { conns, pending, reply, fail, active, idInUse, makeChannel } = core;
|
|
303
|
+
/** @type {Map<number, { server: import('node:net').Server, path: string, abstract: boolean, stat: any, pendingChannels: Set<number> }>} */
|
|
304
|
+
const listeners = new Map();
|
|
305
|
+
const pendingListeners = new Set();
|
|
306
|
+
/** Accepted inbound sockets waiting for InboundAccept: channel_id -> { sock, listenerId, timer }. */
|
|
307
|
+
const inbound = new Map();
|
|
308
|
+
let nextInbound = 0;
|
|
309
|
+
let closed = false;
|
|
310
|
+
const failListen = (listenerId, reason) => reply(listenFail({ listenerId, reason }));
|
|
151
311
|
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
312
|
+
/** Attach a connected socket (TCP or unix) as gateway connection `id`. */
|
|
313
|
+
function attachSocket(id, sock) {
|
|
314
|
+
sock.setNoDelay?.(true);
|
|
315
|
+
let tail = Promise.resolve();
|
|
316
|
+
let graceTimer = null;
|
|
317
|
+
const channel = makeChannel(id, {
|
|
318
|
+
writeAfterRemoteClose: true,
|
|
319
|
+
graceMs: HALF_CLOSE_GRACE_MS,
|
|
320
|
+
onData: (bytes) => { sock.write(bytes, () => channel.consumed(bytes.byteLength)); },
|
|
321
|
+
onRemoteClose: () => { sock.end(); graceTimer = setTimeout(() => sock.destroy(), HALF_CLOSE_GRACE_MS); graceTimer.unref?.(); },
|
|
322
|
+
onClose: () => { clearTimeout(graceTimer); sock.destroy(); },
|
|
323
|
+
});
|
|
324
|
+
conns.set(id, { channel, sock });
|
|
325
|
+
// Origin -> client: one chunk at a time. The socket is paused until the channel has taken the chunk (it waits for
|
|
326
|
+
// credit and for the transport), so a client that stops reading stops the origin instead of filling memory here.
|
|
327
|
+
sock.on('data', (d) => {
|
|
328
|
+
sock.pause();
|
|
329
|
+
tail = channel.write(new Uint8Array(d.buffer, d.byteOffset, d.length)).then(() => { if (!sock.destroyed) sock.resume(); }, () => { sock.destroy(); });
|
|
330
|
+
});
|
|
331
|
+
sock.on('error', (e) => log(`gateway ${id}: ${e.message}`));
|
|
332
|
+
// The origin is gone: say so once everything it sent has gone out, and forget the connection (the client's own
|
|
333
|
+
// GatewayClose, if it sends one, then finds nothing and is ignored).
|
|
334
|
+
sock.on('close', () => { void tail.finally(() => channel.destroy()); });
|
|
335
|
+
return channel;
|
|
336
|
+
}
|
|
155
337
|
|
|
156
338
|
async function openTcp(m) {
|
|
157
339
|
const id = m.gateway_id;
|
|
158
340
|
if (!Number.isInteger(id) || typeof m.host !== 'string' || !Number.isInteger(m.port) || m.port < 1 || m.port > 65535) {
|
|
159
341
|
return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenTcp');
|
|
160
342
|
}
|
|
161
|
-
if (
|
|
162
|
-
if (!
|
|
343
|
+
if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
|
|
344
|
+
if (!cfg.tcp) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'TCP is not enabled on this gateway');
|
|
345
|
+
const decision = nameDecision(cfg.allow, m.host, m.port);
|
|
346
|
+
if (!decision.allowed) {
|
|
163
347
|
log(`gateway: refused ${m.host}:${m.port} (not on the allow list)`);
|
|
164
348
|
return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'destination not allowed by the gateway policy');
|
|
165
349
|
}
|
|
166
350
|
if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
|
|
167
351
|
pending.add(id);
|
|
168
352
|
let sock;
|
|
353
|
+
let resolvedAddr;
|
|
169
354
|
try {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const err = new Error(e.code === 'ENOTFOUND' ? 'name not found' : e.message);
|
|
181
|
-
err.code = code;
|
|
182
|
-
reject(err);
|
|
183
|
-
});
|
|
184
|
-
});
|
|
355
|
+
if (cfg.socks) {
|
|
356
|
+
const lit = parseIp(m.host);
|
|
357
|
+
if (lit && !addressPermitted(cfg, m.host, { explicitLiteral: decision.explicit ? m.host : null })) {
|
|
358
|
+
const e = new Error('the address is not permitted by the gateway policy');
|
|
359
|
+
e.code = GATEWAY_FAIL.POLICY_DENIED;
|
|
360
|
+
throw e;
|
|
361
|
+
}
|
|
362
|
+
sock = await socksConnect(cfg.socks, m.host, m.port, { timeoutMs: cfg.connectTimeoutMs });
|
|
363
|
+
} else {
|
|
364
|
+
({ sock, address: resolvedAddr } = await dialChecked(cfg, m.host, m.port, decision.explicit ? m.host : null));
|
|
185
365
|
}
|
|
186
366
|
} catch (e) {
|
|
187
367
|
pending.delete(id);
|
|
368
|
+
if (e.code === GATEWAY_FAIL.POLICY_DENIED) log(`gateway: refused ${m.host}:${m.port} (${e.message})`);
|
|
188
369
|
return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
|
|
189
370
|
}
|
|
190
371
|
pending.delete(id);
|
|
191
|
-
|
|
192
|
-
sock
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
sock.on('close', () => {
|
|
196
|
-
if (sockets.get(id) === sock) { sockets.delete(id); void reply(gatewayClose({ gatewayId: id })); }
|
|
197
|
-
});
|
|
198
|
-
log(`gateway: ${id} -> ${m.host}:${m.port}${cfg.socks ? ' (via SOCKS5)' : ''}`);
|
|
199
|
-
return reply(gatewayOk({ gatewayId: id }));
|
|
372
|
+
if (closed) { sock.destroy(); return undefined; }
|
|
373
|
+
attachSocket(id, sock);
|
|
374
|
+
log(`gateway: ${id} -> ${m.host}:${m.port}${resolvedAddr && resolvedAddr !== m.host ? ` (${resolvedAddr})` : ''}${cfg.socks ? ' (via SOCKS5)' : ''}`);
|
|
375
|
+
return reply(gatewayOk({ gatewayId: id, resolvedAddr }));
|
|
200
376
|
}
|
|
201
377
|
|
|
202
378
|
async function resolveDns(m) {
|
|
203
379
|
const id = m.gateway_id;
|
|
380
|
+
if (!cfg.tcp) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'DNS is not enabled on this gateway');
|
|
204
381
|
if (cfg.socks) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'names are resolved by the SOCKS proxy; this gateway does not look them up');
|
|
205
382
|
if (typeof m.name !== 'string' || !m.name) return fail(id, GATEWAY_FAIL.DNS_FAILED, 'malformed ResolveDns');
|
|
206
383
|
// Only names the client could also connect to: the allow list is about hosts, not ports, here.
|
|
@@ -209,40 +386,266 @@ export function createGatewaySession(cfg, send, log = () => {}) {
|
|
|
209
386
|
try {
|
|
210
387
|
const family = m.record_type === 'AAAA' ? 6 : m.record_type === 'A' || m.record_type === undefined ? 4 : 0;
|
|
211
388
|
if (!family) return fail(id, GATEWAY_FAIL.DNS_FAILED, `unsupported record type ${String(m.record_type).slice(0, 8)}`);
|
|
212
|
-
const
|
|
389
|
+
const all = (await (await loadDns()).lookup(m.name, { family, all: true, verbatim: true })).map((a) => a.address);
|
|
390
|
+
// An answer a client could not connect to is not handed out either: it would only be a way to learn the
|
|
391
|
+
// host's internal addresses, and a later OpenTcp to it has to pass the same check.
|
|
392
|
+
const lit = parseIp(m.name) ? m.name : null;
|
|
393
|
+
const addresses = all.filter((a) => addressPermitted(cfg, a, { explicitLiteral: lit }));
|
|
394
|
+
if (all.length && !addresses.length) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'the addresses this name resolves to are not permitted by the gateway policy');
|
|
213
395
|
return reply(dnsResult({ gatewayId: id, addresses }));
|
|
214
396
|
} catch (e) {
|
|
215
397
|
return fail(id, GATEWAY_FAIL.DNS_FAILED, String(e.code === 'ENOTFOUND' ? 'name not found' : e.message).slice(0, 200));
|
|
216
398
|
}
|
|
217
399
|
}
|
|
218
400
|
|
|
401
|
+
// ── UDP over the reliable path ───────────────────────────────────
|
|
402
|
+
// One GatewayData is one datagram. This rides the ordered, reliable control stream, so it has the head-of-line
|
|
403
|
+
// blocking and retransmission a UDP user does not expect (WebTransport datagrams are #124's second half); what it
|
|
404
|
+
// does keep is UDP's loss model toward the origin side: a datagram the client cannot take fast enough is DROPPED
|
|
405
|
+
// here rather than buffered, and one the client sends beyond what fits in a datagram is dropped.
|
|
406
|
+
|
|
407
|
+
async function openUdp(m) {
|
|
408
|
+
const id = m.gateway_id;
|
|
409
|
+
if (!Number.isInteger(id) || typeof m.host !== 'string' || !Number.isInteger(m.port) || m.port < 1 || m.port > 65535) {
|
|
410
|
+
return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenUdp');
|
|
411
|
+
}
|
|
412
|
+
if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
|
|
413
|
+
if (!cfg.tcp) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'UDP is not enabled on this gateway');
|
|
414
|
+
if (cfg.socks) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'UDP is not available through a SOCKS proxy');
|
|
415
|
+
const decision = nameDecision(cfg.allow, m.host, m.port);
|
|
416
|
+
if (!decision.allowed) {
|
|
417
|
+
log(`gateway: refused udp ${m.host}:${m.port} (not on the allow list)`);
|
|
418
|
+
return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'destination not allowed by the gateway policy');
|
|
419
|
+
}
|
|
420
|
+
if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
|
|
421
|
+
pending.add(id);
|
|
422
|
+
let sock;
|
|
423
|
+
let address;
|
|
424
|
+
try {
|
|
425
|
+
address = (await resolveChecked(cfg, m.host, decision.explicit ? m.host : null))[0];
|
|
426
|
+
const dgram = (await import('node:dgram')).default;
|
|
427
|
+
sock = dgram.createSocket(address.includes(':') ? 'udp6' : 'udp4');
|
|
428
|
+
await new Promise((resolve, reject) => { sock.once('error', reject); sock.connect(m.port, address, () => { sock.off('error', reject); resolve(); }); });
|
|
429
|
+
} catch (e) {
|
|
430
|
+
pending.delete(id);
|
|
431
|
+
try { sock?.close(); } catch { /* not open */ }
|
|
432
|
+
if (e.code === GATEWAY_FAIL.POLICY_DENIED) log(`gateway: refused udp ${m.host}:${m.port} (${e.message})`);
|
|
433
|
+
return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
|
|
434
|
+
}
|
|
435
|
+
pending.delete(id);
|
|
436
|
+
if (closed) { sock.close(); return undefined; }
|
|
437
|
+
attachDatagrams(id, sock);
|
|
438
|
+
log(`gateway: ${id} -> udp ${m.host}:${m.port}${address !== m.host ? ` (${address})` : ''}`);
|
|
439
|
+
return reply(gatewayOk({ gatewayId: id, resolvedAddr: address }));
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function attachDatagrams(id, sock) {
|
|
443
|
+
let idle = null;
|
|
444
|
+
const touch = () => { clearTimeout(idle); idle = setTimeout(() => channel.destroy('idle timeout'), cfg.udpIdleMs); idle.unref?.(); };
|
|
445
|
+
const outbox = [];
|
|
446
|
+
let outboxBytes = 0;
|
|
447
|
+
let pumping = false;
|
|
448
|
+
const channel = makeChannel(id, {
|
|
449
|
+
onData: (bytes) => {
|
|
450
|
+
touch();
|
|
451
|
+
if (bytes.byteLength > MAX_DATAGRAM) { channel.consumed(bytes.byteLength); return; }
|
|
452
|
+
sock.send(bytes, () => channel.consumed(bytes.byteLength));
|
|
453
|
+
},
|
|
454
|
+
onRemoteClose: () => channel.destroy(), // UDP has no half-close
|
|
455
|
+
onClose: () => { clearTimeout(idle); try { sock.close(); } catch { /* closed */ } },
|
|
456
|
+
});
|
|
457
|
+
conns.set(id, { channel, sock: null });
|
|
458
|
+
async function pump() {
|
|
459
|
+
if (pumping) return;
|
|
460
|
+
pumping = true;
|
|
461
|
+
try {
|
|
462
|
+
while (outbox.length && !channel.closed) {
|
|
463
|
+
const d = outbox.shift();
|
|
464
|
+
outboxBytes -= d.length;
|
|
465
|
+
await channel.write(new Uint8Array(d.buffer, d.byteOffset, d.length));
|
|
466
|
+
}
|
|
467
|
+
} catch { /* closed while writing */ } finally { pumping = false; }
|
|
468
|
+
}
|
|
469
|
+
sock.on('message', (d) => {
|
|
470
|
+
touch();
|
|
471
|
+
if (outboxBytes + d.length > UDP_OUTBOX_BYTES) return; // the client is not keeping up: drop, as a network would
|
|
472
|
+
outbox.push(d); outboxBytes += d.length;
|
|
473
|
+
void pump();
|
|
474
|
+
});
|
|
475
|
+
sock.on('error', (e) => log(`gateway ${id}: ${e.message}`));
|
|
476
|
+
touch();
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// ── unix sockets ─────────────────────────────────────────────────
|
|
480
|
+
|
|
481
|
+
async function openUnix(m) {
|
|
482
|
+
const id = m.gateway_id;
|
|
483
|
+
if (!Number.isInteger(id) || typeof m.path !== 'string') return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'malformed OpenUnix');
|
|
484
|
+
if (idInUse(id)) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'gateway_id already in use');
|
|
485
|
+
if (!cfg.unix || cfg.unix.connect.length === 0) return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'unix sockets are not enabled on this gateway');
|
|
486
|
+
if (active() >= cfg.maxConnections) return fail(id, GATEWAY_FAIL.QUEUE_FULL, 'too many gateway connections');
|
|
487
|
+
pending.add(id);
|
|
488
|
+
let sock;
|
|
489
|
+
try {
|
|
490
|
+
const unix = await loadUnix();
|
|
491
|
+
const chk = await unix.checkUnixPath(m.path, cfg.unix.connect);
|
|
492
|
+
if (!chk.ok) {
|
|
493
|
+
log(`gateway: refused unix ${JSON.stringify(m.path.slice(0, 200))} (${chk.reason})`);
|
|
494
|
+
pending.delete(id);
|
|
495
|
+
return fail(id, GATEWAY_FAIL.POLICY_DENIED, chk.reason);
|
|
496
|
+
}
|
|
497
|
+
if (!chk.abstract) {
|
|
498
|
+
const st = await unix.statSocket(chk.path);
|
|
499
|
+
if (!st) { pending.delete(id); return fail(id, GATEWAY_FAIL.CONNECTION_REFUSED, 'no such socket'); }
|
|
500
|
+
if (!st.socket) { pending.delete(id); log(`gateway: refused unix ${chk.path} (not a socket)`); return fail(id, GATEWAY_FAIL.POLICY_DENIED, 'not a socket'); }
|
|
501
|
+
}
|
|
502
|
+
sock = await new Promise((resolve, reject) => {
|
|
503
|
+
loadNet().then((net) => {
|
|
504
|
+
const s = net.connect({ path: chk.path });
|
|
505
|
+
const t = setTimeout(() => { s.destroy(); const e = new Error('connect timed out'); e.code = GATEWAY_FAIL.TIMEOUT; reject(e); }, cfg.connectTimeoutMs);
|
|
506
|
+
s.once('connect', () => { clearTimeout(t); s.removeAllListeners('error'); resolve(s); });
|
|
507
|
+
s.once('error', (e) => { clearTimeout(t); reject(connectError(e)); });
|
|
508
|
+
}, reject);
|
|
509
|
+
});
|
|
510
|
+
} catch (e) {
|
|
511
|
+
pending.delete(id);
|
|
512
|
+
return fail(id, typeof e.code === 'number' ? e.code : GATEWAY_FAIL.HOST_UNREACHABLE, String(e.message).slice(0, 200));
|
|
513
|
+
}
|
|
514
|
+
pending.delete(id);
|
|
515
|
+
if (closed) { sock.destroy(); return undefined; }
|
|
516
|
+
attachSocket(id, sock);
|
|
517
|
+
log(`gateway: ${id} -> unix ${m.path.slice(0, 200)}`);
|
|
518
|
+
return reply(gatewayOk({ gatewayId: id }));
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
async function listenUnix(m) {
|
|
522
|
+
const id = m.listener_id;
|
|
523
|
+
if (!Number.isInteger(id) || typeof m.path !== 'string') return failListen(id, 'malformed ListenUnix');
|
|
524
|
+
if (listeners.has(id) || pendingListeners.has(id)) return failListen(id, 'listener_id already in use');
|
|
525
|
+
if (!cfg.unix || cfg.unix.listen.length === 0) return failListen(id, 'unix listeners are not enabled on this gateway');
|
|
526
|
+
if (listeners.size + pendingListeners.size >= cfg.unix.maxListeners) return failListen(id, 'too many unix listeners');
|
|
527
|
+
pendingListeners.add(id);
|
|
528
|
+
let server;
|
|
529
|
+
try {
|
|
530
|
+
const unix = await loadUnix();
|
|
531
|
+
const net = await loadNet();
|
|
532
|
+
const chk = await unix.checkUnixPath(m.path, cfg.unix.listen);
|
|
533
|
+
if (!chk.ok) { log(`gateway: refused unix listen ${JSON.stringify(m.path.slice(0, 200))} (${chk.reason})`); return await failListen(id, chk.reason); }
|
|
534
|
+
if (!chk.abstract) {
|
|
535
|
+
const st = await unix.statSocket(chk.path);
|
|
536
|
+
if (st) {
|
|
537
|
+
if (!st.socket) return await failListen(id, 'a file that is not a socket is in the way');
|
|
538
|
+
if (m.replace !== true) return await failListen(id, 'address in use (a socket file exists; ask to replace it)');
|
|
539
|
+
if (!cfg.unix.replaceStale) return await failListen(id, 'replacing an existing socket is not allowed by the gateway policy');
|
|
540
|
+
// Only a stale socket: one nothing accepts connections on.
|
|
541
|
+
const live = await new Promise((resolve) => {
|
|
542
|
+
const probe = net.connect({ path: chk.path });
|
|
543
|
+
probe.once('connect', () => { probe.destroy(); resolve(true); });
|
|
544
|
+
probe.once('error', (e) => resolve(e.code !== 'ECONNREFUSED' && e.code !== 'ENOENT'));
|
|
545
|
+
});
|
|
546
|
+
if (live) return await failListen(id, 'address in use (the existing socket is live)');
|
|
547
|
+
await unix.unlinkIfSocket(chk.path, st);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (closed) return undefined;
|
|
551
|
+
server = net.createServer();
|
|
552
|
+
// Created private from the first instant: the mode of a socket is its umask at bind time.
|
|
553
|
+
const oldMask = (() => { try { return process.umask(0o177); } catch { return null; } })();
|
|
554
|
+
try {
|
|
555
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen({ path: chk.path }, () => { server.off('error', reject); resolve(); }); });
|
|
556
|
+
} finally { if (oldMask !== null) { try { process.umask(oldMask); } catch { /* gone */ } } }
|
|
557
|
+
let stat = null;
|
|
558
|
+
if (!chk.abstract) {
|
|
559
|
+
const fsp = (await import('node:fs/promises')).default;
|
|
560
|
+
await fsp.chmod(chk.path, 0o600);
|
|
561
|
+
stat = await unix.statSocket(chk.path);
|
|
562
|
+
}
|
|
563
|
+
if (closed) { server.close(); if (stat) await unix.unlinkIfSocket(chk.path, stat); return undefined; }
|
|
564
|
+
const entry = { server, path: chk.path, abstract: chk.abstract, stat, pendingChannels: new Set() };
|
|
565
|
+
listeners.set(id, entry);
|
|
566
|
+
server.on('connection', (sock) => onInbound(id, entry, sock));
|
|
567
|
+
server.on('error', (e) => log(`gateway listener ${id}: ${e.message}`));
|
|
568
|
+
log(`gateway: listening on unix ${m.path.slice(0, 200)} (listener ${id})`);
|
|
569
|
+
return await reply(listenOk({ listenerId: id, actualPort: 0 }));
|
|
570
|
+
} catch (e) {
|
|
571
|
+
try { server?.close(); } catch { /* not listening */ }
|
|
572
|
+
return failListen(id, e.code === 'EADDRINUSE' ? 'address in use' : String(e.message).slice(0, 200));
|
|
573
|
+
} finally {
|
|
574
|
+
pendingListeners.delete(id);
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function onInbound(listenerId, entry, sock) {
|
|
579
|
+
if (closed || inbound.size >= MAX_PENDING_INBOUND || active() + inbound.size >= cfg.maxConnections) { sock.destroy(); return; }
|
|
580
|
+
sock.pause();
|
|
581
|
+
sock.on('error', () => {});
|
|
582
|
+
const channelId = ++nextInbound;
|
|
583
|
+
const timer = setTimeout(() => { inbound.delete(channelId); entry.pendingChannels.delete(channelId); sock.destroy(); }, INBOUND_ACCEPT_TIMEOUT_MS);
|
|
584
|
+
timer.unref?.();
|
|
585
|
+
sock.once('close', () => { if (inbound.get(channelId)?.sock === sock) { clearTimeout(timer); inbound.delete(channelId); entry.pendingChannels.delete(channelId); } });
|
|
586
|
+
inbound.set(channelId, { sock, listenerId, timer });
|
|
587
|
+
entry.pendingChannels.add(channelId);
|
|
588
|
+
void reply(inboundOpen({ listenerId, channelId, peerAddr: 'unix', peerPort: 0 }));
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
function inboundAccept(m) {
|
|
592
|
+
const p = inbound.get(m.channel_id);
|
|
593
|
+
if (!p) return;
|
|
594
|
+
clearTimeout(p.timer);
|
|
595
|
+
inbound.delete(m.channel_id);
|
|
596
|
+
listeners.get(p.listenerId)?.pendingChannels.delete(m.channel_id);
|
|
597
|
+
const id = m.gateway_id;
|
|
598
|
+
if (!Number.isInteger(id) || idInUse(id) || p.sock.destroyed || active() >= cfg.maxConnections) { p.sock.destroy(); return; }
|
|
599
|
+
attachSocket(id, p.sock);
|
|
600
|
+
p.sock.resume();
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
function inboundReject(m) {
|
|
604
|
+
const p = inbound.get(m.channel_id);
|
|
605
|
+
if (!p) return;
|
|
606
|
+
clearTimeout(p.timer);
|
|
607
|
+
inbound.delete(m.channel_id);
|
|
608
|
+
p.sock.destroy();
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async function closeListener(id) {
|
|
612
|
+
const l = listeners.get(id);
|
|
613
|
+
if (!l) return;
|
|
614
|
+
listeners.delete(id);
|
|
615
|
+
for (const ch of l.pendingChannels) { const p = inbound.get(ch); if (p) { clearTimeout(p.timer); inbound.delete(ch); p.sock.destroy(); } }
|
|
616
|
+
await new Promise((r) => { l.server.close(() => r()); });
|
|
617
|
+
if (l.stat) await (await loadUnix()).unlinkIfSocket(l.path, l.stat);
|
|
618
|
+
}
|
|
619
|
+
|
|
219
620
|
return {
|
|
621
|
+
setPeerFeatures: (features) => core.setPeerFeatures(features),
|
|
220
622
|
/** @returns {Promise<boolean>} true when the message was a gateway message this session consumed */
|
|
221
623
|
async handle(m) {
|
|
624
|
+
if (closed) return true;
|
|
222
625
|
switch (m.type) {
|
|
223
626
|
case MSG.OPEN_TCP: await openTcp(m); return true;
|
|
224
|
-
case MSG.OPEN_UDP:
|
|
627
|
+
case MSG.OPEN_UDP: await openUdp(m); return true;
|
|
628
|
+
case MSG.OPEN_UNIX: await openUnix(m); return true;
|
|
225
629
|
case MSG.RESOLVE_DNS: await resolveDns(m); return true;
|
|
226
|
-
case MSG.GATEWAY_DATA: {
|
|
227
|
-
const s = sockets.get(m.gateway_id);
|
|
228
|
-
const d = m.data;
|
|
229
|
-
if (s && d && d.length <= MAX_DATA_BYTES) s.write(Buffer.from(d.buffer, d.byteOffset, d.length));
|
|
230
|
-
return true;
|
|
231
|
-
}
|
|
232
|
-
case MSG.GATEWAY_CLOSE: {
|
|
233
|
-
const s = sockets.get(m.gateway_id);
|
|
234
|
-
if (s) { s.end(); setTimeout(() => s.destroy(), 1000).unref(); } // its 'close' event deletes it and acknowledges
|
|
235
|
-
return true;
|
|
236
|
-
}
|
|
237
630
|
case MSG.LISTEN_REQUEST: reply(listenFail({ listenerId: m.listener_id, reason: 'reverse tunnels are not supported by this gateway' })); return true;
|
|
238
|
-
case MSG.
|
|
239
|
-
|
|
631
|
+
case MSG.LISTEN_UNIX: await listenUnix(m); return true;
|
|
632
|
+
case MSG.LISTEN_CLOSE: await closeListener(m.listener_id); return true;
|
|
633
|
+
case MSG.INBOUND_ACCEPT: inboundAccept(m); return true;
|
|
634
|
+
case MSG.INBOUND_REJECT: inboundReject(m); return true;
|
|
635
|
+
// OpenEndpoint, GatewayData, GatewayCredit, GatewayClose: the core.
|
|
636
|
+
default: return core.handle(m);
|
|
240
637
|
}
|
|
241
638
|
},
|
|
242
639
|
close() {
|
|
243
|
-
|
|
244
|
-
|
|
640
|
+
closed = true;
|
|
641
|
+
core.close();
|
|
642
|
+
for (const { sock, timer } of inbound.values()) { clearTimeout(timer); sock.destroy(); }
|
|
643
|
+
inbound.clear();
|
|
644
|
+
for (const id of [...listeners.keys()]) void closeListener(id).catch(() => {});
|
|
245
645
|
},
|
|
246
|
-
get size() { return
|
|
646
|
+
get size() { return conns.size; },
|
|
647
|
+
/** Bytes received from the client for its origins and not yet taken by them (what the caps bound). */
|
|
648
|
+
get bufferedBytes() { return core.bufferedBytes; },
|
|
649
|
+
get listenerCount() { return listeners.size; },
|
|
247
650
|
};
|
|
248
651
|
}
|