diff --git a/package.json b/package.json index 21d4c11..453845a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@motrix/nat", - "version": "0.1.1", + "version": "0.1.2", "description": "Dependency-free UPnP IGD, NAT-PMP, PCP, and STUN for Node.js", "license": "MIT", "author": "Motrix", diff --git a/src/clients/discovery-socket-lifecycle.test.ts b/src/clients/discovery-socket-lifecycle.test.ts new file mode 100644 index 0000000..0808ab1 --- /dev/null +++ b/src/clients/discovery-socket-lifecycle.test.ts @@ -0,0 +1,129 @@ +import { getEventListeners } from 'node:events' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createMockHttpClient } from '../net/mock-http-client.js' +import { MockUdpSocket } from '../net/mock-udp-socket.js' +import { StunClient } from './stun-client.js' +import { UpnpClient } from './upnp-client.js' + +function deferred() { + let resolve!: () => void + const promise = new Promise((yes) => { + resolve = yes + }) + return { promise, resolve } +} + +function makeHarness(protocol: 'stun' | 'upnp') { + const socket = new MockUdpSocket() + const factory = vi.fn(() => socket) + const close = vi.spyOn(socket, 'close') + const send = vi.spyOn(socket, 'send') + const offMessage = vi.spyOn(socket, 'offMessage') + const stun = new StunClient({ udpFactory: factory }) + const upnp = new UpnpClient({ + udpFactory: factory, + http: createMockHttpClient().client, + }) + return { + socket, + factory, + close, + send, + offMessage, + run: (signal?: AbortSignal) => + protocol === 'stun' + ? stun.detectNatType({ + servers: ['192.168.1.1:3478'], + timeoutMs: 10, + ...(signal ? { signal } : {}), + }) + : upnp.discover({ timeoutMs: 10 }), + } +} + +describe('discovery socket cleanup', () => { + beforeEach(() => vi.useFakeTimers()) + afterEach(() => vi.useRealTimers()) + + for (const protocol of ['stun', 'upnp'] as const) { + it(`${protocol} does not send after a timed-out bind completes`, async () => { + const harness = makeHarness(protocol) + const binding = deferred() + vi.spyOn(harness.socket, 'bind').mockReturnValueOnce(binding.promise) + const result = harness.run() + await vi.advanceTimersByTimeAsync(10) + expect((await result).ok).toBe(false) + binding.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(harness.send).not.toHaveBeenCalled() + expect(harness.close).toHaveBeenCalledOnce() + expect(harness.offMessage).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + }) + + it(`${protocol} settles even when close throws synchronously`, async () => { + const harness = makeHarness(protocol) + harness.close.mockImplementationOnce(() => { + throw new Error('close failed') + }) + const result = harness.run() + await vi.advanceTimersByTimeAsync(10) + expect((await result).ok).toBe(false) + expect(harness.offMessage).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + }) + } + + it('STUN removes abort listeners after timeout', async () => { + const harness = makeHarness('stun') + const controller = new AbortController() + const result = harness.run(controller.signal) + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1) + await vi.advanceTimersByTimeAsync(10) + await result + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) + controller.abort() + expect(harness.close).toHaveBeenCalledOnce() + }) + + it('STUN abort during bind closes once and does not query fallback servers', async () => { + const harness = makeHarness('stun') + const binding = deferred() + vi.spyOn(harness.socket, 'bind').mockReturnValueOnce(binding.promise) + const controller = new AbortController() + const client = new StunClient({ udpFactory: harness.factory }) + const result = client.detectNatType({ + servers: ['192.168.1.1:3478', '192.168.1.2:3478'], + timeoutMs: 10, + signal: controller.signal, + }) + controller.abort() + expect((await result).ok).toBe(false) + binding.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(harness.factory).toHaveBeenCalledOnce() + expect(harness.send).not.toHaveBeenCalled() + expect(harness.close).toHaveBeenCalledOnce() + expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0) + expect(vi.getTimerCount()).toBe(0) + }) + + it('STUN skips socket creation for an already aborted request', async () => { + const harness = makeHarness('stun') + expect((await harness.run(AbortSignal.abort())).ok).toBe(false) + expect(harness.factory).not.toHaveBeenCalled() + }) + + it('UPnP does not send another search after timeout during the first send', async () => { + const harness = makeHarness('upnp') + const sending = deferred() + harness.send.mockReturnValueOnce(sending.promise) + const result = harness.run() + await vi.advanceTimersByTimeAsync(10) + expect((await result).ok).toBe(false) + sending.resolve() + await vi.advanceTimersByTimeAsync(0) + expect(harness.send).toHaveBeenCalledOnce() + expect(harness.close).toHaveBeenCalledOnce() + }) +}) diff --git a/src/clients/pmp-pcp-client-lifecycle.test.ts b/src/clients/pmp-pcp-client-lifecycle.test.ts new file mode 100644 index 0000000..2d5ed47 --- /dev/null +++ b/src/clients/pmp-pcp-client-lifecycle.test.ts @@ -0,0 +1,208 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { tick } from '../__test__/utils.js' +import { NatErrorCode } from '../errors.js' +import { MockUdpSocket } from '../net/mock-udp-socket.js' +import { PmpPcpClient } from './pmp-pcp-client.js' + +function deferred() { + let resolve!: () => void + let reject!: (error: Error) => void + const promise = new Promise((yes, no) => { + resolve = yes + reject = no + }) + return { promise, resolve, reject } +} + +function reply(socket: MockUdpSocket) { + const response = Buffer.alloc(12) + response[1] = 0x80 + response.set([203, 0, 113, 42], 8) + socket.emitMessage(response, { address: '192.168.1.1', port: 5351, size: 12 }) +} + +describe('PmpPcpClient socket lifecycle', () => { + let first: MockUdpSocket + let second: MockUdpSocket + let client: PmpPcpClient + + beforeEach(() => { + first = new MockUdpSocket() + second = new MockUdpSocket() + client = new PmpPcpClient({ + udpFactory: vi.fn().mockReturnValueOnce(first).mockReturnValue(second), + gatewayIp: '192.168.1.1', + clientIp: Buffer.alloc(16), + }) + }) + + afterEach(async () => { + await client.close() + }) + + it('does not let an old close detach a newly opened socket', async () => { + const pending = client.natPmpGetExternalIp() + await tick() + const closing = deferred() + const close = vi.spyOn(first, 'close').mockReturnValue(closing.promise) + const firstClose = client.close() + const secondClose = client.close() + const next = client.natPmpGetExternalIp() + await tick() + closing.resolve() + await Promise.all([firstClose, secondClose]) + expect(close).toHaveBeenCalledOnce() + expect((await pending).ok).toBe(false) + expect(second.sendCalls).toHaveLength(1) + reply(second) + expect((await next).ok).toBe(true) + const third = client.natPmpGetExternalIp() + await tick() + reply(second) + expect((await third).ok).toBe(true) + }) + + it('discards a bind that completes after close and reopen', async () => { + const binding = deferred() + vi.spyOn(first, 'bind').mockReturnValue(binding.promise) + const old = client.natPmpGetExternalIp() + await client.close() + const next = client.natPmpGetExternalIp() + await tick() + binding.resolve() + expect(await old).toMatchObject({ + ok: false, + error: NatErrorCode.NetworkChanged, + }) + expect(first.sendCalls).toHaveLength(0) + reply(second) + expect((await next).ok).toBe(true) + }) + + it('retries with a fresh socket after bind fails', async () => { + vi.spyOn(first, 'bind').mockRejectedValueOnce(new Error('bind failed')) + expect(await client.natPmpGetExternalIp()).toMatchObject({ + ok: false, + error: NatErrorCode.GatewayUnreachable, + }) + expect(first.closed).toBe(true) + const next = client.natPmpGetExternalIp() + await tick() + reply(second) + expect((await next).ok).toBe(true) + }) + + it('does not let a late send failure cancel the next request', async () => { + const sending = deferred() + vi.spyOn(first, 'send').mockReturnValueOnce(sending.promise) + const old = client.natPmpGetExternalIp() + await tick() + await client.close() + expect((await old).ok).toBe(false) + const next = client.natPmpGetExternalIp() + await tick() + sending.reject(new Error('late network error')) + await tick() + reply(second) + expect((await next).ok).toBe(true) + }) + + it('recovers from a synchronously throwing bind', async () => { + vi.spyOn(first, 'bind').mockImplementationOnce(() => { + throw new Error('bind failed') + }) + expect(await client.natPmpGetExternalIp()).toMatchObject({ + ok: false, + error: NatErrorCode.GatewayUnreachable, + }) + const next = client.natPmpGetExternalIp() + await tick() + reply(second) + expect((await next).ok).toBe(true) + }) + + it('settles a cancelled bind that never completes', async () => { + vi.spyOn(first, 'bind').mockReturnValue(new Promise(() => {})) + const old = client.natPmpGetExternalIp() + await tick() + await client.close() + expect(await old).toMatchObject({ + ok: false, + error: NatErrorCode.NetworkChanged, + }) + }) + + it('ignores messages retained by an old socket during close', async () => { + const old = client.natPmpGetExternalIp() + await tick() + vi.spyOn(first, 'close').mockResolvedValue() + await client.close() + await old + const next = client.natPmpGetExternalIp() + await tick() + let settled = false + void next.then(() => { + settled = true + }) + reply(first) + await tick() + expect(settled).toBe(false) + reply(second) + expect((await next).ok).toBe(true) + }) + + it('does not let an old PCP send failure delete a reused nonce', async () => { + const sending = deferred() + vi.spyOn(first, 'send').mockReturnValueOnce(sending.promise) + const params = { + internalPort: 6881, + externalPort: 6881, + protocol: 'TCP' as const, + ttl: 3600, + nonce: Buffer.alloc(12, 1), + } + const old = client.pcpMap(params) + await tick() + await client.close() + await old + const next = client.pcpMap(params) + await tick() + sending.reject(new Error('late send error')) + await tick() + const response = Buffer.alloc(60) + response[0] = 2 + response[1] = 0x81 + response.writeUInt32BE(3600, 4) + params.nonce.copy(response, 24) + response[36] = 6 + response.writeUInt16BE(6881, 40) + response.writeUInt16BE(6881, 42) + second.emitMessage(response, { + address: '192.168.1.1', + port: 5351, + size: 60, + }) + expect((await next).ok).toBe(true) + }) + + it('rejects duplicate in-flight PCP nonces without orphaning the first request', async () => { + const params = { + internalPort: 6881, + externalPort: 6881, + protocol: 'TCP' as const, + ttl: 3600, + nonce: Buffer.alloc(12, 1), + } + const pending = client.pcpMap(params) + await tick() + expect(await client.pcpMap(params)).toMatchObject({ + ok: false, + error: NatErrorCode.ProtocolRejected, + }) + await client.close() + expect(await pending).toMatchObject({ + ok: false, + error: NatErrorCode.NetworkChanged, + }) + }) +}) diff --git a/src/clients/pmp-pcp-client.ts b/src/clients/pmp-pcp-client.ts index 5a8f53e..04075fc 100644 --- a/src/clients/pmp-pcp-client.ts +++ b/src/clients/pmp-pcp-client.ts @@ -68,7 +68,10 @@ export interface PcpMapOptions { export class PmpPcpClient { private socket: UdpSocket | null = null - private socketReady: Promise | null = null + private socketReady: Promise | null = null + private cancelSocketReady: (() => void) | null = null + private socketGeneration = 0 + private closing: Promise | null = null private readonly udpFactory: UdpSocketFactory private gatewayIp: string private clientIp: Buffer @@ -184,7 +187,21 @@ export class PmpPcpClient { } async pcpMap(params: PcpMapOptions): Promise> { - await this.ensureSocket() + const generation = this.socketGeneration + let socket: UdpSocket + try { + socket = await this.ensureSocket() + } catch (error) { + return parseErr( + generation === this.socketGeneration + ? NatErrorCode.GatewayUnreachable + : NatErrorCode.NetworkChanged, + (error as Error).message + ) + } + if (socket !== this.socket) { + return parseErr(NatErrorCode.NetworkChanged, 'client closing') + } if (this.pendingNonces.size >= MAX_CONCURRENT_REQUESTS) { return parseErr( NatErrorCode.ProtocolRejected, @@ -208,6 +225,12 @@ export class PmpPcpClient { return parseErr(NatErrorCode.ProtocolRejected, (err as Error).message) } const key = nonce.toString('hex') + if (this.pendingNonces.has(key)) { + return parseErr( + NatErrorCode.ProtocolRejected, + 'pcp nonce already in flight' + ) + } const timeoutMs = Math.max( 1, params.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS @@ -217,7 +240,8 @@ export class PmpPcpClient { let onAbort: (() => void) | null = null const timer = setTimeout(() => { - if (this.pendingNonces.delete(key)) { + if (this.pendingNonces.get(key) === entry) { + this.pendingNonces.delete(key) if (onAbort && params.signal) { params.signal.removeEventListener('abort', onAbort) } @@ -241,7 +265,8 @@ export class PmpPcpClient { if (params.signal) { onAbort = () => { - if (this.pendingNonces.delete(key)) { + if (this.pendingNonces.get(key) === entry) { + this.pendingNonces.delete(key) clearTimeout(timer) resolve(parseErr(NatErrorCode.Timeout, 'aborted')) } @@ -253,9 +278,9 @@ export class PmpPcpClient { params.signal.addEventListener('abort', onAbort, { once: true }) } - // biome-ignore lint/style/noNonNullAssertion: socket guaranteed by ensureSocket() - this.socket!.send(request, NATPMP_PORT, this.gatewayIp).catch((err) => { - if (this.pendingNonces.delete(key)) { + socket.send(request, NATPMP_PORT, this.gatewayIp).catch((err) => { + if (this.pendingNonces.get(key) === entry) { + this.pendingNonces.delete(key) clearTimeout(timer) if (onAbort && params.signal) { params.signal.removeEventListener('abort', onAbort) @@ -268,7 +293,15 @@ export class PmpPcpClient { }) } - async close(): Promise { + close(): Promise { + // Detach the old generation before awaiting I/O. New discovery may open + // another socket while this one is still closing. + const socket = this.socket + this.socket = null + this.socketReady = null + this.socketGeneration++ + this.cancelSocketReady?.() + this.cancelSocketReady = null // Reject all pending for (const [, pending] of this.pendingNonces) { pending.resolve(parseErr(NatErrorCode.NetworkChanged, 'client closing')) @@ -285,11 +318,17 @@ export class PmpPcpClient { clearInterval(this.nonceCleanupTimer) this.nonceCleanupTimer = null } - if (this.socket) { - await this.socket.close() - this.socket = null - this.socketReady = null - } + if (!socket) return this.closing ?? Promise.resolve() + const closing = Promise.all([ + this.closing, + Promise.resolve().then(() => socket.close()), + ]) + .then(() => {}) + .finally(() => { + if (this.closing === closing) this.closing = null + }) + this.closing = closing + return closing } private async sendNatPmp( @@ -297,7 +336,21 @@ export class PmpPcpClient { expectedOpcode: number, options: { timeoutMs?: number; signal?: AbortSignal } ): Promise> { - await this.ensureSocket() + const generation = this.socketGeneration + let socket: UdpSocket + try { + socket = await this.ensureSocket() + } catch (error) { + return parseErr( + generation === this.socketGeneration + ? NatErrorCode.GatewayUnreachable + : NatErrorCode.NetworkChanged, + (error as Error).message + ) + } + if (socket !== this.socket) { + return parseErr(NatErrorCode.NetworkChanged, 'client closing') + } if (this.pendingPmp) { return parseErr(NatErrorCode.ProtocolRejected, 'natpmp request in flight') } @@ -322,22 +375,23 @@ export class PmpPcpClient { } const timer = setTimeout(() => { - if (this.pendingPmp) { + if (this.pendingPmp === entry) { this.pendingPmp = null wrappedResolve(parseErr(NatErrorCode.Timeout, 'natpmp timeout')) } }, timeoutMs) timer.unref?.() - this.pendingPmp = { + const entry: PendingPmp = { opcode: expectedOpcode, resolve: wrappedResolve, timer, } + this.pendingPmp = entry if (options.signal) { onAbort = () => { - if (this.pendingPmp) { + if (this.pendingPmp === entry) { clearTimeout(this.pendingPmp.timer) this.pendingPmp = null wrappedResolve(parseErr(NatErrorCode.Timeout, 'aborted')) @@ -350,9 +404,8 @@ export class PmpPcpClient { options.signal.addEventListener('abort', onAbort, { once: true }) } - // biome-ignore lint/style/noNonNullAssertion: socket guaranteed by ensureSocket() - this.socket!.send(request, NATPMP_PORT, this.gatewayIp).catch((err) => { - if (this.pendingPmp) { + socket.send(request, NATPMP_PORT, this.gatewayIp).catch((err) => { + if (this.pendingPmp === entry) { clearTimeout(this.pendingPmp.timer) this.pendingPmp = null wrappedResolve( @@ -363,21 +416,55 @@ export class PmpPcpClient { }) } - private ensureSocket(): Promise { + private ensureSocket(): Promise { if (this.socketReady) return this.socketReady - this.socketReady = this.bindSocket() + const socket = this.udpFactory({ type: 'udp4' }) + this.socket = socket + this.socketReady = this.bindSocket(socket) return this.socketReady } - private async bindSocket(): Promise { - this.socket = this.udpFactory({ type: 'udp4' }) - await this.socket.bind(0) - this.socket.onMessage((msg, rinfo) => this.onMessage(msg, rinfo)) - this.nonceCleanupTimer = setInterval( - () => this.cleanupExpiredNonces(), - 1000 - ) - this.nonceCleanupTimer.unref?.() + private async bindSocket(socket: UdpSocket): Promise { + const cancelled = new Promise((_resolve, reject) => { + this.cancelSocketReady = () => reject(new Error('client closing')) + }) + try { + await Promise.race([ + Promise.resolve().then(() => { + if (this.socket !== socket) throw new Error('client closing') + return socket.bind(0) + }), + cancelled, + ]) + if (this.socket !== socket) throw new Error('client closing') + this.cancelSocketReady = null + socket.onMessage((msg, rinfo) => { + if (this.socket === socket) this.onMessage(msg, rinfo) + }) + this.nonceCleanupTimer = setInterval( + () => this.cleanupExpiredNonces(), + 1000 + ) + this.nonceCleanupTimer.unref?.() + return socket + } catch (error) { + // A failed bind must not poison all future requests with a cached + // rejection. A detached socket is already owned by close(). + if (this.socket === socket) { + this.socket = null + this.socketReady = null + this.cancelSocketReady = null + try { + await socket.close() + } catch (closeError) { + log.warn( + { err: closeError }, + 'failed to close UDP socket after bind failure' + ) + } + } + throw error + } } private onMessage(msg: Buffer, rinfo: UdpRemoteInfo): void { diff --git a/src/clients/stun-client.ts b/src/clients/stun-client.ts index d6be19d..e902c7c 100644 --- a/src/clients/stun-client.ts +++ b/src/clients/stun-client.ts @@ -45,6 +45,7 @@ export class StunClient { // classification (Symmetric vs FullCone) requires two-server comparison; // that's future work. for (const server of options.servers) { + if (options.signal?.aborted) break const parsed = this.parseServer(server) if (!parsed.ok) { log.warn({ server }, 'ignoring invalid STUN server format') @@ -100,7 +101,14 @@ export class StunClient { const finish = async (r: ParseResult) => { if (settled) return settled = true - await socket.close().catch(() => {}) + clearTimeout(timer) + signal?.removeEventListener('abort', onAbort) + socket.offMessage(onMessage) + try { + await socket.close() + } catch (error) { + log.warn({ err: error }, 'failed to close STUN socket') + } resolve(r) } @@ -110,33 +118,28 @@ export class StunClient { ) timer.unref?.() - socket.onMessage((msg, _rinfo) => { + const onMessage = (msg: Buffer) => { if (settled) return const parsed = parseBindingResponse(msg, transactionId) if (!parsed.ok) return - clearTimeout(timer) void finish(parsed) - }) + } + socket.onMessage(onMessage) + const onAbort = () => + void finish(parseErr(NatErrorCode.Timeout, 'aborted')) if (signal) { if (signal.aborted) { - clearTimeout(timer) - void finish(parseErr(NatErrorCode.Timeout, 'aborted')) + onAbort() return } - signal.addEventListener( - 'abort', - () => { - clearTimeout(timer) - void finish(parseErr(NatErrorCode.Timeout, 'aborted')) - }, - { once: true } - ) + signal.addEventListener('abort', onAbort, { once: true }) } ;(async () => { try { await socket.bind(0) + if (settled) return await socket.send(buffer, port, host) } catch (err) { clearTimeout(timer) diff --git a/src/clients/upnp-client.ts b/src/clients/upnp-client.ts index d63a49b..8b0ebf2 100644 --- a/src/clients/upnp-client.ts +++ b/src/clients/upnp-client.ts @@ -116,13 +116,19 @@ export class UpnpClient { const ac = new AbortController() const cleanup = async () => { - await socket.close().catch(() => {}) + try { + await socket.close() + } catch (error) { + log.warn({ err: error }, 'failed to close discovery socket') + } } return new Promise>((resolve) => { const settle = async (r: ParseResult) => { if (settled) return settled = true + clearTimeout(timer) + socket.offMessage(listener) ac.abort() this.discovering = false await cleanup() @@ -213,12 +219,14 @@ export class UpnpClient { ;(async () => { try { await socket.bind(0, interfaceAddress) + if (settled) return if (interfaceAddress) { // Binding fixes the unicast response address; IP_MULTICAST_IF // fixes the outgoing M-SEARCH interface (including on Windows). socket.setMulticastInterface?.(interfaceAddress) } for (const st of searchTargets) { + if (settled) return await socket.send( buildMSearch(st, mx), SSDP_MULTICAST_PORT, diff --git a/src/net/node-udp-socket.integration.test.ts b/src/net/node-udp-socket.integration.test.ts new file mode 100644 index 0000000..6c3124f --- /dev/null +++ b/src/net/node-udp-socket.integration.test.ts @@ -0,0 +1,45 @@ +import dgram from 'node:dgram' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { NodeUdpSocket } from './udp-socket.js' + +describe('NodeUdpSocket native lifecycle', () => { + afterEach(() => vi.restoreAllMocks()) + + it('cancels a native bind without waiting for its callback', async () => { + const socket = new NodeUdpSocket({ type: 'udp4' }) + const binding = expect(socket.bind(0, '127.0.0.1')).rejects.toThrow( + 'socket closed' + ) + await socket.close() + await binding + expect(socket.address()).toBeNull() + }) + + it('closes native bound and unbound sockets idempotently', async () => { + for (const bind of [false, true]) { + const socket = new NodeUdpSocket({ type: 'udp4' }) + if (bind) await socket.bind(0, '127.0.0.1') + await Promise.all([socket.close(), socket.close()]) + await socket.close() + } + }) + + it('completes close when an implicit bind fails with queued sends', async () => { + let failBind = () => {} + const native = dgram.createSocket({ + type: 'udp4', + lookup: (_hostname, _options, callback) => { + failBind = () => callback(new Error('bind lookup failed'), '', 4) + }, + }) + vi.spyOn(dgram, 'createSocket').mockReturnValueOnce(native) + const socket = new NodeUdpSocket({ type: 'udp4' }) + const sending = expect( + socket.send(Buffer.from('x'), 5351, '127.0.0.1') + ).rejects.toThrow('socket closed') + const closing = socket.close() + failBind() + await sending + await closing + }) +}) diff --git a/src/net/node-udp-socket.test.ts b/src/net/node-udp-socket.test.ts index 0e186cd..7445143 100644 --- a/src/net/node-udp-socket.test.ts +++ b/src/net/node-udp-socket.test.ts @@ -160,4 +160,116 @@ describe('NodeUdpSocket', () => { ) expect(() => subject.setMulticastTTL(1)).toThrow('socket closed') }) + + it('contains errors after bind and rejects in-flight sends', async () => { + const { socket, subject } = createSubject() + await subject.bind() + socket.send.mockImplementationOnce(() => {}) + const sent = subject.send(Buffer.from('x'), 5351, '192.168.1.1') + const failed = expect(sent).rejects.toThrow('network changed') + expect(() => + socket.emit('error', new Error('network changed')) + ).not.toThrow() + await failed + await subject.close() + }) + + it('settles a pending bind on close even if its callback never arrives', async () => { + const { socket, subject } = createSubject() + socket.bind.mockImplementationOnce(() => {}) + const bound = expect(subject.bind()).rejects.toThrow('socket closed') + await subject.close() + await bound + }) + + it('shares completion between concurrent closes', async () => { + const { socket, subject } = createSubject() + let finishClose = () => {} + socket.close.mockImplementationOnce((callback) => { + finishClose = callback + }) + const first = subject.close() + const second = subject.close() + expect(first).toBe(second) + finishClose() + await Promise.all([first, second]) + expect(socket.close).toHaveBeenCalledOnce() + }) + + it('tolerates an already-closed native socket', async () => { + const { socket, subject } = createSubject() + socket.close.mockImplementationOnce(() => { + throw Object.assign(new Error('Not running'), { + code: 'ERR_SOCKET_DGRAM_NOT_RUNNING', + }) + }) + await expect(subject.close()).resolves.toBeUndefined() + await expect(subject.close()).resolves.toBeUndefined() + }) + + it('contains late native errors and messages after close', async () => { + const { socket, subject } = createSubject() + const listener = vi.fn() + subject.onMessage(listener) + await subject.close() + expect(() => socket.emit('error', new Error('late error'))).not.toThrow() + socket.emit('message', Buffer.from('late'), { + address: '192.168.1.1', + port: 5351, + size: 4, + }) + expect(listener).not.toHaveBeenCalled() + }) + + it('allows retry after a synchronous bind failure without keeping stale callbacks', async () => { + const { socket, subject } = createSubject() + socket.bind.mockImplementationOnce(() => { + throw new Error('bind failed') + }) + await expect(subject.bind()).rejects.toThrow('bind failed') + await expect(subject.bind()).resolves.toBeUndefined() + expect(() => socket.emit('error', new Error('idle error'))).not.toThrow() + await expect( + subject.send(Buffer.from('x'), 5351, '192.168.1.1') + ).resolves.toBeUndefined() + await subject.close() + }) + + it('rejects pending sends on close and ignores their late callbacks', async () => { + const { socket, subject } = createSubject() + let callback = (_error: Error | null) => {} + socket.send.mockImplementationOnce((_msg, _port, _address, cb) => { + callback = cb + }) + const sent = expect( + subject.send(Buffer.from('x'), 5351, '192.168.1.1') + ).rejects.toThrow('socket closed') + await subject.close() + await sent + expect(() => callback(new Error('late error'))).not.toThrow() + expect(socket.close).toHaveBeenCalledOnce() + }) + + it('propagates unexpected native close failures', async () => { + const { socket, subject } = createSubject() + socket.close.mockImplementationOnce(() => { + throw new Error('close failed') + }) + await expect(subject.close()).rejects.toThrow('close failed') + await expect(subject.close()).rejects.toThrow('close failed') + expect(socket.close).toHaveBeenCalledOnce() + }) + + it('settles pending work when the native socket closes independently', async () => { + const { socket, subject } = createSubject() + socket.send.mockImplementationOnce(() => {}) + const sent = expect( + subject.send(Buffer.from('x'), 5351, '192.168.1.1') + ).rejects.toThrow('socket closed') + socket.emit('close') + await sent + await subject.close() + expect(socket.close).not.toHaveBeenCalled() + expect(subject.address()).toBeNull() + }) }) diff --git a/src/net/udp-socket.ts b/src/net/udp-socket.ts index ba6d1c2..5aee7f5 100644 --- a/src/net/udp-socket.ts +++ b/src/net/udp-socket.ts @@ -1,4 +1,7 @@ import dgram from 'node:dgram' +import { natLogger } from '../logger.js' + +const log = natLogger('udp') export interface UdpSocketOptions { type: 'udp4' @@ -28,33 +31,64 @@ export interface UdpSocket { export class NodeUdpSocket implements UdpSocket { private socket: dgram.Socket | null private listeners = new Set() - private closed = false + private closePromise: Promise | null = null + private readonly pending = new Set<(error: Error) => void>() constructor(options: UdpSocketOptions) { this.socket = dgram.createSocket({ type: options.type, reuseAddr: options.reuseAddr ?? true, }) + // dgram can emit errors after bind/send callbacks have completed. Keep + // this listener for the native socket's entire lifetime, including close. + this.socket.on('error', (error: Error) => { + if (!this.socket) return + log.warn({ err: error }, 'UDP socket error') + this.rejectPending(error) + }) + this.socket.once('close', () => { + this.socket = null + this.listeners.clear() + this.rejectPending(new Error('socket closed')) + }) this.socket.on('message', (msg, rinfo) => { for (const l of this.listeners) l(msg, rinfo) }) } bind(port?: number, address?: string): Promise { + return this.runOperation((socket, finish) => { + socket.bind(port ?? 0, address, () => finish()) + }) + } + + private runOperation( + start: ( + socket: dgram.Socket, + finish: (error?: Error | null) => void + ) => void + ): Promise { return new Promise((resolve, reject) => { - if (!this.socket) return reject(new Error('socket closed')) - const onErr = (e: Error) => { - this.socket?.off('error', onErr) - reject(e) + const socket = this.socket + if (!socket) return reject(new Error('socket closed')) + const finish = (error?: Error | null) => { + if (!this.pending.delete(finish)) return + if (error) reject(error) + else resolve() + } + this.pending.add(finish) + try { + start(socket, finish) + } catch (error) { + finish(error as Error) } - this.socket.once('error', onErr) - this.socket.bind(port ?? 0, address, () => { - this.socket?.off('error', onErr) - resolve() - }) }) } + private rejectPending(error: Error): void { + for (const finish of this.pending) finish(error) + } + addMembership(multicastAddress: string, interfaceAddress?: string): void { if (!this.socket) throw new Error('socket closed') this.socket.addMembership(multicastAddress, interfaceAddress) @@ -71,17 +105,13 @@ export class NodeUdpSocket implements UdpSocket { } send(msg: Buffer, port: number, address: string): Promise { - return new Promise((resolve, reject) => { - if (!this.socket) return reject(new Error('socket closed')) - this.socket.send(msg, port, address, (err) => { - if (err) reject(err) - else resolve() - }) + return this.runOperation((socket, finish) => { + socket.send(msg, port, address, finish) }) } onMessage(listener: UdpMessageListener): void { - this.listeners.add(listener) + if (this.socket) this.listeners.add(listener) } offMessage(listener: UdpMessageListener): void { @@ -89,13 +119,39 @@ export class NodeUdpSocket implements UdpSocket { } close(): Promise { - if (this.closed || !this.socket) return Promise.resolve() - this.closed = true - const s = this.socket + if (this.closePromise) return this.closePromise + const socket = this.socket this.socket = null - return new Promise((resolve) => { - s.close(() => resolve()) + this.listeners.clear() + this.rejectPending(new Error('socket closed')) + this.closePromise = new Promise((resolve, reject) => { + if (!socket) return resolve() + const finish = (error?: unknown) => { + socket.off('error', closeNative) + if (error) reject(error) + else resolve() + } + const closeNative = () => { + try { + socket.close(() => finish()) + } catch (error) { + if ( + (error as NodeJS.ErrnoException).code === + 'ERR_SOCKET_DGRAM_NOT_RUNNING' + ) { + finish() + } else { + finish(error) + } + } + } + // dgram queues close behind an implicit bind from send(). A bind error + // discards that queue without closing the handle or invoking callbacks; + // retry close once the error event has cleared the native queue. + socket.on('error', closeNative) + closeNative() }) + return this.closePromise } address(): { port: number; address: string } | null {