diff --git a/src/index.node.ts b/src/index.node.ts index 75e191e..47c9681 100644 --- a/src/index.node.ts +++ b/src/index.node.ts @@ -1,2 +1,3 @@ export * from './index.shared.js'; export * from './AsyncSerialPort.node.js'; +export * from './ppp/TcpSocket.js'; diff --git a/src/index.shared.ts b/src/index.shared.ts index 28180e9..26707ab 100644 --- a/src/index.shared.ts +++ b/src/index.shared.ts @@ -4,6 +4,7 @@ export * from './ppp/ICMP.js'; export * from './ppp/IPv4.js'; export * from './ppp/TCP.js'; export * from './ppp/UDP.js'; +export * from './ppp/DNS.js'; export * from './bfc/BFC.js'; export * from './bfb/BFB.js'; export * from './cgsn/CGSN.js'; diff --git a/src/ppp/DNS.test.ts b/src/ppp/DNS.test.ts new file mode 100644 index 0000000..396e58d --- /dev/null +++ b/src/ppp/DNS.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, test } from 'vitest'; +import { encodeDnsQuery, parseDnsResponse } from './DNS.js'; + +describe('DNS: encodeDnsQuery', () => { + test('encodes an A query with recursion desired', () => { + expect(encodeDnsQuery(0x1234, 'example.org').toString('hex')).toBe( + '1234' + '0100' + '0001' + '0000' + '0000' + '0000' + + '07' + Buffer.from('example').toString('hex') + '03' + Buffer.from('org').toString('hex') + '00' + + '0001' + '0001', + ); + }); +}); + +describe('DNS: parseDnsResponse', () => { + test('decodes A records after a compressed CNAME answer', () => { + const response = Buffer.from( + '1234' + '8180' + '0001' + '0002' + '0000' + '0000' + + '03' + Buffer.from('www').toString('hex') + '07' + Buffer.from('example').toString('hex') + '03' + Buffer.from('org').toString('hex') + '00' + + '0001' + '0001' + + // www.example.org CNAME example.org + 'c00c' + '0005' + '0001' + '00000e10' + '0002' + 'c010' + + // example.org A 93.184.215.14 + 'c010' + '0001' + '0001' + '00000e10' + '0004' + '5db8d70e', + 'hex', + ); + expect(parseDnsResponse(0x1234, response)).toEqual(['93.184.215.14']); + }); + + test('ignores responses to another query', () => { + const response = Buffer.from('4321' + '8180' + '0000' + '0000' + '0000' + '0000', 'hex'); + expect(parseDnsResponse(0x1234, response)).toBeUndefined(); + }); + + test('reports a server error', () => { + const response = Buffer.from('1234' + '8183' + '0000' + '0000' + '0000' + '0000', 'hex'); + expect(() => parseDnsResponse(0x1234, response)).toThrow('DNS server returned error 3.'); + }); +}); diff --git a/src/ppp/DNS.ts b/src/ppp/DNS.ts new file mode 100644 index 0000000..5bacce1 --- /dev/null +++ b/src/ppp/DNS.ts @@ -0,0 +1,105 @@ +import { usePromiseWithResolvers } from '#src/utils.js'; +import { formatIpv4Address } from './IPv4.js'; +import type { PPP } from './PPP.js'; +import { UDP } from './UDP.js'; + +const DNS_PORT = 53; +const DNS_FLAG_RESPONSE = 0x8000; +const DNS_FLAG_RECURSION_DESIRED = 0x0100; +const DNS_RCODE_MASK = 0x000F; +const DNS_TYPE_A = 1; +const DNS_CLASS_IN = 1; +const DNS_POINTER = 0xC0; + +export function encodeDnsQuery(id: number, hostname: string): Buffer { + const labels = hostname.split('.').map((label) => Buffer.from(label, 'ascii')); + if (labels.some((label) => label.length < 1 || label.length > 63)) + throw new Error(`Invalid DNS name: ${hostname}`); + const header = Buffer.alloc(12); + header.writeUInt16BE(id, 0); + header.writeUInt16BE(DNS_FLAG_RECURSION_DESIRED, 2); + header.writeUInt16BE(1, 4); + const question = Buffer.alloc(4); + question.writeUInt16BE(DNS_TYPE_A, 0); + question.writeUInt16BE(DNS_CLASS_IN, 2); + return Buffer.concat([ + header, + ...labels.flatMap((label) => [Buffer.from([label.length]), label]), + Buffer.from([0]), + question, + ]); +} + +export function parseDnsResponse(id: number, response: Buffer): string[] | undefined { + if (response.length < 12 || response.readUInt16BE(0) != id) + return undefined; + const flags = response.readUInt16BE(2); + if ((flags & DNS_FLAG_RESPONSE) == 0) + return undefined; + const rcode = flags & DNS_RCODE_MASK; + if (rcode != 0) + throw new Error(`DNS server returned error ${rcode}.`); + const questions = response.readUInt16BE(4); + const answers = response.readUInt16BE(6); + let offset = 12; + for (let i = 0; i < questions; i++) + offset = skipDnsName(response, offset) + 4; + const addresses: string[] = []; + for (let i = 0; i < answers; i++) { + offset = skipDnsName(response, offset); + if (offset + 10 > response.length) + throw new Error('DNS response is truncated.'); + const type = response.readUInt16BE(offset); + const dataClass = response.readUInt16BE(offset + 2); + const dataLength = response.readUInt16BE(offset + 8); + offset += 10; + if (offset + dataLength > response.length) + throw new Error('DNS response is truncated.'); + if (type == DNS_TYPE_A && dataClass == DNS_CLASS_IN && dataLength == 4) + addresses.push(formatIpv4Address(response.subarray(offset, offset + 4))); + offset += dataLength; + } + return addresses; +} + +export class DNS { + constructor(private readonly ppp: PPP) {} + + async resolveIpv4(hostname: string, server: string, timeout = 10000): Promise { + const id = Math.floor(Math.random() * 0x10000); + const udp = new UDP(this.ppp); + const { promise, resolve, reject } = usePromiseWithResolvers(); + udp.onMessage((message) => { + if (message.address != server || message.port != DNS_PORT) + return; + try { + const addresses = parseDnsResponse(id, message.data); + if (addresses) + resolve(addresses); + } catch (error) { + reject(error); + } + }); + const timer = setTimeout(() => reject(new Error(`DNS query for ${hostname} timed out.`)), timeout); + void promise.catch(() => undefined); + try { + await udp.send(server, DNS_PORT, encodeDnsQuery(id, hostname)); + return await promise; + } finally { + clearTimeout(timer); + udp.close(); + } + } +} + +function skipDnsName(message: Buffer, offset: number): number { + while (offset < message.length) { + const length = message[offset]; + if ((length & DNS_POINTER) == DNS_POINTER) + return offset + 2; + offset += 1 + length; + if (length == 0) + return offset; + } + throw new Error('DNS response is truncated.'); +} diff --git a/src/ppp/PPP.test.ts b/src/ppp/PPP.test.ts index 8745db7..d48e556 100644 --- a/src/ppp/PPP.test.ts +++ b/src/ppp/PPP.test.ts @@ -1,11 +1,14 @@ +import { once } from 'node:events'; import { afterAll, beforeAll, describe, expect, test } from 'vitest'; import { openPort } from '../../examples/utils.js'; import { AsyncSerialPort } from '#src/AsyncSerialPort.js'; import { AtChannel, type AtCommandResponse } from '#src/at/AtChannel.js'; import { delay } from '#src/utils.js'; +import { DNS, encodeDnsQuery } from './DNS.js'; import { ICMP } from './ICMP.js'; import { PPP, PppProtocol, type PppConnectionInfo, type PppPingResult } from './PPP.js'; import { TCP } from './TCP.js'; +import { TcpSocket } from './TcpSocket.js'; import { UDP } from './UDP.js'; const PORT_PATH = process.env.PPP_PORT ?? '/dev/ttyUSB0'; @@ -14,6 +17,7 @@ const USERNAME = process.env.PPP_USERNAME ?? ''; const PASSWORD = process.env.PPP_PASSWORD ?? ''; const TARGET = process.env.PPP_TARGET ?? '8.8.8.8'; const DNS_TARGET = process.env.PPP_DNS_TARGET ?? '8.8.8.8'; +const DNS_HOSTNAME = process.env.PPP_DNS_HOSTNAME ?? 'example.com'; const TCP_TARGET = process.env.PPP_TCP_TARGET ?? '1.1.1.1'; const TCP_PORT = Number(process.env.PPP_TCP_PORT ?? 80); const DIAL_COMMAND = process.env.PPP_DIAL ?? 'ATDT*99***1#'; @@ -122,7 +126,7 @@ describeHardware('PPP hardware', () => { if (!ppp) throw new Error('PPP was not initialized.'); const udp = new UDP(ppp); - const query = dnsQuery(); + const query = encodeDnsQuery(Math.floor(Math.random() * 0x10000), DNS_HOSTNAME); let timer: NodeJS.Timeout | undefined; try { const response = new Promise((resolve, reject) => { @@ -142,6 +146,15 @@ describeHardware('PPP hardware', () => { } }, 15000); + test('resolves a hostname through DNS', async () => { + if (!ppp) + throw new Error('PPP was not initialized.'); + const addresses = await new DNS(ppp).resolveIpv4(DNS_HOSTNAME, DNS_TARGET, 10000); + expect(addresses.length).toBeGreaterThan(0); + for (const address of addresses) + expect(address).toMatch(/^\d+\.\d+\.\d+\.\d+$/); + }, 15000); + test('opens a TCP connection and exchanges data', async () => { if (!ppp) throw new Error('PPP was not initialized.'); @@ -171,16 +184,26 @@ describeHardware('PPP hardware', () => { await tcp.close(); } }, 35000); -}); -function dnsQuery(): Buffer { - const id = Math.floor(Math.random() * 0x10000); - return Buffer.from([ - id >> 8, id & 0xFF, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 7, ...Buffer.from('example'), 3, - ...Buffer.from('com'), 0, 0, 1, 0, 1, - ]); -} + test('exchanges data through TcpSocket until the peer closes', async () => { + if (!ppp) + throw new Error('PPP was not initialized.'); + const socket = new TcpSocket(ppp); + try { + await socket.connect(TCP_TARGET, TCP_PORT, 15000); + const chunks: Buffer[] = []; + socket.on('data', (chunk: Buffer) => chunks.push(chunk)); + const closed = once(socket, 'close', { signal: AbortSignal.timeout(20000) }); + socket.write('GET / HTTP/1.0\r\nHost: one.one.one.one\r\nConnection: close\r\n\r\n'); + await closed; + expect(Buffer.concat(chunks).toString()).toMatch(/^HTTP\/1\.[01] /); + expect(socket.readableEnded).toBe(true); + expect(socket.writableFinished).toBe(true); + } finally { + socket.destroy(); + } + }, 40000); +}); async function waitForAttach(atc: AtChannel, attached: boolean, timeout: number): Promise { const deadline = Date.now() + timeout; diff --git a/src/ppp/PPP.ts b/src/ppp/PPP.ts index e0e26ae..69331af 100644 --- a/src/ppp/PPP.ts +++ b/src/ppp/PPP.ts @@ -479,11 +479,6 @@ export class PPP extends BaseSerialProtocol { while (!localOpened || !peerOpened) { const packet = await this.nextPacketUntil(deadline, retryInterval); if (!packet) { - const compatibleOptions = removeIpcpDnsOptions(requestOptions); - if (compatibleOptions.length != requestOptions.length) { - requestOptions = compatibleOptions; - request = this.createControlPacket(PppControlCode.CONFIGURE_REQUEST, requestOptions); - } await this.send(PppProtocol.IPCP, request); continue; } @@ -810,11 +805,6 @@ function ipcpOptions(): Buffer { ]); } -function removeIpcpDnsOptions(options: Buffer): Buffer { - return Buffer.concat(splitOptions(options).filter((option) => - option[0] != IpcpOption.PRIMARY_DNS && option[0] != IpcpOption.SECONDARY_DNS)); -} - function rejectIpcpOptions(data: Buffer): Buffer { return Buffer.concat(splitOptions(data).filter((option) => { switch (option[0]) { diff --git a/src/ppp/TCP.ts b/src/ppp/TCP.ts index 94467bf..c36fc59 100644 --- a/src/ppp/TCP.ts +++ b/src/ppp/TCP.ts @@ -39,6 +39,7 @@ type CloseWaiter = { }; export type TcpDataHandler = (data: Buffer) => void; +export type TcpEndHandler = (error?: Error) => void; export class TCP { readonly localPort: number; @@ -54,6 +55,7 @@ export class TCP { private closing = false; private sending = false; private readonly handlers = new Set(); + private readonly endHandlers = new Set(); private readonly segments: TcpSegment[] = []; private segmentWaiter: SegmentWaiter | undefined; private ackWaiter: AckWaiter | undefined; @@ -75,6 +77,13 @@ export class TCP { return () => this.handlers.delete(callback); } + onEnd(callback: TcpEndHandler): () => void { + if (this.closed) + throw new Error('TCP socket is closed.'); + this.endHandlers.add(callback); + return () => this.endHandlers.delete(callback); + } + async connect(address: string, port: number, timeout = 10000): Promise { if (this.closed) throw new Error('TCP socket is closed.'); @@ -161,6 +170,7 @@ export class TCP { this.connected = false; this.unsubscribe(); this.handlers.clear(); + this.endHandlers.clear(); const error = new Error('TCP socket is closed.'); if (this.segmentWaiter) { clearTimeout(this.segmentWaiter.timer); @@ -256,8 +266,10 @@ export class TCP { private handleConnectedSegment(segment: TcpSegment): void { if ((segment.flags & TCP_RST) != 0) { - this.ackWaiter?.reject(new Error('TCP connection was reset by the peer.')); + const error = new Error('TCP connection was reset by the peer.'); + this.ackWaiter?.reject(error); this.ackWaiter = undefined; + this.notifyEnd(error); this.destroy(); return; } @@ -290,11 +302,22 @@ export class TCP { clearTimeout(waiter.timer); waiter.resolve(); } + this.notifyEnd(); } if (segment.payload.length > 0 || (segment.flags & TCP_FIN) != 0) void this.sendSegment(TCP_ACK, Buffer.alloc(0)).catch((error: unknown) => debug('TCP ACK failed: %O', error)); } + private notifyEnd(error?: Error): void { + for (const callback of this.endHandlers) { + try { + callback(error); + } catch (callbackError) { + debug('TCP end callback failed: %O', callbackError); + } + } + } + private nextSegment(timeout: number): Promise { const segment = this.segments.shift(); if (segment) diff --git a/src/ppp/TcpSocket.ts b/src/ppp/TcpSocket.ts new file mode 100644 index 0000000..f038623 --- /dev/null +++ b/src/ppp/TcpSocket.ts @@ -0,0 +1,47 @@ +import { Duplex } from 'node:stream'; +import type { PPP } from './PPP.js'; +import { TCP } from './TCP.js'; + +export class TcpSocket extends Duplex { + private readonly tcp: TCP; + + constructor(ppp: PPP) { + super({ allowHalfOpen: false }); + this.tcp = new TCP(ppp); + this.tcp.onData((data) => this.push(data)); + this.tcp.onEnd((error) => { + if (error) + this.destroy(error); + else + this.push(null); + }); + } + + async connect(address: string, port: number, timeout?: number): Promise { + try { + await this.tcp.connect(address, port, timeout); + } catch (error) { + this.destroy(); + throw error; + } + } + + override _read(): void { + } + + override _write(chunk: Buffer, _encoding: BufferEncoding, callback: (error?: Error | null) => void): void { + this.tcp.send(chunk).then(() => callback(), callback); + } + + override _final(callback: (error?: Error | null) => void): void { + this.tcp.close().then(() => { + this.push(null); + callback(); + }, callback); + } + + override _destroy(error: Error | null, callback: (error?: Error | null) => void): void { + this.tcp.destroy(); + callback(error); + } +}