@ai-ecoverse/slicc-kernel 1.188.1 → 1.189.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.
@@ -684,7 +684,10 @@ function remoteWorker(open, options = {}) {
684
684
  opened2 = await open(wire);
685
685
  } catch (err) {
686
686
  kernel.end();
687
- queueMicrotask(() => fail4(err instanceof Error ? err.message : String(err)));
687
+ const status = err?.exitStatus;
688
+ const message3 = err instanceof Error ? err.message : String(err);
689
+ if (typeof status === "number") refuse2(message3, status);
690
+ else queueMicrotask(() => fail4(message3));
688
691
  return;
689
692
  }
690
693
  if (ended) {
@@ -4818,7 +4821,7 @@ function satisfies(version, range2) {
4818
4821
  }
4819
4822
 
4820
4823
  // src/version.ts
4821
- var KERNEL_VERSION = true ? "1.188.1" : "0.0.0-dev";
4824
+ var KERNEL_VERSION = true ? "1.189.1" : "0.0.0-dev";
4822
4825
  var OS_RELEASE = "6.0.0-slicc";
4823
4826
  function procVersion() {
4824
4827
  return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC
@@ -12017,6 +12020,35 @@ function statOf2(attr2, path, mount) {
12017
12020
  } : {}
12018
12021
  };
12019
12022
  }
12023
+ var Gathered = class {
12024
+ bytes = new Uint8Array(0);
12025
+ owned = false;
12026
+ size;
12027
+ length = 0;
12028
+ constructor(size) {
12029
+ this.size = size;
12030
+ }
12031
+ add(chunk2) {
12032
+ const need2 = this.length + chunk2.length;
12033
+ if (this.length === 0) {
12034
+ this.bytes = chunk2;
12035
+ } else {
12036
+ if (!this.owned || this.bytes.length < need2) {
12037
+ const grown = new Uint8Array(
12038
+ Math.max(this.size, need2, this.owned ? this.bytes.length * 2 : 0)
12039
+ );
12040
+ grown.set(this.bytes.subarray(0, this.length));
12041
+ this.bytes = grown;
12042
+ this.owned = true;
12043
+ }
12044
+ this.bytes.set(chunk2, this.length);
12045
+ }
12046
+ this.length = need2;
12047
+ }
12048
+ get whole() {
12049
+ return this.length === this.bytes.length ? this.bytes : this.bytes.subarray(0, this.length);
12050
+ }
12051
+ };
12020
12052
  function concat4(chunks2, total) {
12021
12053
  if (chunks2.length === 1 && chunks2[0]?.length === total) return chunks2[0];
12022
12054
  const out = new Uint8Array(total);
@@ -12509,25 +12541,23 @@ var MountFs = class _MountFs {
12509
12541
  }
12510
12542
  const fh = await this.open(mount, rel2, false);
12511
12543
  const chunk2 = mount.caps.maxIo ?? DEFAULT_IO;
12512
- const chunks2 = [];
12513
- let total = 0;
12544
+ const out = new Gathered(attr2.size);
12514
12545
  try {
12515
12546
  for (; ; ) {
12516
12547
  const bytes = await mount.conn.call({
12517
12548
  op: "read",
12518
12549
  fh,
12519
- offset: total,
12550
+ offset: out.length,
12520
12551
  size: chunk2
12521
12552
  });
12522
12553
  if (bytes.length === 0) break;
12523
- chunks2.push(bytes);
12524
- total += bytes.length;
12525
- if (bytes.length < chunk2 && total >= attr2.size) break;
12554
+ out.add(bytes);
12555
+ if (bytes.length < chunk2 && out.length >= attr2.size) break;
12526
12556
  }
12527
12557
  } finally {
12528
12558
  await mount.conn.call({ op: "release", fh });
12529
12559
  }
12530
- return concat4(chunks2, total);
12560
+ return out.whole;
12531
12561
  }
12532
12562
  async writeFile(path, content, owner, redirects = 0) {
12533
12563
  const real2 = await this.follow(path, 0, true);
@@ -21064,6 +21094,462 @@ var HttpHandles = class {
21064
21094
  }
21065
21095
  };
21066
21096
 
21097
+ // src/kernel/net/dns-stub.ts
21098
+ var DNS_PORT = 53;
21099
+ var DNS_STUB_ADDRESS = "127.0.0.53";
21100
+ var RESOLV_CONF_PATH = "/etc/resolv.conf";
21101
+ var RESOLV_CONF = `nameserver ${DNS_STUB_ADDRESS}
21102
+ options edns0
21103
+ `;
21104
+ var DNS_STUB_TTL = 30;
21105
+ var DNS_FORWARD_TIMEOUT_MS = 5e3;
21106
+ var DNS_TCP_IDLE_MS = 1e4;
21107
+ var DNS_TCP_MAX = 64;
21108
+ var DNS_UDP_INFLIGHT = 64;
21109
+ var TYPE_A = 1;
21110
+ var TYPE_PTR = 12;
21111
+ var TYPE_AAAA = 28;
21112
+ var TYPE_OPT = 41;
21113
+ var CLASS_IN = 1;
21114
+ var NOERROR = 0;
21115
+ var FORMERR = 1;
21116
+ var SERVFAIL = 2;
21117
+ var NXDOMAIN = 3;
21118
+ var NOTIMP = 4;
21119
+ var QR = 32768;
21120
+ var AA = 1024;
21121
+ var TC = 512;
21122
+ var RD = 256;
21123
+ var RA = 128;
21124
+ var CD = 16;
21125
+ var UDP_PLAIN = 512;
21126
+ var UDP_EDNS = 1232;
21127
+ var UDP_MAX = 4096;
21128
+ var DOH_MAX = 65535;
21129
+ var LOCAL_ZONES = ["localhost", "slicc.internal"];
21130
+ var MESSAGE = "application/dns-message";
21131
+ var u16 = (b, at) => b[at] << 8 | b[at + 1];
21132
+ function skipName(b, at) {
21133
+ let i = at;
21134
+ for (let hops = 0; hops < 128; hops++) {
21135
+ if (i >= b.length) return void 0;
21136
+ const len = b[i];
21137
+ if (len === 0) return i + 1;
21138
+ if ((len & 192) === 192) return i + 2 <= b.length ? i + 2 : void 0;
21139
+ if (len & 192) return void 0;
21140
+ i += len + 1;
21141
+ }
21142
+ return void 0;
21143
+ }
21144
+ function readName(b, at) {
21145
+ const labels = [];
21146
+ let i = at;
21147
+ let size = 0;
21148
+ for (; ; ) {
21149
+ if (i >= b.length) return void 0;
21150
+ const len = b[i];
21151
+ if (len === 0) break;
21152
+ if (len & 192) return void 0;
21153
+ size += len + 1;
21154
+ if (size > 254 || i + 1 + len > b.length) return void 0;
21155
+ labels.push(new TextDecoder().decode(b.subarray(i + 1, i + 1 + len)));
21156
+ i += len + 1;
21157
+ }
21158
+ return { name: labels.join(".").toLowerCase(), end: i + 1 };
21159
+ }
21160
+ function parseQuery(b) {
21161
+ if (b.length < 12) return void 0;
21162
+ const id2 = u16(b, 0);
21163
+ const flags2 = u16(b, 2);
21164
+ if (flags2 & QR) return void 0;
21165
+ if (flags2 >> 11 & 15) return { ok: false, id: id2, flags: flags2, rcode: NOTIMP };
21166
+ if (u16(b, 4) !== 1) return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
21167
+ const read = readName(b, 12);
21168
+ if (!read || read.end + 4 > b.length) return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
21169
+ const type = u16(b, read.end);
21170
+ const klass = u16(b, read.end + 2);
21171
+ const end = read.end + 4;
21172
+ let edns;
21173
+ let at = end;
21174
+ const records = u16(b, 6) + u16(b, 8) + u16(b, 10);
21175
+ for (let n = 0; n < records; n++) {
21176
+ const after = skipName(b, at);
21177
+ if (after === void 0 || after + 10 > b.length)
21178
+ return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
21179
+ if (u16(b, after) === TYPE_OPT) edns = Math.max(UDP_PLAIN, u16(b, after + 2));
21180
+ at = after + 10 + u16(b, after + 8);
21181
+ if (at > b.length) return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
21182
+ }
21183
+ return { ok: true, question: { id: id2, flags: flags2, name: read.name, type, klass, end, edns } };
21184
+ }
21185
+ function encodeName(name2) {
21186
+ const out = [];
21187
+ for (const label of name2.split(".").filter(Boolean)) {
21188
+ const bytes = new TextEncoder().encode(label);
21189
+ out.push(bytes.length, ...bytes);
21190
+ }
21191
+ out.push(0);
21192
+ return out;
21193
+ }
21194
+ function header2(id2, flags2, counts) {
21195
+ const out = [id2 >> 8, id2 & 255, flags2 >> 8, flags2 & 255];
21196
+ for (const c of counts) out.push(c >> 8, c & 255);
21197
+ return out;
21198
+ }
21199
+ function opt() {
21200
+ return [0, 0, TYPE_OPT, UDP_EDNS >> 8, UDP_EDNS & 255, 0, 0, 0, 0, 0, 0];
21201
+ }
21202
+ function record2(type, rdata) {
21203
+ const ttl = DNS_STUB_TTL;
21204
+ return [
21205
+ 192,
21206
+ 12,
21207
+ type >> 8,
21208
+ type & 255,
21209
+ 0,
21210
+ CLASS_IN,
21211
+ ttl >>> 24 & 255,
21212
+ ttl >>> 16 & 255,
21213
+ ttl >>> 8 & 255,
21214
+ ttl & 255,
21215
+ rdata.length >> 8,
21216
+ rdata.length & 255,
21217
+ ...rdata
21218
+ ];
21219
+ }
21220
+ function replyFlags(query, rcode, aa) {
21221
+ return QR | query & 30720 | (aa ? AA : 0) | query & RD | RA | query & CD | rcode;
21222
+ }
21223
+ function answers(reply, q) {
21224
+ if (reply.length < 12 || !(u16(reply, 2) & QR) || u16(reply, 4) !== 1) return false;
21225
+ const read = readName(reply, 12);
21226
+ if (!read || read.end + 4 > reply.length) return false;
21227
+ return read.name === q.name && u16(reply, read.end) === q.type && u16(reply, read.end + 2) === q.klass;
21228
+ }
21229
+ function errorReply2(id2, flags2, rcode) {
21230
+ return new Uint8Array(header2(id2, replyFlags(flags2, rcode, false), [0, 0, 0, 0]));
21231
+ }
21232
+ function answerReply(query, q, rcode, answers2, aa) {
21233
+ const extra = q.edns !== void 0 ? [opt()] : [];
21234
+ return new Uint8Array([
21235
+ ...header2(q.id, replyFlags(q.flags, rcode, aa), [1, answers2.length, 0, extra.length]),
21236
+ ...query.subarray(12, q.end),
21237
+ ...answers2.flat(),
21238
+ ...extra.flat()
21239
+ ]);
21240
+ }
21241
+ function truncated(reply, q, query) {
21242
+ const limit = q.edns !== void 0 ? Math.min(q.edns, UDP_MAX) : UDP_PLAIN;
21243
+ if (reply.length <= limit) return reply;
21244
+ const flags2 = u16(reply, 2) | TC;
21245
+ const extra = q.edns !== void 0 ? [opt()] : [];
21246
+ return new Uint8Array([
21247
+ ...header2(q.id, flags2, [1, 0, 0, extra.length]),
21248
+ ...query.subarray(12, q.end),
21249
+ ...extra.flat()
21250
+ ]);
21251
+ }
21252
+ function ipv6Text(groups) {
21253
+ return groups.map((g) => g.toString(16)).join(":");
21254
+ }
21255
+ function reverseAddress(name2) {
21256
+ if (name2.endsWith(".in-addr.arpa")) {
21257
+ const parts2 = name2.slice(0, -".in-addr.arpa".length).split(".");
21258
+ if (parts2.length !== 4) return void 0;
21259
+ const text = parts2.reverse().join(".");
21260
+ return ipv4Bytes(text) ? text.split(".").map(Number).join(".") : void 0;
21261
+ }
21262
+ if (name2.endsWith(".ip6.arpa")) {
21263
+ const nibbles = name2.slice(0, -".ip6.arpa".length).split(".");
21264
+ if (nibbles.length !== 32 || !nibbles.every((n) => /^[0-9a-f]$/.test(n))) return void 0;
21265
+ const hex5 = nibbles.reverse().join("");
21266
+ const groups = Array.from(
21267
+ { length: 8 },
21268
+ (_, i) => Number.parseInt(hex5.slice(i * 4, i * 4 + 4), 16)
21269
+ );
21270
+ return ipv6Text(groups);
21271
+ }
21272
+ return void 0;
21273
+ }
21274
+ function local(name2) {
21275
+ return LOCAL_ZONES.some((zone) => name2 === zone || name2.endsWith(`.${zone}`));
21276
+ }
21277
+ function literal2(name2) {
21278
+ return ipv4Bytes(name2) !== void 0 || ipv6Groups(name2) !== void 0;
21279
+ }
21280
+ function addressData(address2, type) {
21281
+ if (type === TYPE_A) return ipv4Bytes(address2);
21282
+ const groups = type === TYPE_AAAA ? ipv6Groups(address2) : void 0;
21283
+ return groups?.flatMap((g) => [g >> 8, g & 255]);
21284
+ }
21285
+ var DnsStub = class {
21286
+ resolver;
21287
+ forwarder;
21288
+ timeoutMs;
21289
+ constructor(options) {
21290
+ this.resolver = options.resolver;
21291
+ this.forwarder = options.forward;
21292
+ this.timeoutMs = options.timeoutMs ?? DNS_FORWARD_TIMEOUT_MS;
21293
+ }
21294
+ async answer(query, udp) {
21295
+ const parsed3 = parseQuery(query);
21296
+ if (!parsed3) return void 0;
21297
+ if (!parsed3.ok) return errorReply2(parsed3.id, parsed3.flags, parsed3.rcode);
21298
+ const q = parsed3.question;
21299
+ const reply = await this.reply(query, q).catch(
21300
+ () => answerReply(query, q, SERVFAIL, [], false)
21301
+ );
21302
+ return udp ? truncated(reply, q, query) : reply;
21303
+ }
21304
+ async reply(query, q) {
21305
+ if (q.klass !== CLASS_IN || literal2(q.name)) return this.forward(query, q);
21306
+ if (q.type === TYPE_PTR) {
21307
+ const address2 = reverseAddress(q.name);
21308
+ const name2 = address2 !== void 0 ? await this.reverse(address2) : void 0;
21309
+ if (name2 !== void 0)
21310
+ return answerReply(query, q, NOERROR, [record2(TYPE_PTR, encodeName(name2))], true);
21311
+ return this.forward(query, q);
21312
+ }
21313
+ if (q.type === TYPE_A || q.type === TYPE_AAAA) {
21314
+ const addresses = q.name === "" ? [] : await this.lookup(q.name);
21315
+ const answers2 = addresses.flatMap((a) => {
21316
+ const data = addressData(a, q.type);
21317
+ return data ? [record2(q.type, data)] : [];
21318
+ });
21319
+ if (answers2.length > 0 || local(q.name) || await this.known(q.name)) {
21320
+ const rcode = addresses.length > 0 ? NOERROR : NXDOMAIN;
21321
+ return answerReply(query, q, rcode, answers2, local(q.name));
21322
+ }
21323
+ return this.forward(query, q);
21324
+ }
21325
+ if (await this.known(q.name)) return answerReply(query, q, NOERROR, [], true);
21326
+ if (local(q.name)) {
21327
+ const there = (await this.lookup(q.name)).length > 0;
21328
+ return answerReply(query, q, there ? NOERROR : NXDOMAIN, [], true);
21329
+ }
21330
+ return this.forward(query, q);
21331
+ }
21332
+ lookup(name2) {
21333
+ return this.resolver.resolve(name2, 0, void 0, false).catch(() => []);
21334
+ }
21335
+ known(name2) {
21336
+ return this.resolver.known(name2).catch(() => false);
21337
+ }
21338
+ reverse(address2) {
21339
+ return this.resolver.reverse(address2).catch(() => void 0);
21340
+ }
21341
+ async forward(query, q) {
21342
+ if (!this.forwarder) return answerReply(query, q, SERVFAIL, [], false);
21343
+ const asked = query.slice();
21344
+ asked[0] = 0;
21345
+ asked[1] = 0;
21346
+ const got = await this.forwarder(asked, AbortSignal.timeout(this.timeoutMs)).catch(
21347
+ () => void 0
21348
+ );
21349
+ if (!got || !answers(got, q)) return answerReply(query, q, SERVFAIL, [], false);
21350
+ const reply = got.slice();
21351
+ reply[0] = q.id >> 8;
21352
+ reply[1] = q.id & 255;
21353
+ return reply;
21354
+ }
21355
+ };
21356
+ async function collect(body, max) {
21357
+ const parts2 = [];
21358
+ let size = 0;
21359
+ for await (const part of body) {
21360
+ size += part.length;
21361
+ if (size > max) return void 0;
21362
+ parts2.push(part);
21363
+ }
21364
+ const out = new Uint8Array(size);
21365
+ let at = 0;
21366
+ for (const part of parts2) {
21367
+ out.set(part, at);
21368
+ at += part.length;
21369
+ }
21370
+ return out;
21371
+ }
21372
+ function dohForward(transport, url) {
21373
+ return async (query, signal) => {
21374
+ const res = await transport.fetch({
21375
+ url,
21376
+ method: "POST",
21377
+ headers: [
21378
+ ["content-type", MESSAGE],
21379
+ ["accept", MESSAGE]
21380
+ ],
21381
+ body: query,
21382
+ signal
21383
+ });
21384
+ const type = res.headers.find(([k]) => k.toLowerCase() === "content-type")?.[1] ?? "";
21385
+ if (res.status !== 200 || type.split(";")[0].trim().toLowerCase() !== MESSAGE) {
21386
+ await res.cancel().catch(() => void 0);
21387
+ return void 0;
21388
+ }
21389
+ return collect(res.body, DOH_MAX);
21390
+ };
21391
+ }
21392
+ async function writeAll3(conn, bytes) {
21393
+ for (let at = 0; at < bytes.length; ) {
21394
+ const n = await conn.write(bytes.subarray(at));
21395
+ if (!(n > 0)) throw new Error("the uplink wrote nothing");
21396
+ at += n;
21397
+ }
21398
+ }
21399
+ function uplinkForward(uplink, server) {
21400
+ return async (query, signal) => {
21401
+ const conn = await uplink.dial({ network: "tcp", host: server, port: DNS_PORT, signal });
21402
+ const stop = () => conn.close();
21403
+ signal.addEventListener("abort", stop, { once: true });
21404
+ try {
21405
+ await writeAll3(conn, new Uint8Array([query.length >> 8, query.length & 255, ...query]));
21406
+ let got = new Uint8Array();
21407
+ for (; ; ) {
21408
+ if (got.length >= 2 && got.length >= 2 + u16(got, 0)) return got.slice(2, 2 + u16(got, 0));
21409
+ const piece = await conn.read();
21410
+ if (!piece) return void 0;
21411
+ const next3 = new Uint8Array(got.length + piece.length);
21412
+ next3.set(got);
21413
+ next3.set(piece, got.length);
21414
+ got = next3;
21415
+ }
21416
+ } finally {
21417
+ signal.removeEventListener("abort", stop);
21418
+ conn.close();
21419
+ }
21420
+ };
21421
+ }
21422
+ var u32 = (b, at) => u16(b, at) * 65536 + u16(b, at + 2);
21423
+ function addressText(type, rdata) {
21424
+ if (type === TYPE_A && rdata.length === 4) return rdata.join(".");
21425
+ if (type !== TYPE_AAAA || rdata.length !== 16) return void 0;
21426
+ return ipv6Text(Array.from({ length: 8 }, (_, i) => u16(rdata, i * 2)));
21427
+ }
21428
+ function addressesOf(reply, type) {
21429
+ if (reply.length < 12 || !(u16(reply, 2) & QR)) return void 0;
21430
+ const rcode = u16(reply, 2) & 15;
21431
+ if (rcode === NXDOMAIN) return { addresses: [] };
21432
+ if (rcode !== NOERROR) return void 0;
21433
+ let at = 12;
21434
+ for (let n = u16(reply, 4); n > 0; n--) {
21435
+ const after = skipName(reply, at);
21436
+ if (after === void 0) return void 0;
21437
+ at = after + 4;
21438
+ }
21439
+ const addresses = [];
21440
+ let ttl;
21441
+ for (let n = u16(reply, 6); n > 0; n--) {
21442
+ const after = skipName(reply, at);
21443
+ if (after === void 0 || after + 10 > reply.length) return void 0;
21444
+ const end = after + 10 + u16(reply, after + 8);
21445
+ if (end > reply.length) return void 0;
21446
+ const text = u16(reply, after) === type && u16(reply, after + 2) === CLASS_IN ? addressText(type, reply.subarray(after + 10, end)) : void 0;
21447
+ if (text !== void 0) {
21448
+ addresses.push(text);
21449
+ ttl = Math.min(ttl ?? Number.POSITIVE_INFINITY, u32(reply, after + 4));
21450
+ }
21451
+ at = end;
21452
+ }
21453
+ return { addresses, ...ttl !== void 0 ? { ttl } : {} };
21454
+ }
21455
+ function addressQuery(name2, type) {
21456
+ return new Uint8Array([
21457
+ ...header2(0, RD, [1, 0, 0, 0]),
21458
+ ...encodeName(name2),
21459
+ type >> 8,
21460
+ type & 255,
21461
+ 0,
21462
+ CLASS_IN
21463
+ ]);
21464
+ }
21465
+ async function forwardedLookup(forward, name2, family, signal) {
21466
+ const types = family === 4 ? [TYPE_A] : family === 6 ? [TYPE_AAAA] : [TYPE_A, TYPE_AAAA];
21467
+ const answers2 = await Promise.all(
21468
+ types.map(async (type) => {
21469
+ const reply = await forward(addressQuery(name2, type), signal);
21470
+ const answer2 = reply ? addressesOf(reply, type) : void 0;
21471
+ if (!answer2) throw new Error(`the DNS forwarder gave no answer for ${name2}`);
21472
+ return answer2;
21473
+ })
21474
+ );
21475
+ const ttls = answers2.flatMap((a) => a.ttl === void 0 ? [] : [a.ttl]);
21476
+ return {
21477
+ addresses: answers2.flatMap((a) => a.addresses),
21478
+ ...ttls.length > 0 ? { ttl: Math.min(...ttls) } : {}
21479
+ };
21480
+ }
21481
+ function dnsForward(uplink, transport, doh) {
21482
+ const server = uplink?.nameserver;
21483
+ if (uplink && server && (ipv4Bytes(server) || ipv6Groups(server)))
21484
+ return uplinkForward(uplink, server);
21485
+ return typeof doh === "string" ? dohForward(transport, doh) : void 0;
21486
+ }
21487
+ async function readExactly(conn, size, signal) {
21488
+ const out = new Uint8Array(size);
21489
+ let at = 0;
21490
+ while (at < size) {
21491
+ const piece = await conn.read(size - at, signal);
21492
+ if (piece.length === 0) return void 0;
21493
+ out.set(piece, at);
21494
+ at += piece.length;
21495
+ }
21496
+ return out;
21497
+ }
21498
+ async function serveTcp(stub, conn) {
21499
+ try {
21500
+ for (; ; ) {
21501
+ const idle2 = AbortSignal.timeout(DNS_TCP_IDLE_MS);
21502
+ const size = await readExactly(conn, 2, idle2);
21503
+ if (!size) return;
21504
+ const query = await readExactly(conn, u16(size, 0), idle2);
21505
+ if (!query) return;
21506
+ const reply = await stub.answer(query, false);
21507
+ if (!reply) return;
21508
+ const framed = new Uint8Array([reply.length >> 8, reply.length & 255, ...reply]);
21509
+ const sent = await conn.write(framed, AbortSignal.timeout(DNS_TCP_IDLE_MS));
21510
+ if (sent < framed.length) return;
21511
+ }
21512
+ } catch {
21513
+ return;
21514
+ } finally {
21515
+ conn.close();
21516
+ }
21517
+ }
21518
+ function enableDnsStub(net, stub) {
21519
+ const at = { family: "inet", host: "127.0.0.1", port: DNS_PORT };
21520
+ net.reserve(DNS_PORT);
21521
+ net.kernelOnly(DNS_PORT, true);
21522
+ net.activate(at, () => {
21523
+ const listener = net.listen(at);
21524
+ const open = /* @__PURE__ */ new Set();
21525
+ void (async () => {
21526
+ for (; ; ) {
21527
+ const conn = await listener.accept().catch(() => void 0);
21528
+ if (!conn) return;
21529
+ if (open.size >= DNS_TCP_MAX) {
21530
+ conn.close();
21531
+ continue;
21532
+ }
21533
+ open.add(conn);
21534
+ void serveTcp(stub, conn).finally(() => open.delete(conn));
21535
+ }
21536
+ })();
21537
+ });
21538
+ let inflight = 0;
21539
+ net.serveDgram(DNS_PORT, (datagram2, to) => {
21540
+ if (inflight >= DNS_UDP_INFLIGHT) return;
21541
+ inflight++;
21542
+ void stub.answer(datagram2.bytes, true).then(
21543
+ (reply) => {
21544
+ if (!reply) return;
21545
+ const from = { family: "inet", host: to.host, port: DNS_PORT };
21546
+ net.deliverDgram(datagram2.from.port, { bytes: reply, from });
21547
+ },
21548
+ () => void 0
21549
+ ).finally(() => inflight--);
21550
+ });
21551
+ }
21552
+
21067
21553
  // src/kernel/net/hosts-file.ts
21068
21554
  var HOSTS_PATH = "/etc/hosts";
21069
21555
  function parseHosts(text) {
@@ -21140,6 +21626,7 @@ var Resolver = class {
21140
21626
  cache = /* @__PURE__ */ new Map();
21141
21627
  pending = /* @__PURE__ */ new Map();
21142
21628
  hosts;
21629
+ forward;
21143
21630
  constructor(options) {
21144
21631
  this.uplink = options.uplink;
21145
21632
  this.routes = options.routes;
@@ -21149,6 +21636,7 @@ var Resolver = class {
21149
21636
  this.own = ownNames(options.hostname ?? DEFAULT_HOSTNAME);
21150
21637
  this.builtin = parseHosts(hostsFile(options.hostname ?? DEFAULT_HOSTNAME));
21151
21638
  this.hosts = options.hosts;
21639
+ this.forward = options.forward;
21152
21640
  }
21153
21641
  async fromFile(key, family) {
21154
21642
  const listed = (await this.hosts?.().catch(() => void 0))?.get(key);
@@ -21173,7 +21661,7 @@ var Resolver = class {
21173
21661
  if (ipv4Bytes(address2)?.[0] === 127) return "localhost";
21174
21662
  return void 0;
21175
21663
  }
21176
- async resolve(name2, family, blocking) {
21664
+ async resolve(name2, family, blocking, forwarded = true) {
21177
21665
  const key = name2.toLowerCase().replace(/\.$/, "");
21178
21666
  const local2 = hostsEntry(key, this.own);
21179
21667
  if (ipv6Groups(key)) {
@@ -21189,40 +21677,60 @@ var Resolver = class {
21189
21677
  if (!this.uplink || key === "") return [];
21190
21678
  const asked = this.uplink.traits.ipv6 ? family : 4;
21191
21679
  if (family === 6 && asked !== 6) return [];
21192
- const id2 = `${asked}:${key}`;
21680
+ return this.remote(key, asked, blocking, forwarded);
21681
+ }
21682
+ remote(key, asked, blocking, forwarded) {
21683
+ const id2 = `${forwarded && this.forward ? "forwarded" : "uplink"}:${asked}:${key}`;
21193
21684
  const hit = this.cache.get(id2);
21194
- if (hit && hit.expires > this.now()) return hit.addresses;
21685
+ if (hit && hit.expires > this.now()) return Promise.resolve(hit.addresses);
21195
21686
  const signal = blocking?.();
21196
- if (signal?.aborted) throw new KernelError("EINTR");
21687
+ if (signal?.aborted) return Promise.reject(new KernelError("EINTR"));
21197
21688
  let lookup2 = this.pending.get(id2);
21198
21689
  if (!lookup2) {
21199
21690
  const abort = new AbortController();
21200
- lookup2 = { work: this.lookup(key, asked, id2, abort.signal), abort, waiters: 0 };
21691
+ const work = this.lookup(key, asked, id2, abort.signal, forwarded);
21692
+ lookup2 = { work, abort, waiters: 0 };
21201
21693
  this.pending.set(id2, lookup2);
21202
21694
  const done4 = () => this.pending.delete(id2);
21203
21695
  void lookup2.work.then(done4, done4);
21204
21696
  }
21205
21697
  return waitFor(lookup2, signal);
21206
21698
  }
21207
- async lookup(name2, family, id2, abandoned) {
21208
- const uplink = this.uplink;
21699
+ async lookup(name2, family, id2, abandoned, forwarded) {
21209
21700
  const timeout = AbortSignal.any([AbortSignal.timeout(this.timeoutMs), abandoned]);
21210
- let answer2;
21701
+ const own = await this.ask(
21702
+ name2,
21703
+ `resolve ${name2}: the uplink gave no answer`,
21704
+ timeout,
21705
+ () => this.uplink?.resolve ? this.uplink.resolve(name2, family, timeout) : Promise.resolve([])
21706
+ );
21707
+ let answer2 = { ...own, addresses: own.addresses.filter((a) => this.usable(name2, a, family)) };
21708
+ const forward = this.forward;
21709
+ if (answer2.addresses.length === 0 && forwarded && forward && !local(name2)) {
21710
+ const found = await this.ask(
21711
+ name2,
21712
+ `resolve ${name2}: the DNS forwarder gave no answer`,
21713
+ timeout,
21714
+ () => forwardedLookup(forward, name2, family, timeout)
21715
+ );
21716
+ answer2 = { ...found, addresses: found.addresses.filter((a) => this.usable(name2, a, family)) };
21717
+ }
21718
+ if (answer2.addresses.length > 0) this.remember(id2, answer2.addresses, answer2.ttl);
21719
+ return answer2.addresses;
21720
+ }
21721
+ async ask(name2, failure, timeout, work) {
21211
21722
  try {
21212
- answer2 = answerOf2(
21723
+ return answerOf2(
21213
21724
  await Promise.race([
21214
- uplink.resolve(name2, family, timeout),
21725
+ work(),
21215
21726
  new Promise(
21216
21727
  (_, reject) => timeout.addEventListener("abort", () => reject(timeout.reason), { once: true })
21217
21728
  )
21218
21729
  ])
21219
21730
  );
21220
21731
  } catch {
21221
- throw new KernelError("ETIMEDOUT", `resolve ${name2}: the uplink gave no answer`);
21732
+ throw new KernelError("ETIMEDOUT", failure);
21222
21733
  }
21223
- const addresses = answer2.addresses.filter((a) => this.usable(name2, a, family));
21224
- if (addresses.length > 0) this.remember(id2, addresses, answer2.ttl);
21225
- return addresses;
21226
21734
  }
21227
21735
  usable(name2, address2, family) {
21228
21736
  const v4 = ipv4Bytes(address2) !== void 0;
@@ -22783,7 +23291,7 @@ function bytesOf2(text) {
22783
23291
  for (let i = 0; i < text.length; i++) out[i] = text.charCodeAt(i);
22784
23292
  return out;
22785
23293
  }
22786
- async function writeAll3(conn, bytes) {
23294
+ async function writeAll4(conn, bytes) {
22787
23295
  for (let at = 0; at < bytes.length; ) at += await conn.write(bytes.subarray(at));
22788
23296
  }
22789
23297
  var CRLF2 = [13, 10, 13, 10];
@@ -22933,7 +23441,7 @@ var SessionWriter = class {
22933
23441
  const line = bytesOf2(`${out.line}\r
22934
23442
  `);
22935
23443
  try {
22936
- await writeAll3(this.conn, line);
23444
+ await writeAll4(this.conn, line);
22937
23445
  } finally {
22938
23446
  line.fill(0);
22939
23447
  }
@@ -22956,7 +23464,7 @@ var SessionWriter = class {
22956
23464
  const out = started ? await this.pgClient.message(message3).catch(() => ({ bytes: message3, done: true })) : { bytes: message3, done: false };
22957
23465
  if ("values" in out && out.values) this.remember(out.values);
22958
23466
  try {
22959
- await writeAll3(this.conn, out.bytes);
23467
+ await writeAll4(this.conn, out.bytes);
22960
23468
  } finally {
22961
23469
  out.bytes.fill(0);
22962
23470
  message3.fill(0);
@@ -22974,7 +23482,7 @@ var SessionWriter = class {
22974
23482
  const out = this.buffer;
22975
23483
  this.buffer = new Uint8Array(0);
22976
23484
  try {
22977
- await writeAll3(this.conn, out);
23485
+ await writeAll4(this.conn, out);
22978
23486
  } finally {
22979
23487
  out.fill(0);
22980
23488
  }
@@ -22990,8 +23498,8 @@ var SessionWriter = class {
22990
23498
  const head = done4 ? bytesOf2(done4.head) : all.subarray(0, end);
22991
23499
  if (done4) this.remember(done4.values);
22992
23500
  try {
22993
- await writeAll3(this.conn, head);
22994
- await writeAll3(this.conn, all.subarray(end));
23501
+ await writeAll4(this.conn, head);
23502
+ await writeAll4(this.conn, all.subarray(end));
22995
23503
  } finally {
22996
23504
  head.fill(0);
22997
23505
  all.fill(0);
@@ -28863,406 +29371,6 @@ function isMessage(data) {
28863
29371
  return adopt !== null && Array.isArray(adopt.records) && Array.isArray(adopt.flocks);
28864
29372
  }
28865
29373
 
28866
- // src/kernel/net/dns-stub.ts
28867
- var DNS_PORT = 53;
28868
- var DNS_STUB_ADDRESS = "127.0.0.53";
28869
- var RESOLV_CONF_PATH = "/etc/resolv.conf";
28870
- var RESOLV_CONF = `nameserver ${DNS_STUB_ADDRESS}
28871
- options edns0
28872
- `;
28873
- var DNS_STUB_TTL = 30;
28874
- var DNS_FORWARD_TIMEOUT_MS = 5e3;
28875
- var DNS_TCP_IDLE_MS = 1e4;
28876
- var DNS_TCP_MAX = 64;
28877
- var DNS_UDP_INFLIGHT = 64;
28878
- var TYPE_A = 1;
28879
- var TYPE_PTR = 12;
28880
- var TYPE_AAAA = 28;
28881
- var TYPE_OPT = 41;
28882
- var CLASS_IN = 1;
28883
- var NOERROR = 0;
28884
- var FORMERR = 1;
28885
- var SERVFAIL = 2;
28886
- var NXDOMAIN = 3;
28887
- var NOTIMP = 4;
28888
- var QR = 32768;
28889
- var AA = 1024;
28890
- var TC = 512;
28891
- var RD = 256;
28892
- var RA = 128;
28893
- var CD = 16;
28894
- var UDP_PLAIN = 512;
28895
- var UDP_EDNS = 1232;
28896
- var UDP_MAX = 4096;
28897
- var DOH_MAX = 65535;
28898
- var LOCAL_ZONES = ["localhost", "slicc.internal"];
28899
- var MESSAGE = "application/dns-message";
28900
- var u16 = (b, at) => b[at] << 8 | b[at + 1];
28901
- function skipName(b, at) {
28902
- let i = at;
28903
- for (let hops = 0; hops < 128; hops++) {
28904
- if (i >= b.length) return void 0;
28905
- const len = b[i];
28906
- if (len === 0) return i + 1;
28907
- if ((len & 192) === 192) return i + 2 <= b.length ? i + 2 : void 0;
28908
- if (len & 192) return void 0;
28909
- i += len + 1;
28910
- }
28911
- return void 0;
28912
- }
28913
- function readName(b, at) {
28914
- const labels = [];
28915
- let i = at;
28916
- let size = 0;
28917
- for (; ; ) {
28918
- if (i >= b.length) return void 0;
28919
- const len = b[i];
28920
- if (len === 0) break;
28921
- if (len & 192) return void 0;
28922
- size += len + 1;
28923
- if (size > 254 || i + 1 + len > b.length) return void 0;
28924
- labels.push(new TextDecoder().decode(b.subarray(i + 1, i + 1 + len)));
28925
- i += len + 1;
28926
- }
28927
- return { name: labels.join(".").toLowerCase(), end: i + 1 };
28928
- }
28929
- function parseQuery(b) {
28930
- if (b.length < 12) return void 0;
28931
- const id2 = u16(b, 0);
28932
- const flags2 = u16(b, 2);
28933
- if (flags2 & QR) return void 0;
28934
- if (flags2 >> 11 & 15) return { ok: false, id: id2, flags: flags2, rcode: NOTIMP };
28935
- if (u16(b, 4) !== 1) return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
28936
- const read = readName(b, 12);
28937
- if (!read || read.end + 4 > b.length) return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
28938
- const type = u16(b, read.end);
28939
- const klass = u16(b, read.end + 2);
28940
- const end = read.end + 4;
28941
- let edns;
28942
- let at = end;
28943
- const records = u16(b, 6) + u16(b, 8) + u16(b, 10);
28944
- for (let n = 0; n < records; n++) {
28945
- const after = skipName(b, at);
28946
- if (after === void 0 || after + 10 > b.length)
28947
- return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
28948
- if (u16(b, after) === TYPE_OPT) edns = Math.max(UDP_PLAIN, u16(b, after + 2));
28949
- at = after + 10 + u16(b, after + 8);
28950
- if (at > b.length) return { ok: false, id: id2, flags: flags2, rcode: FORMERR };
28951
- }
28952
- return { ok: true, question: { id: id2, flags: flags2, name: read.name, type, klass, end, edns } };
28953
- }
28954
- function encodeName(name2) {
28955
- const out = [];
28956
- for (const label of name2.split(".").filter(Boolean)) {
28957
- const bytes = new TextEncoder().encode(label);
28958
- out.push(bytes.length, ...bytes);
28959
- }
28960
- out.push(0);
28961
- return out;
28962
- }
28963
- function header2(id2, flags2, counts) {
28964
- const out = [id2 >> 8, id2 & 255, flags2 >> 8, flags2 & 255];
28965
- for (const c of counts) out.push(c >> 8, c & 255);
28966
- return out;
28967
- }
28968
- function opt() {
28969
- return [0, 0, TYPE_OPT, UDP_EDNS >> 8, UDP_EDNS & 255, 0, 0, 0, 0, 0, 0];
28970
- }
28971
- function record2(type, rdata) {
28972
- const ttl = DNS_STUB_TTL;
28973
- return [
28974
- 192,
28975
- 12,
28976
- type >> 8,
28977
- type & 255,
28978
- 0,
28979
- CLASS_IN,
28980
- ttl >>> 24 & 255,
28981
- ttl >>> 16 & 255,
28982
- ttl >>> 8 & 255,
28983
- ttl & 255,
28984
- rdata.length >> 8,
28985
- rdata.length & 255,
28986
- ...rdata
28987
- ];
28988
- }
28989
- function replyFlags(query, rcode, aa) {
28990
- return QR | query & 30720 | (aa ? AA : 0) | query & RD | RA | query & CD | rcode;
28991
- }
28992
- function answers(reply, q) {
28993
- if (reply.length < 12 || !(u16(reply, 2) & QR) || u16(reply, 4) !== 1) return false;
28994
- const read = readName(reply, 12);
28995
- if (!read || read.end + 4 > reply.length) return false;
28996
- return read.name === q.name && u16(reply, read.end) === q.type && u16(reply, read.end + 2) === q.klass;
28997
- }
28998
- function errorReply2(id2, flags2, rcode) {
28999
- return new Uint8Array(header2(id2, replyFlags(flags2, rcode, false), [0, 0, 0, 0]));
29000
- }
29001
- function answerReply(query, q, rcode, answers2, aa) {
29002
- const extra = q.edns !== void 0 ? [opt()] : [];
29003
- return new Uint8Array([
29004
- ...header2(q.id, replyFlags(q.flags, rcode, aa), [1, answers2.length, 0, extra.length]),
29005
- ...query.subarray(12, q.end),
29006
- ...answers2.flat(),
29007
- ...extra.flat()
29008
- ]);
29009
- }
29010
- function truncated(reply, q, query) {
29011
- const limit = q.edns !== void 0 ? Math.min(q.edns, UDP_MAX) : UDP_PLAIN;
29012
- if (reply.length <= limit) return reply;
29013
- const flags2 = u16(reply, 2) | TC;
29014
- const extra = q.edns !== void 0 ? [opt()] : [];
29015
- return new Uint8Array([
29016
- ...header2(q.id, flags2, [1, 0, 0, extra.length]),
29017
- ...query.subarray(12, q.end),
29018
- ...extra.flat()
29019
- ]);
29020
- }
29021
- function ipv6Text(groups) {
29022
- return groups.map((g) => g.toString(16)).join(":");
29023
- }
29024
- function reverseAddress(name2) {
29025
- if (name2.endsWith(".in-addr.arpa")) {
29026
- const parts2 = name2.slice(0, -".in-addr.arpa".length).split(".");
29027
- if (parts2.length !== 4) return void 0;
29028
- const text = parts2.reverse().join(".");
29029
- return ipv4Bytes(text) ? text.split(".").map(Number).join(".") : void 0;
29030
- }
29031
- if (name2.endsWith(".ip6.arpa")) {
29032
- const nibbles = name2.slice(0, -".ip6.arpa".length).split(".");
29033
- if (nibbles.length !== 32 || !nibbles.every((n) => /^[0-9a-f]$/.test(n))) return void 0;
29034
- const hex5 = nibbles.reverse().join("");
29035
- const groups = Array.from(
29036
- { length: 8 },
29037
- (_, i) => Number.parseInt(hex5.slice(i * 4, i * 4 + 4), 16)
29038
- );
29039
- return ipv6Text(groups);
29040
- }
29041
- return void 0;
29042
- }
29043
- function local(name2) {
29044
- return LOCAL_ZONES.some((zone) => name2 === zone || name2.endsWith(`.${zone}`));
29045
- }
29046
- function literal2(name2) {
29047
- return ipv4Bytes(name2) !== void 0 || ipv6Groups(name2) !== void 0;
29048
- }
29049
- function addressData(address2, type) {
29050
- if (type === TYPE_A) return ipv4Bytes(address2);
29051
- const groups = type === TYPE_AAAA ? ipv6Groups(address2) : void 0;
29052
- return groups?.flatMap((g) => [g >> 8, g & 255]);
29053
- }
29054
- var DnsStub = class {
29055
- resolver;
29056
- forwarder;
29057
- timeoutMs;
29058
- constructor(options) {
29059
- this.resolver = options.resolver;
29060
- this.forwarder = options.forward;
29061
- this.timeoutMs = options.timeoutMs ?? DNS_FORWARD_TIMEOUT_MS;
29062
- }
29063
- async answer(query, udp) {
29064
- const parsed3 = parseQuery(query);
29065
- if (!parsed3) return void 0;
29066
- if (!parsed3.ok) return errorReply2(parsed3.id, parsed3.flags, parsed3.rcode);
29067
- const q = parsed3.question;
29068
- const reply = await this.reply(query, q).catch(
29069
- () => answerReply(query, q, SERVFAIL, [], false)
29070
- );
29071
- return udp ? truncated(reply, q, query) : reply;
29072
- }
29073
- async reply(query, q) {
29074
- if (q.klass !== CLASS_IN || literal2(q.name)) return this.forward(query, q);
29075
- if (q.type === TYPE_PTR) {
29076
- const address2 = reverseAddress(q.name);
29077
- const name2 = address2 !== void 0 ? await this.reverse(address2) : void 0;
29078
- if (name2 !== void 0)
29079
- return answerReply(query, q, NOERROR, [record2(TYPE_PTR, encodeName(name2))], true);
29080
- return this.forward(query, q);
29081
- }
29082
- if (q.type === TYPE_A || q.type === TYPE_AAAA) {
29083
- const addresses = q.name === "" ? [] : await this.lookup(q.name);
29084
- const answers2 = addresses.flatMap((a) => {
29085
- const data = addressData(a, q.type);
29086
- return data ? [record2(q.type, data)] : [];
29087
- });
29088
- if (answers2.length > 0 || local(q.name) || await this.known(q.name)) {
29089
- const rcode = addresses.length > 0 ? NOERROR : NXDOMAIN;
29090
- return answerReply(query, q, rcode, answers2, local(q.name));
29091
- }
29092
- return this.forward(query, q);
29093
- }
29094
- if (await this.known(q.name)) return answerReply(query, q, NOERROR, [], true);
29095
- if (local(q.name)) {
29096
- const there = (await this.lookup(q.name)).length > 0;
29097
- return answerReply(query, q, there ? NOERROR : NXDOMAIN, [], true);
29098
- }
29099
- return this.forward(query, q);
29100
- }
29101
- lookup(name2) {
29102
- return this.resolver.resolve(name2, 0).catch(() => []);
29103
- }
29104
- known(name2) {
29105
- return this.resolver.known(name2).catch(() => false);
29106
- }
29107
- reverse(address2) {
29108
- return this.resolver.reverse(address2).catch(() => void 0);
29109
- }
29110
- async forward(query, q) {
29111
- if (!this.forwarder) return answerReply(query, q, SERVFAIL, [], false);
29112
- const asked = query.slice();
29113
- asked[0] = 0;
29114
- asked[1] = 0;
29115
- const got = await this.forwarder(asked, AbortSignal.timeout(this.timeoutMs)).catch(
29116
- () => void 0
29117
- );
29118
- if (!got || !answers(got, q)) return answerReply(query, q, SERVFAIL, [], false);
29119
- const reply = got.slice();
29120
- reply[0] = q.id >> 8;
29121
- reply[1] = q.id & 255;
29122
- return reply;
29123
- }
29124
- };
29125
- async function collect(body, max) {
29126
- const parts2 = [];
29127
- let size = 0;
29128
- for await (const part of body) {
29129
- size += part.length;
29130
- if (size > max) return void 0;
29131
- parts2.push(part);
29132
- }
29133
- const out = new Uint8Array(size);
29134
- let at = 0;
29135
- for (const part of parts2) {
29136
- out.set(part, at);
29137
- at += part.length;
29138
- }
29139
- return out;
29140
- }
29141
- function dohForward(transport, url) {
29142
- return async (query, signal) => {
29143
- const res = await transport.fetch({
29144
- url,
29145
- method: "POST",
29146
- headers: [
29147
- ["content-type", MESSAGE],
29148
- ["accept", MESSAGE]
29149
- ],
29150
- body: query,
29151
- signal
29152
- });
29153
- const type = res.headers.find(([k]) => k.toLowerCase() === "content-type")?.[1] ?? "";
29154
- if (res.status !== 200 || type.split(";")[0].trim().toLowerCase() !== MESSAGE) {
29155
- await res.cancel().catch(() => void 0);
29156
- return void 0;
29157
- }
29158
- return collect(res.body, DOH_MAX);
29159
- };
29160
- }
29161
- async function writeAll4(conn, bytes) {
29162
- for (let at = 0; at < bytes.length; ) {
29163
- const n = await conn.write(bytes.subarray(at));
29164
- if (!(n > 0)) throw new Error("the uplink wrote nothing");
29165
- at += n;
29166
- }
29167
- }
29168
- function uplinkForward(uplink, server) {
29169
- return async (query, signal) => {
29170
- const conn = await uplink.dial({ network: "tcp", host: server, port: DNS_PORT, signal });
29171
- const stop = () => conn.close();
29172
- signal.addEventListener("abort", stop, { once: true });
29173
- try {
29174
- await writeAll4(conn, new Uint8Array([query.length >> 8, query.length & 255, ...query]));
29175
- let got = new Uint8Array();
29176
- for (; ; ) {
29177
- if (got.length >= 2 && got.length >= 2 + u16(got, 0)) return got.slice(2, 2 + u16(got, 0));
29178
- const piece = await conn.read();
29179
- if (!piece) return void 0;
29180
- const next3 = new Uint8Array(got.length + piece.length);
29181
- next3.set(got);
29182
- next3.set(piece, got.length);
29183
- got = next3;
29184
- }
29185
- } finally {
29186
- signal.removeEventListener("abort", stop);
29187
- conn.close();
29188
- }
29189
- };
29190
- }
29191
- function dnsForward(uplink, transport, doh) {
29192
- const server = uplink?.nameserver;
29193
- if (uplink && server && (ipv4Bytes(server) || ipv6Groups(server)))
29194
- return uplinkForward(uplink, server);
29195
- return typeof doh === "string" ? dohForward(transport, doh) : void 0;
29196
- }
29197
- function kernelDnsStub(resolver, transport, uplink, doh) {
29198
- return new DnsStub({ resolver, forward: dnsForward(uplink, transport, doh) });
29199
- }
29200
- async function readExactly(conn, size, signal) {
29201
- const out = new Uint8Array(size);
29202
- let at = 0;
29203
- while (at < size) {
29204
- const piece = await conn.read(size - at, signal);
29205
- if (piece.length === 0) return void 0;
29206
- out.set(piece, at);
29207
- at += piece.length;
29208
- }
29209
- return out;
29210
- }
29211
- async function serveTcp(stub, conn) {
29212
- try {
29213
- for (; ; ) {
29214
- const idle2 = AbortSignal.timeout(DNS_TCP_IDLE_MS);
29215
- const size = await readExactly(conn, 2, idle2);
29216
- if (!size) return;
29217
- const query = await readExactly(conn, u16(size, 0), idle2);
29218
- if (!query) return;
29219
- const reply = await stub.answer(query, false);
29220
- if (!reply) return;
29221
- const framed = new Uint8Array([reply.length >> 8, reply.length & 255, ...reply]);
29222
- const sent = await conn.write(framed, AbortSignal.timeout(DNS_TCP_IDLE_MS));
29223
- if (sent < framed.length) return;
29224
- }
29225
- } catch {
29226
- return;
29227
- } finally {
29228
- conn.close();
29229
- }
29230
- }
29231
- function enableDnsStub(net, stub) {
29232
- const at = { family: "inet", host: "127.0.0.1", port: DNS_PORT };
29233
- net.reserve(DNS_PORT);
29234
- net.kernelOnly(DNS_PORT, true);
29235
- net.activate(at, () => {
29236
- const listener = net.listen(at);
29237
- const open = /* @__PURE__ */ new Set();
29238
- void (async () => {
29239
- for (; ; ) {
29240
- const conn = await listener.accept().catch(() => void 0);
29241
- if (!conn) return;
29242
- if (open.size >= DNS_TCP_MAX) {
29243
- conn.close();
29244
- continue;
29245
- }
29246
- open.add(conn);
29247
- void serveTcp(stub, conn).finally(() => open.delete(conn));
29248
- }
29249
- })();
29250
- });
29251
- let inflight = 0;
29252
- net.serveDgram(DNS_PORT, (datagram2, to) => {
29253
- if (inflight >= DNS_UDP_INFLIGHT) return;
29254
- inflight++;
29255
- void stub.answer(datagram2.bytes, true).then(
29256
- (reply) => {
29257
- if (!reply) return;
29258
- const from = { family: "inet", host: to.host, port: DNS_PORT };
29259
- net.deliverDgram(datagram2.from.port, { bytes: reply, from });
29260
- },
29261
- () => void 0
29262
- ).finally(() => inflight--);
29263
- });
29264
- }
29265
-
29266
29374
  // src/kernel/net/remote-transport.ts
29267
29375
  var TransportError = class extends Error {
29268
29376
  status;
@@ -33992,7 +34100,7 @@ function tmpfs() {
33992
34100
  // src/process/wasi/wasi-module.ts
33993
34101
  function importedMemory(bytes) {
33994
34102
  let at = 8;
33995
- const u32 = () => {
34103
+ const u322 = () => {
33996
34104
  let result = 0;
33997
34105
  let shift = 0;
33998
34106
  for (; ; ) {
@@ -34003,31 +34111,31 @@ function importedMemory(bytes) {
34003
34111
  }
34004
34112
  };
34005
34113
  const name2 = () => {
34006
- const len = u32();
34114
+ const len = u322();
34007
34115
  const s = new TextDecoder().decode(bytes.subarray(at, at + len));
34008
34116
  at += len;
34009
34117
  return s;
34010
34118
  };
34011
34119
  const limits2 = () => {
34012
34120
  const flags2 = bytes[at++];
34013
- const initial3 = u32();
34014
- const maximum = flags2 & 1 ? u32() : void 0;
34121
+ const initial3 = u322();
34122
+ const maximum = flags2 & 1 ? u322() : void 0;
34015
34123
  return { initial: initial3, maximum, shared: (flags2 & 2) !== 0 };
34016
34124
  };
34017
34125
  while (at < bytes.length) {
34018
34126
  const id2 = bytes[at++];
34019
- const size = u32();
34127
+ const size = u322();
34020
34128
  const end = at + size;
34021
34129
  if (id2 !== 2) {
34022
34130
  at = end;
34023
34131
  continue;
34024
34132
  }
34025
- const count2 = u32();
34133
+ const count2 = u322();
34026
34134
  for (let i = 0; i < count2; i++) {
34027
34135
  const module = name2();
34028
34136
  const field4 = name2();
34029
34137
  const kind = bytes[at++];
34030
- if (kind === 0) u32();
34138
+ if (kind === 0) u322();
34031
34139
  else if (kind === 1) {
34032
34140
  at++;
34033
34141
  limits2();
@@ -34037,7 +34145,7 @@ function importedMemory(bytes) {
34037
34145
  } else if (kind === 3) at += 2;
34038
34146
  else if (kind === 4) {
34039
34147
  at++;
34040
- u32();
34148
+ u322();
34041
34149
  }
34042
34150
  }
34043
34151
  return void 0;
@@ -34975,8 +35083,10 @@ var Launcher = class {
34975
35083
  this.uplink = options.uplink;
34976
35084
  this.routes = new Routes(options.uplink?.traits.ipv6 === true);
34977
35085
  if (options.uplink?.routes) this.routes.set(options.uplink.routes);
35086
+ const forward = dnsForward(options.uplink, this.transport, options.doh);
34978
35087
  this.resolver = new Resolver({
34979
35088
  uplink: options.uplink,
35089
+ forward,
34980
35090
  routes: this.routes,
34981
35091
  hostname,
34982
35092
  hosts: hostsReader(this.base)
@@ -34988,10 +35098,7 @@ var Launcher = class {
34988
35098
  roots: packageTlsRoots(this.verifiedFs(options.fs), this.modulesDir),
34989
35099
  ca: this.ca
34990
35100
  });
34991
- enableDnsStub(
34992
- this.net,
34993
- kernelDnsStub(this.resolver, this.transport, options.uplink, options.doh)
34994
- );
35101
+ enableDnsStub(this.net, new DnsStub({ resolver: this.resolver, forward }));
34995
35102
  enableCdp(this.net, this.cdp);
34996
35103
  this.facades.enable(this.net);
34997
35104
  const fs = this.commandFs(this.base);
@@ -35807,7 +35914,7 @@ var Launcher = class {
35807
35914
  const foreign = foreignImports(bytes);
35808
35915
  const libc = libcVersionOf(bytes);
35809
35916
  const named = customSectionsOf(bytes, "name").length > 0;
35810
- const compiled = this.compile ? await this.compile(bytes, key) : await WebAssembly.compile(bytes);
35917
+ const compiled = this.compile ? await this.compile(bytes, key, this.sourceOf(path)) : await WebAssembly.compile(bytes);
35811
35918
  if (libc !== void 0) this.libcs.set(compiled, libc);
35812
35919
  return {
35813
35920
  value: { module: compiled, ...memory ? { memory } : {}, foreign, named },
@@ -35919,10 +36026,20 @@ var Launcher = class {
35919
36026
  );
35920
36027
  }
35921
36028
  reread(target, read) {
36029
+ this.forgetCompiled(target.wasm);
36030
+ return read();
36031
+ }
36032
+ forgetCompiled(path) {
35922
36033
  for (const key of this.compiled.keys()) {
35923
- if (key.startsWith(`${target.wasm}:`)) this.compiled.delete(key);
36034
+ if (key.startsWith(`${path}:`) || key.startsWith(`${path}\0`)) this.compiled.delete(key);
35924
36035
  }
35925
- return read();
36036
+ }
36037
+ sourceOf(path) {
36038
+ return {
36039
+ path,
36040
+ read: () => this.base.readFileBuffer(path),
36041
+ stale: () => this.forgetCompiled(path)
36042
+ };
35926
36043
  }
35927
36044
  exeId(target) {
35928
36045
  if (target.abi !== "wasi" || (target.copy ?? target.glue) !== target.wasm) {
@@ -38960,38 +39077,94 @@ function initialMemory(bytes) {
38960
39077
  }
38961
39078
  return 0;
38962
39079
  }
39080
+ var viewOf = (source) => source instanceof ArrayBuffer ? new Uint8Array(source) : new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
39081
+ var bufferOf2 = (bytes) => bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && bytes.buffer instanceof ArrayBuffer ? bytes.buffer : bytes.slice().buffer;
39082
+ var ImageError = class extends Error {
39083
+ code;
39084
+ exitStatus;
39085
+ constructor(code, message3) {
39086
+ super(`${code}: ${message3}`);
39087
+ this.code = code;
39088
+ this.exitStatus = code === "ENOENT" ? 127 : 126;
39089
+ }
39090
+ };
39091
+ function unread(path, err) {
39092
+ const code = err?.code;
39093
+ if (code === "ENOENT" || code === "ENOTDIR") {
39094
+ return new ImageError("ENOENT", `${path} is gone since the kernel compiled it`);
39095
+ }
39096
+ const why = err instanceof Error ? err.message : String(err);
39097
+ return new ImageError(typeof code === "string" ? code : "EIO", `${path} cannot be read: ${why}`);
39098
+ }
38963
39099
  var Images = class {
38964
- initial = /* @__PURE__ */ new Map();
38965
- bytes = /* @__PURE__ */ new Map();
38966
- handles = /* @__PURE__ */ new Map();
38967
- async register(source) {
38968
- const view2 = source instanceof ArrayBuffer ? new Uint8Array(source) : new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
39100
+ images = /* @__PURE__ */ new Map();
39101
+ reading = /* @__PURE__ */ new Map();
39102
+ async register(source, from) {
39103
+ const view2 = viewOf(source);
38969
39104
  const image = await digest(view2);
38970
- const known = this.handles.get(image);
38971
- if (known) return known;
39105
+ const known = this.images.get(image);
39106
+ if (known) {
39107
+ if (from) known.sources.set(from.path, from);
39108
+ else known.bytes ??= view2.slice().buffer;
39109
+ return known.handle;
39110
+ }
38972
39111
  const handle = Object.freeze({ image });
38973
- this.bytes.set(image, view2.slice().buffer);
38974
- this.initial.set(image, initialMemory(view2));
38975
- this.handles.set(image, handle);
39112
+ this.images.set(image, {
39113
+ handle,
39114
+ initial: initialMemory(view2),
39115
+ module: view2.byteLength,
39116
+ sources: new Map(from ? [[from.path, from]] : []),
39117
+ ...from ? {} : { bytes: view2.slice().buffer }
39118
+ });
38976
39119
  return handle;
38977
39120
  }
38978
- compile = async (bytes) => await this.register(bytes);
39121
+ compile = async (bytes, _key, from) => await this.register(bytes, from);
39122
+ load(image) {
39123
+ const entry = this.images.get(image);
39124
+ if (!entry) return Promise.reject(new ImageError("ENOENT", `no program image ${image}`));
39125
+ if (entry.bytes) return Promise.resolve(entry.bytes);
39126
+ const known = this.reading.get(image);
39127
+ if (known !== void 0) return known;
39128
+ const read = this.read(image, entry).finally(() => this.reading.delete(image));
39129
+ this.reading.set(image, read);
39130
+ return read;
39131
+ }
39132
+ async read(image, entry) {
39133
+ let failed4;
39134
+ for (const source of [...entry.sources.values()]) {
39135
+ try {
39136
+ const bytes = await source.read();
39137
+ if (bytes.byteLength === entry.module && await digest(bytes) === image) {
39138
+ return bufferOf2(bytes);
39139
+ }
39140
+ failed4 ??= new ImageError("ESTALE", `${source.path} changed since the kernel compiled it`);
39141
+ } catch (err) {
39142
+ failed4 ??= unread(source.path, err);
39143
+ }
39144
+ entry.sources.delete(source.path);
39145
+ source.stale?.();
39146
+ }
39147
+ throw failed4 ?? new ImageError("ENOENT", `no file holds program image ${image}`);
39148
+ }
38979
39149
  get(image) {
38980
- const bytes = this.bytes.get(image);
38981
- if (!bytes) throw new Error(`no program image ${image}`);
39150
+ const bytes = this.images.get(image)?.bytes;
39151
+ if (!bytes) throw new Error(`no program image ${image} kept in memory: load() reads it`);
38982
39152
  return bytes;
38983
39153
  }
38984
39154
  sizeOf(image) {
38985
- return {
38986
- initial: this.initial.get(image) ?? 0,
38987
- module: this.bytes.get(image)?.byteLength ?? 0
38988
- };
39155
+ const entry = this.images.get(image);
39156
+ return { initial: entry?.initial ?? 0, module: entry?.module ?? 0 };
38989
39157
  }
38990
39158
  has(image) {
38991
- return this.bytes.has(image);
39159
+ return this.images.has(image);
38992
39160
  }
38993
39161
  get size() {
38994
- return this.bytes.size;
39162
+ return this.images.size;
39163
+ }
39164
+ get held() {
39165
+ let total = 0;
39166
+ for (const entry of this.images.values()) total += entry.bytes?.byteLength ?? 0;
39167
+ return total;
38995
39168
  }
38996
39169
  };
38997
39170
  function imageOf(module) {
@@ -39752,12 +39925,16 @@ function parentOf11(init) {
39752
39925
  function cloudflareProcesses(loader, images, gate, code, memory = {}) {
39753
39926
  let hostDigest;
39754
39927
  let loads = 0;
39928
+ const failedLoads = /* @__PURE__ */ new Map();
39755
39929
  const idOf3 = async (ref) => {
39756
39930
  hostDigest ??= digest(`${code.host}\0${code.process}\0${code.localForks !== false}`);
39757
39931
  const imports = ref.imports ? `-${ref.imports.digest.slice(0, 16)}` : "";
39758
- return `slicc-${(await hostDigest).slice(0, 16)}-${ref.image.slice(0, 40)}${imports}`;
39932
+ const failed4 = failedLoads.get(keyOf3(ref));
39933
+ const again = failed4 === void 0 ? "" : `-r${failed4}`;
39934
+ return `slicc-${(await hostDigest).slice(0, 16)}-${ref.image.slice(0, 40)}${imports}${again}`;
39759
39935
  };
39760
- const workerCode = (ref) => {
39936
+ const workerCode = async (ref) => {
39937
+ const wasm = await images.load(ref.image);
39761
39938
  loads++;
39762
39939
  const env = {
39763
39940
  ...code.localForks === false ? { SLICC_LOCAL_FORKS: "off" } : {},
@@ -39770,7 +39947,7 @@ function cloudflareProcesses(loader, images, gate, code, memory = {}) {
39770
39947
  modules: {
39771
39948
  "host.js": code.host,
39772
39949
  "process.js": code.process,
39773
- "program.wasm": { wasm: images.get(ref.image) },
39950
+ "program.wasm": { wasm },
39774
39951
  "imports.js": ref.imports?.source ?? NO_IMPORTS_MODULE
39775
39952
  },
39776
39953
  globalOutbound: null,
@@ -39855,8 +40032,13 @@ function cloudflareProcesses(loader, images, gate, code, memory = {}) {
39855
40032
  if (pid !== void 0 && seated.get(pid) === seat) seated.delete(pid);
39856
40033
  seat.release();
39857
40034
  };
40035
+ const cold = {};
40036
+ const code2 = () => workerCode(ref).catch((err) => {
40037
+ cold.failed = err;
40038
+ throw err;
40039
+ });
39858
40040
  try {
39859
- const host = loader.get(seat.id, () => workerCode(ref)).getEntrypoint();
40041
+ const host = loader.get(seat.id, code2).getEntrypoint();
39860
40042
  return await openLink(host, release, {
39861
40043
  forks,
39862
40044
  sized: (bytes) => seat.memory(bytes),
@@ -39865,7 +40047,11 @@ function cloudflareProcesses(loader, images, gate, code, memory = {}) {
39865
40047
  });
39866
40048
  } catch (err) {
39867
40049
  release();
39868
- throw err;
40050
+ const failed4 = cold.failed ?? err;
40051
+ if (failed4 instanceof ImageError) {
40052
+ failedLoads.set(keyOf3(ref), (failedLoads.get(keyOf3(ref)) ?? 0) + 1);
40053
+ }
40054
+ throw failed4;
39869
40055
  }
39870
40056
  }
39871
40057
  };
@@ -40016,6 +40202,10 @@ var SqlStore = class {
40016
40202
  rows(query, ...bindings) {
40017
40203
  return this.sql.exec(query, ...bindings).toArray();
40018
40204
  }
40205
+ each(query, ...bindings) {
40206
+ const cursor = this.sql.exec(query, ...bindings);
40207
+ return cursor[Symbol.iterator] ? cursor : cursor.toArray();
40208
+ }
40019
40209
  row(query, ...bindings) {
40020
40210
  return this.rows(query, ...bindings)[0];
40021
40211
  }
@@ -40447,7 +40637,7 @@ var Files = class {
40447
40637
  const first = Math.floor(start2 / CHUNK_BYTES);
40448
40638
  const last = Math.floor((end - 1) / CHUNK_BYTES);
40449
40639
  const state = this.chunks.get(node);
40450
- const rows = this.store.rows(
40640
+ const rows = this.store.each(
40451
40641
  `SELECT idx, substr(data, max(? - idx * ${CHUNK_BYTES}, 0) + 1, min(? - idx * ${CHUNK_BYTES}, ${CHUNK_BYTES}) - max(? - idx * ${CHUNK_BYTES}, 0)) AS part FROM slicc_chunks WHERE node = ? AND idx BETWEEN ? AND ?`,
40452
40642
  start2,
40453
40643
  end,