AtlatestRepositorysigil-nat

sigil-nat / tree / tools / natdiscovery.mjs

1// Read-only queries to one configured gateway. No MAP or AddPortMapping calls.
2import { createSocket } from 'node:dgram';
3import { execFileSync } from 'node:child_process';
4import { isIP } from 'node:net';
5import { pcpAnnounce, decodePcp, natPmpAddress, decodeNatPmp } from './codecs.mjs';
6
7export function gatewayRoute() {
8 const routes = JSON.parse(execFileSync('ip', ['-j', '-4', 'route', 'show', 'default'], { encoding: 'utf8' }));
9 const routesWithGateway = routes.filter(route => isIP(route.gateway) === 4);
10 if (routesWithGateway.length !== 1) throw new Error('Choose one unambiguous IPv4 default gateway');
11 const route = routesWithGateway[0];
12 const addresses = JSON.parse(execFileSync('ip', ['-j', '-4', 'address', 'show', 'dev', route.dev], { encoding: 'utf8' }))
13 .flatMap(device => device.addr_info).filter(address => address.family === 'inet' && address.scope === 'global');
14 const localAddress = route.prefsrc ?? (addresses.length === 1 ? addresses[0].local : undefined);
15 if (isIP(localAddress) !== 4 || !addresses.some(address => address.local === localAddress))
16 throw new Error('Default gateway has no unambiguous owned IPv4 source');
17 return { gateway: route.gateway, localAddress, interface: route.dev };
20export function udpQuery({ gateway, localAddress, request, decode, delays }) {
21 if (isIP(gateway) !== 4 || isIP(localAddress) !== 4 || !Buffer.isBuffer(request) || request.length > 1100)
22 throw new Error('Invalid bounded gateway query');
23 if (!Array.isArray(delays) || delays.length < 1 || delays.length > 4 ||
24 delays.some(delay => !Number.isInteger(delay) || delay < 100 || delay > 6000))
25 throw new Error('Invalid gateway retry budget');
26 return new Promise((done, reject) => {
27 const socket = createSocket('udp4');
28 let timer, attempt = 0, finished = false, received = 0;
29 const finish = (error, value) => {
30 if (finished) return;
31 finished = true; clearTimeout(timer);
32 try { socket.close(); } catch (closeError) { if (closeError.code !== 'ERR_SOCKET_DGRAM_NOT_RUNNING') throw closeError; }
33 if (error) reject(error); else done(value);
34 };
35 socket.on('error', error => finish(error));
36 socket.on('message', (bytes, peer) => {
37 if (++received > 32) return finish(new Error('Gateway response work budget exceeded'));
38 if (peer.address !== gateway || peer.port !== 5351 || bytes.length > 1100) return;
39 try { finish(null, decode(bytes)); } catch { /* Discard unrelated/truncated replies until bounded timeout. */ }
40 });
41 socket.bind(0, localAddress, () => {
42 const send = () => {
43 if (finished) return;
44 socket.send(request, 5351, gateway, error => { if (error) finish(error); });
45 timer = setTimeout(() => {
46 if (++attempt < delays.length) send();
47 else finish(new Error('Gateway query timed out'));
48 }, delays[attempt]);
49 };
50 send();
51 });
52 });
55export function parseSsdp(bytes, gateway) {
56 if (!Buffer.isBuffer(bytes) || bytes.length > 8192) throw new Error('SSDP response exceeds limit');
57 const lines = bytes.toString('utf8').split('\r\n');
58 if (!/^HTTP\/1\.[01] 200(?: |$)/.test(lines.shift())) throw new Error('Not an SSDP success response');
59 const headers = {};
60 for (const line of lines) {
61 if (!line) break;
62 const match = /^([A-Za-z0-9-]+):[ \t]*(.*)$/.exec(line);
63 if (!match || match[2].length > 2048) throw new Error('Invalid SSDP header');
64 const name = match[1].toLowerCase();
65 if (name in headers) throw new Error('Duplicate SSDP header');
66 headers[name] = match[2].trim();
67 if (Object.keys(headers).length > 32) throw new Error('SSDP header count limit');
68 }
69 if (!/^urn:schemas-upnp-org:(?:device:InternetGatewayDevice:[12]|service:WANIPConnection:[12]|service:WANPPPConnection:1)$/.test(headers.st ?? ''))
70 throw new Error('Not an IGD advertisement');
71 const location = new URL(headers.location);
72 if (!['http:', 'https:'].includes(location.protocol) || location.hostname !== gateway ||
73 location.username || location.password || location.hash) throw new Error('IGD description must remain on the exact gateway');
74 return { protocol: 'upnp-igd', location: location.href, searchTarget: headers.st, server: headers.server ?? '' };
76export function ssdpDiscover({ gateway, localAddress }) {
77 return new Promise((done, reject) => {
78 const socket = createSocket('udp4');
79 const results = new Map();
80 let timer, received = 0, finished = false;
81 const finish = error => {
82 if (finished) return;
83 finished = true; clearTimeout(timer);
84 try { socket.close(); } catch (closeError) { if (closeError.code !== 'ERR_SOCKET_DGRAM_NOT_RUNNING') throw closeError; }
85 if (error) reject(error); else done([...results.values()]);
86 };
87 socket.on('error', finish);
88 socket.on('message', (bytes, peer) => {
89 if (++received > 32) return finish(new Error('SSDP response work limit'));
90 if (peer.address !== gateway) return;
91 try { const result = parseSsdp(bytes, gateway); results.set(result.location, result); } catch { /* Not our gateway IGD. */ }
92 });
93 socket.bind(0, localAddress, () => {
94 try {
95 socket.setMulticastInterface(localAddress); socket.setMulticastTTL(1);
96 timer = setTimeout(() => finish(), 2500);
97 const targets = ['device:InternetGatewayDevice:1', 'device:InternetGatewayDevice:2',
98 'service:WANIPConnection:1', 'service:WANIPConnection:2', 'service:WANPPPConnection:1'];
99 for (const destination of ['239.255.255.250', gateway]) {
100 for (const target of targets) {
101 const mx = destination === gateway ? '' : 'MX: 1\r\n';
102 const bytes = Buffer.from(`M-SEARCH * HTTP/1.1\r\nHOST: ${destination}:1900\r\nMAN: "ssdp:discover"\r\n${mx}ST: urn:schemas-upnp-org:${target}\r\nUSER-AGENT: Linux UPnP/1.1 SigilSpike/1\r\n\r\n`);
103 socket.send(bytes, 1900, destination, error => { if (error) finish(error); });
104 }
105 }
106 } catch (error) { finish(error); }
107 });
108 });
111export async function discoverGateway(route) {
112 const result = { mode: 'read-only-gateway-discovery', route, startedAt: new Date().toISOString(), createsMapping: false };
113 try { result.pcp = await udpQuery({ ...route, request: pcpAnnounce(route.localAddress),
114 decode: bytes => decodePcp(bytes, 0), delays: [3000, 6000] }); }
115 catch (error) { result.pcp = { error: error.message }; }
116 try { result.natPmp = await udpQuery({ ...route, request: natPmpAddress(),
117 decode: bytes => decodeNatPmp(bytes, 0), delays: [250, 500, 1000] }); }
118 catch (error) { result.natPmp = { error: error.message }; }
119 try { result.upnp = await ssdpDiscover(route); }
120 catch (error) { result.upnp = { error: error.message }; }
121 result.endedAt = new Date().toISOString();
122 return result;