/* eslint-disable no-bitwise */ /* eslint-disable no-console */ import dgram from "node:dgram"; import dnsPacket from "dns-packet"; const debugLevel = Number.parseInt(process.env.NODE_DEBUG, 16); const debug = debugLevel & 0x4 ? (x) => console.error("DNS-Q: " + x) : void 0; export default class DnsServer { udp: dgram.Socket; onRequest: (msg: dnsPacket.Packet) => Promise; async listen(port = 5053) { while(true) { await new Promise((resolve, reject) => { this.udp = dgram.createSocket("udp4"); this.udp.on("listening", () => console.log(`DNS Server Listening on ${port}`)); this.udp.on("error", (error) => { console.error(error); }); this.udp.on("close", resolve); this.udp.on("message", (msg, rinfo) => { debug?.(hexDump(msg)); this.process(msg, rinfo).catch(console.error); }); this.udp.bind(port); }); } } private async process(msg: Buffer, rinfo: dgram.RemoteInfo) { let response: dnsPacket.Packet; let packet; try { packet = dnsPacket.decode(msg); response = await this.onRequest(packet); const buffer = dnsPacket.encode(response); this.udp.send(buffer, 0, buffer.length, rinfo.port, rinfo.address, (error) => { debug?.(error); }); } catch (error) { if (response) { console.log(response); return; } if (packet) { console.error(error); return; } } } } /** * Debugging utility to print part of packet in hex. * @param {Buffer} buf * @param {number} length * @param {number} width Octets per line * @return {string} */ function hexDump(buf, length?, width = 32) { if (!Buffer.isBuffer(buf)) { throw new Error("argument must be buffer"); } let str = "\n"; str += "0"; str += "\t"; for (let i = 0; i < length; i++) { str += buf.toString("hex", i, i + 1); str += " "; if ((i + 1) % (width / 2)) {continue;} str += " "; if ((i + 1) % width) {continue;} str += "\n"; str += String(i + 1); str += "\t"; } return str; }