import { Answer, AUTHORITATIVE_ANSWER, Packet } from "dns-packet"; import { toAnswer } from "./toAnswer.js"; import ApexDomain from "../../common/ApexDomain.js"; import TimedCache from "@entity-access/entity-access/dist/common/cache/TimedCache.js"; import sleep from "../../common/sleep.js"; import { globalServices } from "../../globalServices.js"; import MessagingService from "../services/message-events/MessagingService.js"; import DnsServer from "./DnsServer.js"; import { AppStringHelper } from "../../common/AppStringHelper.js"; import SocialMailContext from "../model/SocialMailContext.js"; interface IDnsResponseRecord { additionals: Answer[]; answers: Answer[]; authorities: Answer[]; } const getApexDomain = (name: string) => { try { return ApexDomain.getApexDomain(name); } catch (error) { console.error(`Failed to get apex domain for ${name}`); return null; } }; export default class NamedService { public static instance = new NamedService(); private timedCache = new TimedCache(15*60*1000); // private ac: AbortController = new AbortController(); async restart(serverID) { await sleep(5000); console.log(`Name server cache cleared`); this.timedCache.clear(); } public start() { const ms = globalServices.resolve(MessagingService); ms.refreshDns.on(({ serverID }) => this.restart(serverID).catch(console.error)); ms.clearDnsCache.on(() => { console.log(`Name server cache cleared`); this.timedCache.clear(); }); this.runRepeat().catch(console.error); } private async runRepeat() { while(true) { try { const ns = new DnsServer(); ns.onRequest = (req) => this.request(req); await ns.listen(5053); } catch (error) { console.error(error); } await sleep(15000); } } private async request(req: Packet): Promise { let success = false; const additionals = []; const answers = []; const authorities = []; let flags = AUTHORITATIVE_ANSWER; for (const { name, type } of req.questions) { // const typeName = nsTypeNames[type]; // console.log(`${name}-${type}`); const lowerCaseName = AppStringHelper.remove00(name).trim().toLowerCase(); if (!lowerCaseName) { continue; } const rs = await this.timedCache.getOrCreateAsync(`${lowerCaseName}-${type}`, (x) => this.queryDb(type, lowerCaseName)); for (const r of rs.answers) { success ||= true; answers.push(r); } for (const r of rs.additionals) { success ||= true; additionals.push(r); } for (const r of rs.authorities) { success ||= true; authorities.push(r); } } if (!success) { flags = 0x3; } return { type: "response", id: req.id, flags, questions: req.questions, answers, additionals, authorities }; } private async queryDb(typeName: string, name: string): Promise { using scope = globalServices.createScope(); const db = scope.resolve(SocialMailContext); const answers = [] as Answer[]; const additionals = [] as Answer[]; const authorities = [] as Answer[]; const { domain: root, subdomain } = getApexDomain(name); if (!root) { return { answers, authorities, additionals }; } // const nsRecords = await db.dnsZoneRecords.where({ typeName, root }, (x, p) => // x.type === "NS" // && x.fqdn === p.root) // .toArray(); // const soaRecords = await db.dnsZoneRecords.where({ typeName, root }, (x, p) => // x.type === "SOA" // && x.fqdn === p.root) // .toArray(); // const hasAuthority = nsRecords.length > 0; // for (const x of nsRecords) { // authorities.push(toAnswer(name, x)); // } if (name.startsWith("*.")) { // we do not support wildcard delegation return { answers, authorities, additionals }; } const cNameQueries = []; const typeNames = [typeName]; if (typeName === "A" || typeName === "AAAA" || typeName === "TXT") { typeNames.push("CNAME"); } // console.log(`looking for ${typeNames} for ${name}`); // check if there is a wildcard ... const records = await db.cachedDnsRecords.where({ typeNames, host: name }, (x, p) => x.type in p.typeNames && x.fqdn === p.host && x.disabled === false ) .toArray(); const rootPostFix = "." + root; let answerCount = 0; // console.log(records); for (const x of records) { switch(x.type) { case "CNAME": if (x.value.endsWith(rootPostFix)) { // CNAME should not resolve itself as a CNAME if (name !== x.value) { cNameQueries.push(x.value); continue; } } answerCount++; break; case "MX": if (x.value.endsWith(rootPostFix)) { cNameQueries.push(x.value.split(" ").pop()); } answerCount++; break; default: answerCount++; break; } answers.push(toAnswer(name, x)); } if(cNameQueries.length) { const nameRecords = await db.cachedDnsRecords.where({ cNameQueries }, (x, p) => x.fqdn in p.cNameQueries && x.type === "A" ).toArray(); for (const x of nameRecords) { answerCount++; additionals.push(toAnswer(x.fqdn,x)); } } const i = subdomain.indexOf("."); const wildcard = i === -1 ? `*.${root}` : `*.${subdomain.substring(i + 1)}.${root}`; ; if (answerCount === 0) { if (typeName === "A") { // console.log(`Looking up ${wildcard} for ${name}`); const r = await db.cachedDnsRecords.where({ wildcard }, (x, p) => x.fqdn === p.wildcard && x.disabled === false ) .toArray(); for (const x of r) { answers.push(toAnswer(name, x)); } } if (typeName === "AAAA") { // if there is no A record... const hasA = await db.cachedDnsRecords .where({ host: name}, (x, p) => x.fqdn === p.host && x.type === "A" && x.disabled === false) .some(); if (!hasA) { const r = await db.cachedDnsRecords.where({ wildcard }, (x, p) => x.fqdn === p.wildcard && x.disabled === false ) .toArray(); for (const x of r) { answers.push(toAnswer(name, x)); } } } } // console.log({ answers, additionals, authorities }); const authorityRecords = (answers.length || additionals.length) ? await db.cachedDnsRecords.where({ typeName, root }, (x, p) => x.type === "NS" && x.fqdn === p.root && x.disabled === false) .toArray() : await db.cachedDnsRecords.where({ typeName, root }, (x, p) => x.type === "SOA" && x.fqdn === p.root && x.disabled === false) .toArray(); for (const x of authorityRecords) { authorities.push(toAnswer(name, x)); } return { answers, additionals, authorities }; } }