@intellectual-frontiers/net 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/acme.d.ts +71 -0
- package/dist/acme.js +475 -0
- package/dist/dns.d.ts +57 -0
- package/dist/dns.js +381 -0
- package/dist/http-client.d.ts +149 -0
- package/dist/http-client.js +248 -0
- package/dist/mod.d.ts +21 -0
- package/dist/mod.js +21 -0
- package/dist/net.d.ts +84 -0
- package/dist/net.js +288 -0
- package/dist/serve.d.ts +33 -0
- package/dist/serve.js +109 -0
- package/dist/tcp.d.ts +77 -0
- package/dist/tcp.js +274 -0
- package/package.json +72 -4
- package/src/acme.ts +546 -0
- package/src/dns.ts +423 -0
- package/src/http-client.ts +369 -0
- package/src/mod.ts +22 -0
- package/src/net.ts +332 -0
- package/src/serve.ts +135 -0
- package/src/tcp.ts +344 -0
package/src/dns.ts
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
// Spec: 0001-net FR-007
|
|
2
|
+
/**
|
|
3
|
+
* Names on the network (commons 0001-net FR-007). `resolveDns` asks for `A`, `AAAA`, `CNAME`, `MX`, `NS`, `TXT` and `SRV`
|
|
4
|
+
* records, with the records in these shapes (`MX` as `{ preference, exchange }`, `TXT` as each record's
|
|
5
|
+
* strings, `SRV` as `{ priority, weight, port, target }`), and answers with a `Result` whose error says whether the name does not exist,
|
|
6
|
+
* has no such record, or could not be asked: a name that does not resolve is an expected outcome, not an exception.
|
|
7
|
+
*
|
|
8
|
+
* The question is asked here, over `node:dgram` (and `node:net` where the answer is too long for UDP), not through `node:dns`: the two
|
|
9
|
+
* runtimes' `node:dns` can disagree on exactly what this must tell apart (Bun reports a name without the record as one that does not exist),
|
|
10
|
+
* so one small stub resolver (RFC 1035, with EDNS0
|
|
11
|
+
* for answers up to 1232 bytes over UDP) gives the same answer everywhere. The servers asked are the system's (`node:dns`'s `getServers`,
|
|
12
|
+
* which reads `/etc/resolv.conf` or Windows's settings) or the one given; each is tried twice, for two seconds each time.
|
|
13
|
+
*
|
|
14
|
+
* Names in records come without the trailing dot (`mail.example.com`, as Node gives them). The
|
|
15
|
+
* DNS is asked directly, so the hosts file (`localhost`) is not read.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { resolveDns } from "./dns.ts";
|
|
20
|
+
* const r = await resolveDns("example.com", "MX");
|
|
21
|
+
* if (r.kind === "ok") for (const mx of r.value) console.log(mx.preference, mx.exchange);
|
|
22
|
+
* else if (r.error.kind === "not-found") console.log("no such domain");
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* @module
|
|
26
|
+
*/
|
|
27
|
+
import { getServers } from "node:dns";
|
|
28
|
+
import * as dgram from "node:dgram";
|
|
29
|
+
import * as net from "node:net";
|
|
30
|
+
import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
31
|
+
|
|
32
|
+
/** The record types that can be asked for. */
|
|
33
|
+
export type RecordType = "A" | "AAAA" | "CNAME" | "MX" | "NS" | "TXT" | "SRV";
|
|
34
|
+
|
|
35
|
+
/** A mail exchanger. */
|
|
36
|
+
export type MxRecord = { readonly preference: number; readonly exchange: string };
|
|
37
|
+
|
|
38
|
+
/** A service's host and port. */
|
|
39
|
+
export type SrvRecord = { readonly priority: number; readonly weight: number; readonly port: number; readonly target: string };
|
|
40
|
+
|
|
41
|
+
/** The shape of one record of each type: an address or a name as a string, `TXT` as its strings (join them for the whole text). */
|
|
42
|
+
export type RecordOf = {
|
|
43
|
+
readonly A: string;
|
|
44
|
+
readonly AAAA: string;
|
|
45
|
+
readonly CNAME: string;
|
|
46
|
+
readonly NS: string;
|
|
47
|
+
readonly MX: MxRecord;
|
|
48
|
+
readonly TXT: readonly string[];
|
|
49
|
+
readonly SRV: SrvRecord;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Why there is no answer: the name does not exist (NXDOMAIN), it has no record of that type, or the DNS could not be asked (`code` is
|
|
54
|
+
* `ESERVFAIL`, `EREFUSED`, `EFORMERR`, `ENOTIMP` or `ERCODE<n>` for the server's answer, `ETIMEOUT`, `ECANCELLED`, `EBADRESP` for an
|
|
55
|
+
* answer that cannot be read, `EBADNAME`, `ENOSERVERS`, or the host's error code, such as `ECONNREFUSED`).
|
|
56
|
+
*/
|
|
57
|
+
export type DnsError =
|
|
58
|
+
| { readonly kind: "not-found"; readonly name: string }
|
|
59
|
+
| { readonly kind: "no-data"; readonly name: string; readonly type: RecordType }
|
|
60
|
+
| { readonly kind: "failed"; readonly name: string; readonly code: string; readonly message: string };
|
|
61
|
+
|
|
62
|
+
/** The server to ask, instead of the system's. */
|
|
63
|
+
export type NameServer = { readonly ipAddr: string; readonly port?: number };
|
|
64
|
+
|
|
65
|
+
/** How to ask. */
|
|
66
|
+
export type ResolveDnsOptions = {
|
|
67
|
+
/** The server to ask; the system's where not given. */
|
|
68
|
+
readonly nameServer?: NameServer;
|
|
69
|
+
/** Aborting it gives up (a `failed` error with code `ECANCELLED`). */
|
|
70
|
+
readonly signal?: AbortSignal;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const TYPE_CODE: { readonly [K in RecordType]: number } = { A: 1, NS: 2, CNAME: 5, MX: 15, TXT: 16, AAAA: 28, SRV: 33 };
|
|
74
|
+
const CLASS_IN = 1;
|
|
75
|
+
const OPT = 41;
|
|
76
|
+
const UDP_SIZE = 1232;
|
|
77
|
+
const TRY_MS = 2000;
|
|
78
|
+
const TRIES = 2;
|
|
79
|
+
const RCODE: Readonly<Record<number, string>> = { 1: "EFORMERR", 2: "ESERVFAIL", 4: "ENOTIMP", 5: "EREFUSED" };
|
|
80
|
+
|
|
81
|
+
type Failed = Extract<DnsError, { kind: "failed" }>;
|
|
82
|
+
|
|
83
|
+
/** A failure that ends the whole query (the caller gave up), as opposed to one where the next try or server may help. */
|
|
84
|
+
class Stop extends Error {
|
|
85
|
+
readonly code: string;
|
|
86
|
+
constructor(code: string, message: string) {
|
|
87
|
+
super(message);
|
|
88
|
+
this.code = code;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function u16(n: number): readonly number[] {
|
|
93
|
+
return [(n >> 8) & 0xff, n & 0xff];
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function encodeName(name: string): number[] | undefined {
|
|
97
|
+
const trimmed = name.endsWith(".") ? name.slice(0, -1) : name;
|
|
98
|
+
if (trimmed === "") return [0];
|
|
99
|
+
const out: number[] = [];
|
|
100
|
+
for (const label of trimmed.split(".")) {
|
|
101
|
+
const bytes = new TextEncoder().encode(label);
|
|
102
|
+
if (bytes.length === 0 || bytes.length > 63) return undefined;
|
|
103
|
+
out.push(bytes.length, ...bytes);
|
|
104
|
+
}
|
|
105
|
+
out.push(0);
|
|
106
|
+
return out.length > 255 ? undefined : out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function query(id: number, qname: readonly number[], qtype: number): Uint8Array {
|
|
110
|
+
return Uint8Array.from([
|
|
111
|
+
...u16(id),
|
|
112
|
+
0x01,
|
|
113
|
+
0x00, // a standard query, recursion desired
|
|
114
|
+
...u16(1),
|
|
115
|
+
...u16(0),
|
|
116
|
+
...u16(0),
|
|
117
|
+
...u16(1), // one question, and one additional record: EDNS0's OPT
|
|
118
|
+
...qname,
|
|
119
|
+
...u16(qtype),
|
|
120
|
+
...u16(CLASS_IN),
|
|
121
|
+
0, // the root
|
|
122
|
+
...u16(OPT),
|
|
123
|
+
...u16(UDP_SIZE),
|
|
124
|
+
0,
|
|
125
|
+
0,
|
|
126
|
+
0,
|
|
127
|
+
0,
|
|
128
|
+
...u16(0),
|
|
129
|
+
]);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** A reader of a DNS message that throws `RangeError` past its end. */
|
|
133
|
+
class Message {
|
|
134
|
+
readonly bytes: Uint8Array;
|
|
135
|
+
pos = 0;
|
|
136
|
+
constructor(bytes: Uint8Array) {
|
|
137
|
+
this.bytes = bytes;
|
|
138
|
+
}
|
|
139
|
+
byte(at = this.pos++): number {
|
|
140
|
+
const b = this.bytes[at];
|
|
141
|
+
if (b === undefined) throw new RangeError("the answer ends early");
|
|
142
|
+
return b;
|
|
143
|
+
}
|
|
144
|
+
u16(): number {
|
|
145
|
+
return (this.byte() << 8) | this.byte();
|
|
146
|
+
}
|
|
147
|
+
u32(): number {
|
|
148
|
+
return ((this.u16() << 16) >>> 0) + this.u16();
|
|
149
|
+
}
|
|
150
|
+
slice(length: number): Uint8Array {
|
|
151
|
+
if (this.pos + length > this.bytes.length) throw new RangeError("the answer ends early");
|
|
152
|
+
const out = this.bytes.subarray(this.pos, this.pos + length);
|
|
153
|
+
this.pos += length;
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
/** A name, following compression pointers (at most 64 of them, so a loop ends). */
|
|
157
|
+
name(): string {
|
|
158
|
+
const labels: string[] = [];
|
|
159
|
+
let at = this.pos;
|
|
160
|
+
let jumped = false;
|
|
161
|
+
for (let hops = 0; hops < 64;) {
|
|
162
|
+
const len = this.byte(at);
|
|
163
|
+
if (len === 0) {
|
|
164
|
+
if (!jumped) this.pos = at + 1;
|
|
165
|
+
return labels.join(".");
|
|
166
|
+
}
|
|
167
|
+
if ((len & 0xc0) === 0xc0) {
|
|
168
|
+
const target = ((len & 0x3f) << 8) | this.byte(at + 1);
|
|
169
|
+
if (!jumped) this.pos = at + 2;
|
|
170
|
+
jumped = true;
|
|
171
|
+
at = target;
|
|
172
|
+
hops++;
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if ((len & 0xc0) !== 0) throw new RangeError("a label type that is not known");
|
|
176
|
+
if (at + 1 + len > this.bytes.length) throw new RangeError("the answer ends early");
|
|
177
|
+
labels.push(new TextDecoder().decode(this.bytes.subarray(at + 1, at + 1 + len)));
|
|
178
|
+
at += 1 + len;
|
|
179
|
+
}
|
|
180
|
+
throw new RangeError("a loop of compressed names");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function ipv6(bytes: Uint8Array): string {
|
|
185
|
+
const groups: number[] = [];
|
|
186
|
+
for (let i = 0; i < 16; i += 2) groups.push(((bytes[i] ?? 0) << 8) | (bytes[i + 1] ?? 0));
|
|
187
|
+
// RFC 5952: the longest run of two or more zero groups (the first, on a tie) becomes `::`.
|
|
188
|
+
let best = -1;
|
|
189
|
+
let bestLen = 1;
|
|
190
|
+
for (let i = 0; i < 8;) {
|
|
191
|
+
let j = i;
|
|
192
|
+
while (j < 8 && groups[j] === 0) j++;
|
|
193
|
+
if (j - i > bestLen) {
|
|
194
|
+
best = i;
|
|
195
|
+
bestLen = j - i;
|
|
196
|
+
}
|
|
197
|
+
i = j === i ? i + 1 : j;
|
|
198
|
+
}
|
|
199
|
+
const hex = groups.map((g) => g.toString(16));
|
|
200
|
+
if (best < 0) return hex.join(":");
|
|
201
|
+
return `${hex.slice(0, best).join(":")}::${hex.slice(best + bestLen).join(":")}`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function characterStrings(data: Uint8Array): string[] {
|
|
205
|
+
const out: string[] = [];
|
|
206
|
+
for (let i = 0; i < data.length;) {
|
|
207
|
+
const len = data[i] ?? 0;
|
|
208
|
+
if (i + 1 + len > data.length) throw new RangeError("a TXT string ends early");
|
|
209
|
+
out.push(new TextDecoder().decode(data.subarray(i + 1, i + 1 + len)));
|
|
210
|
+
i += 1 + len;
|
|
211
|
+
}
|
|
212
|
+
return out;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
type Parse = { readonly [K in RecordType]: (m: Message, length: number) => RecordOf[K] };
|
|
216
|
+
|
|
217
|
+
const PARSE: Parse = {
|
|
218
|
+
A: (m, length) => {
|
|
219
|
+
if (length !== 4) throw new RangeError("an A record that is not 4 bytes");
|
|
220
|
+
return Array.from(m.slice(4)).join(".");
|
|
221
|
+
},
|
|
222
|
+
AAAA: (m, length) => {
|
|
223
|
+
if (length !== 16) throw new RangeError("an AAAA record that is not 16 bytes");
|
|
224
|
+
return ipv6(m.slice(16));
|
|
225
|
+
},
|
|
226
|
+
CNAME: (m) => m.name(),
|
|
227
|
+
NS: (m) => m.name(),
|
|
228
|
+
MX: (m) => ({ preference: m.u16(), exchange: m.name() }),
|
|
229
|
+
TXT: (m, length) => characterStrings(m.slice(length)),
|
|
230
|
+
SRV: (m) => ({ priority: m.u16(), weight: m.u16(), port: m.u16(), target: m.name() }),
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
type Answer<T extends RecordType> =
|
|
234
|
+
| { readonly kind: "records"; readonly records: RecordOf[T][] }
|
|
235
|
+
| { readonly kind: "nxdomain" }
|
|
236
|
+
| { readonly kind: "rcode"; readonly rcode: number }
|
|
237
|
+
| { readonly kind: "truncated" }
|
|
238
|
+
| { readonly kind: "not-ours" };
|
|
239
|
+
|
|
240
|
+
function parseAnswer<T extends RecordType>(bytes: Uint8Array, id: number, qname: string, type: T): Answer<T> {
|
|
241
|
+
const m = new Message(bytes);
|
|
242
|
+
if (m.u16() !== id) return { kind: "not-ours" };
|
|
243
|
+
const flags = m.u16();
|
|
244
|
+
if ((flags & 0x8000) === 0) return { kind: "not-ours" };
|
|
245
|
+
const qd = m.u16();
|
|
246
|
+
const an = m.u16();
|
|
247
|
+
m.u16();
|
|
248
|
+
m.u16();
|
|
249
|
+
for (let i = 0; i < qd; i++) {
|
|
250
|
+
const name = m.name();
|
|
251
|
+
const qtype = m.u16();
|
|
252
|
+
m.u16();
|
|
253
|
+
if (name.toLowerCase() !== qname.toLowerCase() || qtype !== TYPE_CODE[type]) return { kind: "not-ours" };
|
|
254
|
+
}
|
|
255
|
+
if ((flags & 0x0200) !== 0) return { kind: "truncated" };
|
|
256
|
+
const rcode = flags & 0x0f;
|
|
257
|
+
if (rcode === 3) return { kind: "nxdomain" };
|
|
258
|
+
if (rcode !== 0) return { kind: "rcode", rcode };
|
|
259
|
+
const parse: (m: Message, length: number) => RecordOf[T] = PARSE[type];
|
|
260
|
+
const records: RecordOf[T][] = [];
|
|
261
|
+
for (let i = 0; i < an; i++) {
|
|
262
|
+
m.name();
|
|
263
|
+
const rtype = m.u16();
|
|
264
|
+
const rclass = m.u16();
|
|
265
|
+
m.u32();
|
|
266
|
+
const length = m.u16();
|
|
267
|
+
const end = m.pos + length;
|
|
268
|
+
if (end > bytes.length) throw new RangeError("the answer ends early");
|
|
269
|
+
if (rtype === TYPE_CODE[type] && rclass === CLASS_IN) records.push(parse(m, length));
|
|
270
|
+
m.pos = end;
|
|
271
|
+
}
|
|
272
|
+
return { kind: "records", records };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
type Server = { readonly host: string; readonly port: number };
|
|
276
|
+
|
|
277
|
+
function systemServers(): Server[] {
|
|
278
|
+
const seen = new Set<string>();
|
|
279
|
+
const out: Server[] = [];
|
|
280
|
+
for (const s of getServers()) {
|
|
281
|
+
let server: Server;
|
|
282
|
+
const v6 = /^\[(.+)\]:(\d+)$/.exec(s);
|
|
283
|
+
const v4 = /^([\d.]+):(\d+)$/.exec(s);
|
|
284
|
+
if (v6?.[1] !== undefined && v6[2] !== undefined) server = { host: v6[1], port: Number(v6[2]) };
|
|
285
|
+
else if (v4?.[1] !== undefined && v4[2] !== undefined) server = { host: v4[1], port: Number(v4[2]) };
|
|
286
|
+
else server = { host: s, port: 53 };
|
|
287
|
+
const key = `${server.host} ${server.port}`;
|
|
288
|
+
if (seen.has(key) || net.isIP(server.host) === 0) continue;
|
|
289
|
+
seen.add(key);
|
|
290
|
+
out.push(server);
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function randomId(): number {
|
|
296
|
+
const b = new Uint16Array(1);
|
|
297
|
+
crypto.getRandomValues(b);
|
|
298
|
+
return b[0] ?? 0;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** Wait for `start` to settle, or for the try's time, or for the signal; `cleanup` runs once whatever happens. */
|
|
302
|
+
function attempt<A>(signal: AbortSignal | undefined, start: (settle: (a: A) => void, fail: (e: Error) => void) => () => void): Promise<A> {
|
|
303
|
+
return new Promise<A>((resolve, reject) => {
|
|
304
|
+
let cleanup = (): void => undefined;
|
|
305
|
+
let done = false;
|
|
306
|
+
const finish = (f: () => void): void => {
|
|
307
|
+
if (done) return;
|
|
308
|
+
done = true;
|
|
309
|
+
clearTimeout(timer);
|
|
310
|
+
signal?.removeEventListener("abort", onAbort);
|
|
311
|
+
cleanup();
|
|
312
|
+
f();
|
|
313
|
+
};
|
|
314
|
+
const onAbort = (): void => finish(() => reject(new Stop("ECANCELLED", "the query was aborted")));
|
|
315
|
+
const timer = setTimeout(
|
|
316
|
+
() => finish(() => reject(Object.assign(new Error("the server did not answer in time"), { code: "ETIMEOUT" }))),
|
|
317
|
+
TRY_MS,
|
|
318
|
+
);
|
|
319
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
320
|
+
cleanup = start(
|
|
321
|
+
(a) => finish(() => resolve(a)),
|
|
322
|
+
(e) => finish(() => reject(e)),
|
|
323
|
+
);
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function askUdp<T extends RecordType>(server: Server, qname: string, type: T, signal: AbortSignal | undefined): Promise<Answer<T>> {
|
|
328
|
+
const id = randomId();
|
|
329
|
+
const encoded = encodeName(qname) ?? [0];
|
|
330
|
+
return attempt(signal, (settle, fail) => {
|
|
331
|
+
const socket = dgram.createSocket(net.isIPv6(server.host) ? "udp6" : "udp4");
|
|
332
|
+
socket.on("error", fail);
|
|
333
|
+
socket.on("message", (msg: Uint8Array, from) => {
|
|
334
|
+
if (from.port !== server.port) return;
|
|
335
|
+
try {
|
|
336
|
+
const answer = parseAnswer(msg, id, qname, type);
|
|
337
|
+
if (answer.kind !== "not-ours") settle(answer);
|
|
338
|
+
} catch (e) {
|
|
339
|
+
fail(Object.assign(new Error(`the answer cannot be read: ${e instanceof Error ? e.message : String(e)}`), { code: "EBADRESP" }));
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
socket.send(query(id, encoded, TYPE_CODE[type]), server.port, server.host);
|
|
343
|
+
return () => socket.close();
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function askTcp<T extends RecordType>(server: Server, qname: string, type: T, signal: AbortSignal | undefined): Promise<Answer<T>> {
|
|
348
|
+
const id = randomId();
|
|
349
|
+
const q = query(id, encodeName(qname) ?? [0], TYPE_CODE[type]);
|
|
350
|
+
return attempt(signal, (settle, fail) => {
|
|
351
|
+
const socket = net.connect({ host: server.host, port: server.port });
|
|
352
|
+
let buffered = new Uint8Array(0);
|
|
353
|
+
socket.on("error", fail);
|
|
354
|
+
socket.on("connect", () => socket.write(Uint8Array.from([...u16(q.length), ...q])));
|
|
355
|
+
socket.on("data", (chunk: Uint8Array) => {
|
|
356
|
+
const next = new Uint8Array(buffered.length + chunk.length);
|
|
357
|
+
next.set(buffered);
|
|
358
|
+
next.set(chunk, buffered.length);
|
|
359
|
+
buffered = next;
|
|
360
|
+
if (buffered.length < 2) return;
|
|
361
|
+
const length = ((buffered[0] ?? 0) << 8) | (buffered[1] ?? 0);
|
|
362
|
+
if (buffered.length < 2 + length) return;
|
|
363
|
+
try {
|
|
364
|
+
const answer = parseAnswer(buffered.subarray(2, 2 + length), id, qname, type);
|
|
365
|
+
if (answer.kind === "not-ours" || answer.kind === "truncated")
|
|
366
|
+
fail(Object.assign(new Error("an answer that is not ours"), { code: "EBADRESP" }));
|
|
367
|
+
else settle(answer);
|
|
368
|
+
} catch (e) {
|
|
369
|
+
fail(Object.assign(new Error(`the answer cannot be read: ${e instanceof Error ? e.message : String(e)}`), { code: "EBADRESP" }));
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
return () => socket.destroy();
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function failure(name: string, e: unknown): Failed {
|
|
377
|
+
const code: unknown = typeof e === "object" && e !== null ? Reflect.get(e, "code") : undefined;
|
|
378
|
+
return { kind: "failed", name, code: typeof code === "string" ? code : "", message: e instanceof Error ? e.message : String(e) };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The records of a type for a name, or why there are none. */
|
|
382
|
+
export async function resolveDns<T extends RecordType>(
|
|
383
|
+
name: string,
|
|
384
|
+
type: T,
|
|
385
|
+
options: ResolveDnsOptions = {},
|
|
386
|
+
): Promise<Result<readonly RecordOf[T][], DnsError>> {
|
|
387
|
+
const { signal, nameServer } = options;
|
|
388
|
+
const qname = name.endsWith(".") ? name.slice(0, -1) : name;
|
|
389
|
+
if (signal?.aborted === true) return err({ kind: "failed", name, code: "ECANCELLED", message: "the query was aborted" });
|
|
390
|
+
if (encodeName(qname) === undefined) return err({ kind: "failed", name, code: "EBADNAME", message: `not a domain name: ${name}` });
|
|
391
|
+
const servers = nameServer === undefined ? systemServers() : [{ host: nameServer.ipAddr, port: nameServer.port ?? 53 }];
|
|
392
|
+
let last: Failed = { kind: "failed", name, code: "ENOSERVERS", message: "no DNS server is configured" };
|
|
393
|
+
for (const server of servers) {
|
|
394
|
+
for (let t = 0; t < TRIES; t++) {
|
|
395
|
+
try {
|
|
396
|
+
let answer = await askUdp(server, qname, type, signal);
|
|
397
|
+
if (answer.kind === "truncated") answer = await askTcp(server, qname, type, signal);
|
|
398
|
+
switch (answer.kind) {
|
|
399
|
+
case "records":
|
|
400
|
+
return answer.records.length === 0 ? err({ kind: "no-data", name, type }) : ok(answer.records);
|
|
401
|
+
case "nxdomain":
|
|
402
|
+
return err({ kind: "not-found", name });
|
|
403
|
+
case "rcode": {
|
|
404
|
+
const code = RCODE[answer.rcode] ?? `ERCODE${answer.rcode}`;
|
|
405
|
+
last = { kind: "failed", name, code, message: `the server at ${server.host} answered ${code}` };
|
|
406
|
+
t = TRIES; // the next server, not the same one again
|
|
407
|
+
break;
|
|
408
|
+
}
|
|
409
|
+
case "truncated":
|
|
410
|
+
case "not-ours":
|
|
411
|
+
last = { kind: "failed", name, code: "EBADRESP", message: "the server's answer could not be used" };
|
|
412
|
+
break;
|
|
413
|
+
default:
|
|
414
|
+
return absurd(answer);
|
|
415
|
+
}
|
|
416
|
+
} catch (e) {
|
|
417
|
+
if (e instanceof Stop) return err({ kind: "failed", name, code: e.code, message: e.message });
|
|
418
|
+
last = failure(name, e);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
return err(last);
|
|
423
|
+
}
|