| 24 | const dnsCache = new Map<string, DnsResult>; |
| 25 | |
| 26 | const lookup = ( |
| 27 | hostname: string, |
| 28 | options: dns.LookupOptions, |
| 29 | callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number |
| 30 | ) => void): void => { |
| 31 | // Check DNS cache first |
| 32 | const cachedResult = dnsCache.get(hostname); |
| 33 | if (cachedResult && cachedResult.expiry > Date.now()) { |
| 34 | callback(null, cachedResult.address, cachedResult.family); |
| 35 | return; |
| 36 | } |
| 37 | |
| 38 | const buf = dnsPacket.encode({ |
| 39 | type: 'query', |
| 40 | id: getId(), |
| 41 | flags: dnsPacket.RECURSION_DESIRED, |
| 42 | questions: [{ |
| 43 | type: 'A', |
| 44 | name: hostname |
| 45 | }] |
| 46 | }); |
| 47 | |
| 48 | const reqOpts = { |
| 49 | hostname: 'cloudflare-dns.com', |
| 50 | port: 443, |
| 51 | path: '/dns-query', |
| 52 | method: 'POST', |
| 53 | headers: { |
| 54 | 'Content-Type': 'application/dns-message', |
| 55 | 'Content-Length': Buffer.byteLength(buf) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | const request = https.request(reqOpts, (response) => { |
| 60 | response.on('data', (d) => { |
| 61 | const result = dnsPacket.decode(d); |
| 62 | if (result.answers && result.answers.length > 0) { |
| 63 | const answer: any = result.answers[0]; |
| 64 | dnsCache.set(hostname, { |
| 65 | address: answer.data, |
| 66 | family: 4, |
| 67 | expiry: Date.now() + (answer.ttl * 1000) |
| 68 | }); |
| 69 | callback(null, answer.data, 4); |
| 70 | } else { |
| 71 | callback(new Error('No answers in DNS response'), '', 0); |
| 72 | } |
| 73 | }) |
| 74 | }) |
| 75 | |
| 76 | |
| 77 | request.on('error', (e) => { |
| 78 | console.error(e); |
| 79 | callback(e, '', 0); |
| 80 | }) |
| 81 | request.write(buf) |
| 82 | request.end() |
| 83 | } |