@ai-ecoverse/slicc-kernel 1.123.2 → 1.124.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.
@@ -4442,6 +4442,111 @@ var Routes = class {
4442
4442
  }
4443
4443
  };
4444
4444
 
4445
+ // src/kernel/net/switch-conn.ts
4446
+ var SwitchConn = class {
4447
+ raw;
4448
+ box = [];
4449
+ pulling = false;
4450
+ waiters = [];
4451
+ switching = false;
4452
+ secure;
4453
+ failed;
4454
+ constructor(raw) {
4455
+ this.raw = raw;
4456
+ }
4457
+ get localAddr() {
4458
+ return this.raw.localAddr;
4459
+ }
4460
+ get remoteAddr() {
4461
+ return this.raw.remoteAddr;
4462
+ }
4463
+ get upgraded() {
4464
+ return this.switching || this.secure !== void 0;
4465
+ }
4466
+ wake() {
4467
+ for (const wake of this.waiters.splice(0)) wake();
4468
+ }
4469
+ changed() {
4470
+ return new Promise((resolve2) => this.waiters.push(resolve2));
4471
+ }
4472
+ pull() {
4473
+ if (this.pulling || this.box.length > 0) return;
4474
+ this.pulling = true;
4475
+ this.raw.read().then(
4476
+ (bytes) => this.box.push(bytes),
4477
+ (err) => this.box.push(err instanceof Error ? err : new Error(String(err)))
4478
+ ).finally(() => {
4479
+ this.pulling = false;
4480
+ this.wake();
4481
+ });
4482
+ }
4483
+ take() {
4484
+ const next3 = this.box.shift();
4485
+ if (next3 instanceof Error) throw next3;
4486
+ return next3;
4487
+ }
4488
+ async rawRead() {
4489
+ while (this.box.length === 0) {
4490
+ this.pull();
4491
+ await this.changed();
4492
+ }
4493
+ return this.take();
4494
+ }
4495
+ async read() {
4496
+ for (; ; ) {
4497
+ if (this.failed) throw this.failed;
4498
+ if (this.secure) return this.secure.read();
4499
+ if (!this.switching && this.box.length > 0) return this.take();
4500
+ if (!this.switching) this.pull();
4501
+ await this.changed();
4502
+ }
4503
+ }
4504
+ async settled() {
4505
+ while (this.switching) await this.changed();
4506
+ if (this.failed) throw this.failed;
4507
+ return this.secure ?? this.raw;
4508
+ }
4509
+ async write(bytes) {
4510
+ return (await this.settled()).write(bytes);
4511
+ }
4512
+ closeWrite() {
4513
+ void this.settled().then(
4514
+ (conn) => conn.closeWrite(),
4515
+ () => void 0
4516
+ );
4517
+ }
4518
+ close() {
4519
+ this.failed ??= new Error("closed");
4520
+ this.secure?.close();
4521
+ this.raw.close();
4522
+ this.wake();
4523
+ }
4524
+ async upgrade(make) {
4525
+ if (this.upgraded) throw new Error("already upgraded");
4526
+ this.switching = true;
4527
+ this.wake();
4528
+ const view2 = {
4529
+ localAddr: this.raw.localAddr,
4530
+ remoteAddr: this.raw.remoteAddr,
4531
+ read: () => this.rawRead(),
4532
+ write: (bytes) => this.raw.write(bytes),
4533
+ closeWrite: () => this.raw.closeWrite(),
4534
+ close: () => this.raw.close()
4535
+ };
4536
+ try {
4537
+ const { conn, info } = await make(view2);
4538
+ this.secure = conn;
4539
+ return info;
4540
+ } catch (err) {
4541
+ this.failed = err instanceof Error ? err : new Error(String(err));
4542
+ throw err;
4543
+ } finally {
4544
+ this.switching = false;
4545
+ this.wake();
4546
+ }
4547
+ }
4548
+ };
4549
+
4445
4550
  // src/kernel/net/uplink-socket.ts
4446
4551
  var CHUNK = 64 * 1024;
4447
4552
  function hostPort(text) {
@@ -4766,7 +4871,18 @@ var KernelSocket = class _KernelSocket {
4766
4871
  clearTimeout(timer);
4767
4872
  }
4768
4873
  }
4769
- dial(addr, route) {
4874
+ switch;
4875
+ connectSecure(addr, route, secure2) {
4876
+ if (this.state !== "open") throw new KernelError("EISCONN");
4877
+ return this.dial(addr, route, secure2);
4878
+ }
4879
+ upgradeSecure(make) {
4880
+ if (this.state !== "connected") throw new KernelError("ENOTCONN");
4881
+ if (!this.switch) throw new KernelError("EOPNOTSUPP");
4882
+ if (this.switch.upgraded || this.writeShut || this.readShut) throw new KernelError("EINVAL");
4883
+ return this.switch.upgrade(make);
4884
+ }
4885
+ dial(addr, route, secure2) {
4770
4886
  this.state = "connecting";
4771
4887
  const abort = new AbortController();
4772
4888
  this.dialing = abort;
@@ -4787,11 +4903,25 @@ var KernelSocket = class _KernelSocket {
4787
4903
  () => void 0
4788
4904
  );
4789
4905
  return Promise.race([dialled, abandoned]).then(
4790
- (conn) => {
4906
+ async (raw) => {
4791
4907
  if (abort.signal.aborted) throw dialError(abort.signal.reason, timedOut, true);
4908
+ const conn = new SwitchConn(raw);
4909
+ if (secure2) {
4910
+ clearTimeout(timer);
4911
+ try {
4912
+ await Promise.race([secure2(conn), abandoned]);
4913
+ } catch (e) {
4914
+ conn.close();
4915
+ throw this.dialFailed(
4916
+ abort,
4917
+ e instanceof KernelError ? e : new KernelError("ENOTSUP", e instanceof Error ? e.message : String(e))
4918
+ );
4919
+ }
4920
+ }
4792
4921
  this.local = { family: "inet", host: "0.0.0.0", port: 0, ...hostPort(conn.localAddr) };
4793
4922
  this.peer = { ...addr, ...hostPort(conn.remoteAddr) };
4794
4923
  this.dialing = void 0;
4924
+ this.switch = conn;
4795
4925
  this.attach(
4796
4926
  uplinkLink(conn, () => {
4797
4927
  this.reset = true;
@@ -4800,17 +4930,19 @@ var KernelSocket = class _KernelSocket {
4800
4930
  );
4801
4931
  },
4802
4932
  (e) => {
4803
- const error = dialError(e, timedOut, abort.signal.aborted);
4804
- if (this.dialing === abort) {
4805
- this.dialing = void 0;
4806
- this.failed = error.code;
4807
- this.state = "open";
4808
- this.changes.wake();
4809
- }
4810
- throw error;
4933
+ throw this.dialFailed(abort, dialError(e, timedOut, abort.signal.aborted));
4811
4934
  }
4812
4935
  ).finally(() => clearTimeout(timer));
4813
4936
  }
4937
+ dialFailed(abort, error) {
4938
+ if (this.dialing === abort) {
4939
+ this.dialing = void 0;
4940
+ this.failed = error.code;
4941
+ this.state = "open";
4942
+ this.changes.wake();
4943
+ }
4944
+ return error;
4945
+ }
4814
4946
  unlink() {
4815
4947
  const link2 = this.link;
4816
4948
  if (link2) {
@@ -4916,6 +5048,7 @@ var LoopbackNet = class {
4916
5048
  useUplink(route) {
4917
5049
  this.route = route;
4918
5050
  }
5051
+ tlsClient;
4919
5052
  uplinkFor(host) {
4920
5053
  const route = this.route;
4921
5054
  if (!route) return void 0;
@@ -5057,12 +5190,12 @@ function serveSocket(socket, port, onClose) {
5057
5190
  let writes = Promise.resolve();
5058
5191
  let credit = 0;
5059
5192
  let granted2;
5060
- const send = (message3, transfer) => {
5193
+ const send2 = (message3, transfer) => {
5061
5194
  if (!closed) port.postMessage(message3, transfer);
5062
5195
  };
5063
5196
  const close = (reset = false) => {
5064
5197
  if (closed) return;
5065
- if (reset) send({ error: "ECONNRESET" });
5198
+ if (reset) send2({ error: "ECONNRESET" });
5066
5199
  closed = true;
5067
5200
  granted2?.();
5068
5201
  socket.close();
@@ -5074,9 +5207,9 @@ function serveSocket(socket, port, onClose) {
5074
5207
  if (closed) return;
5075
5208
  try {
5076
5209
  await socket.write(data);
5077
- send({ ack: true });
5210
+ send2({ ack: true });
5078
5211
  } catch (err) {
5079
- send({ error: codeOf(err) });
5212
+ send2({ error: codeOf(err) });
5080
5213
  }
5081
5214
  });
5082
5215
  };
@@ -5101,11 +5234,11 @@ function serveSocket(socket, port, onClose) {
5101
5234
  const chunk2 = await socket.read(CHUNK2);
5102
5235
  if (chunk2.length === 0) break;
5103
5236
  credit--;
5104
- send(chunk2, [chunk2.buffer]);
5237
+ send2(chunk2, [chunk2.buffer]);
5105
5238
  }
5106
- send({ end: true });
5239
+ send2({ end: true });
5107
5240
  } catch (err) {
5108
- send({ error: codeOf(err) });
5241
+ send2({ error: codeOf(err) });
5109
5242
  }
5110
5243
  })();
5111
5244
  return () => close(true);
@@ -6018,7 +6151,7 @@ function joinable(l, pgid, ours) {
6018
6151
  if (sid === void 0) throw fsError("ESRCH", `no process group ${pgid}`);
6019
6152
  if (!ours(sid)) throw fsError("EPERM", `process group ${pgid} is in another session`);
6020
6153
  }
6021
- function cdpRegistry(send, gone) {
6154
+ function cdpRegistry(send2, gone) {
6022
6155
  const registered = /* @__PURE__ */ new Map();
6023
6156
  const drop = (id2) => {
6024
6157
  registered.get(id2)?.();
@@ -6027,7 +6160,7 @@ function cdpRegistry(send, gone) {
6027
6160
  return {
6028
6161
  serve(l, req) {
6029
6162
  const hook = portCdpHook(
6030
- (request2, cdp) => send({ cdpOpen: { ...request2, registration: req.id }, port: cdp }, [
6163
+ (request2, cdp) => send2({ cdpOpen: { ...request2, registration: req.id }, port: cdp }, [
6031
6164
  cdp
6032
6165
  ]),
6033
6166
  gone
@@ -6041,7 +6174,7 @@ function cdpRegistry(send, gone) {
6041
6174
  }
6042
6175
  };
6043
6176
  }
6044
- function facadeRegistry(send, gone) {
6177
+ function facadeRegistry(send2, gone) {
6045
6178
  const registered = /* @__PURE__ */ new Map();
6046
6179
  const drop = (id2) => {
6047
6180
  registered.get(id2)?.();
@@ -6050,7 +6183,7 @@ function facadeRegistry(send, gone) {
6050
6183
  return {
6051
6184
  serve(l, req) {
6052
6185
  const hook = portFacadeHook(
6053
- (request2, facade) => send({ facadeOpen: { ...request2, registration: req.id }, port: facade }, [
6186
+ (request2, facade) => send2({ facadeOpen: { ...request2, registration: req.id }, port: facade }, [
6054
6187
  facade
6055
6188
  ]),
6056
6189
  gone
@@ -6064,9 +6197,9 @@ function facadeRegistry(send, gone) {
6064
6197
  }
6065
6198
  };
6066
6199
  }
6067
- function hostRegistries(send, gone) {
6068
- const cdps = cdpRegistry(send, gone);
6069
- const facades = facadeRegistry(send, gone);
6200
+ function hostRegistries(send2, gone) {
6201
+ const cdps = cdpRegistry(send2, gone);
6202
+ const facades = facadeRegistry(send2, gone);
6070
6203
  return {
6071
6204
  answer(l, req) {
6072
6205
  if (req.op === "serve-cdp") return cdps.serve(l, req);
@@ -6093,21 +6226,21 @@ function visibleTo(g, notify) {
6093
6226
  });
6094
6227
  };
6095
6228
  }
6096
- async function watchOp(l, req, watches, send, g) {
6229
+ async function watchOp(l, req, watches, send2, g) {
6097
6230
  if (req.op === "unwatch") {
6098
6231
  watches.get(req.watch)?.();
6099
6232
  watches.delete(req.watch);
6100
6233
  return { result: true };
6101
6234
  }
6102
6235
  if (g) for (const path of req.paths) await readable(g, "watch", l.fs.resolvePath("/", path));
6103
- const notify = visibleTo(g, (change) => send({ watch: req.id, change }));
6236
+ const notify = visibleTo(g, (change) => send2({ watch: req.id, change }));
6104
6237
  const unwatch = l.watchers.watch(req.paths, { recursive: req.recursive }, notify);
6105
6238
  watches.set(req.id, unwatch);
6106
6239
  return { result: req.id };
6107
6240
  }
6108
6241
  var TRAITS_WATCH = -1;
6109
- function traitsWatch(launcher, transport, send) {
6110
- return launcher.onTraits(() => send({ traits: transport.traits }));
6242
+ function traitsWatch(launcher, transport, send2) {
6243
+ return launcher.onTraits(() => send2({ traits: transport.traits }));
6111
6244
  }
6112
6245
  function serveClient(port, host) {
6113
6246
  let state = "new";
@@ -6119,14 +6252,14 @@ function serveClient(port, host) {
6119
6252
  const watches = /* @__PURE__ */ new Map();
6120
6253
  let net;
6121
6254
  const ended = Promise.withResolvers();
6122
- const send = (message3, transfer = []) => {
6255
+ const send2 = (message3, transfer = []) => {
6123
6256
  if (state !== "closed") port.postMessage(message3, transfer);
6124
6257
  };
6125
- const reply = (id2, body, transfer) => send({ id: id2, ...body }, transfer);
6126
- const hosts = hostRegistries(send, ended.promise);
6258
+ const reply = (id2, body, transfer) => send2({ id: id2, ...body }, transfer);
6259
+ const hosts = hostRegistries(send2, ended.promise);
6127
6260
  function detach(kill = false, bye = "the slicc-kernel detached this client") {
6128
6261
  if (state === "closed") return;
6129
- send({ bye });
6262
+ send2({ bye });
6130
6263
  state = "closed";
6131
6264
  net?.close();
6132
6265
  for (const unwatch of watches.values()) unwatch();
@@ -6140,19 +6273,19 @@ function serveClient(port, host) {
6140
6273
  ended.resolve();
6141
6274
  }
6142
6275
  async function hello(message3) {
6143
- const refused2 = versionError(message3.protocol);
6144
- if (refused2) {
6145
- send({ hello: { protocol: PROTOCOL, error: refused2 } });
6276
+ const refused3 = versionError(message3.protocol);
6277
+ if (refused3) {
6278
+ send2({ hello: { protocol: PROTOCOL, error: refused3 } });
6146
6279
  detach();
6147
6280
  return;
6148
6281
  }
6149
6282
  const launcher = await host.launcher();
6150
6283
  if (host.scope !== "transport") self = await accountOf(launcher, host.user ?? 0);
6151
6284
  const transport = host.transport?.() ?? launcher.transport;
6152
- net = serveTransport({ postMessage: (m, t) => send(m, t) }, transport);
6285
+ net = serveTransport({ postMessage: (m, t) => send2(m, t) }, transport);
6153
6286
  state = "open";
6154
6287
  if (message3.lock && host.locks) void host.locks.request(message3.lock, () => detach());
6155
- send({
6288
+ send2({
6156
6289
  hello: {
6157
6290
  protocol: PROTOCOL,
6158
6291
  traits: transport.traits,
@@ -6160,7 +6293,7 @@ function serveClient(port, host) {
6160
6293
  ...host.lock ? { lock: host.lock } : {}
6161
6294
  }
6162
6295
  });
6163
- watches.set(TRAITS_WATCH, traitsWatch(launcher, transport, send));
6296
+ watches.set(TRAITS_WATCH, traitsWatch(launcher, transport, send2));
6164
6297
  }
6165
6298
  async function terminal(req, l) {
6166
6299
  const session = await l.openTerminal(req.argv, {
@@ -6224,7 +6357,7 @@ function serveClient(port, host) {
6224
6357
  return clientFs(l, host.tag, self, req);
6225
6358
  case "watch":
6226
6359
  case "unwatch":
6227
- return watchOp(l, req, watches, send, guard2(l));
6360
+ return watchOp(l, req, watches, send2, guard2(l));
6228
6361
  case "mount":
6229
6362
  return { result: await l.mountAs(clientCred(self), req.spec) };
6230
6363
  case "umount":
@@ -6250,7 +6383,7 @@ function serveClient(port, host) {
6250
6383
  if (data.hello) {
6251
6384
  if (state === "new") {
6252
6385
  hello(data.hello).catch((err) => {
6253
- send({ hello: { protocol: PROTOCOL, error: String(err?.message ?? err) } });
6386
+ send2({ hello: { protocol: PROTOCOL, error: String(err?.message ?? err) } });
6254
6387
  detach();
6255
6388
  });
6256
6389
  }
@@ -6432,7 +6565,7 @@ function satisfies(version, range2) {
6432
6565
  }
6433
6566
 
6434
6567
  // src/version.ts
6435
- var KERNEL_VERSION = true ? "1.123.2" : "0.0.0-dev";
6568
+ var KERNEL_VERSION = true ? "1.124.1" : "0.0.0-dev";
6436
6569
  var OS_RELEASE = "6.0.0-slicc";
6437
6570
  function procVersion() {
6438
6571
  return `Linux version ${OS_RELEASE} (slicc-kernel ${KERNEL_VERSION}) #1 SMP PREEMPT_DYNAMIC
@@ -6714,13 +6847,13 @@ async function tierPackages(fs, physical, roots, bins, kernel) {
6714
6847
  const own = commandsOf(pkg, manifest);
6715
6848
  const named = new Set(own.map((command) => command.name));
6716
6849
  const extra = bins ? await binCommandsOf(physical, pkg, manifest, named) : [];
6717
- const refused2 = engineRefusal(manifest, kernel);
6850
+ const refused3 = engineRefusal(manifest, kernel);
6718
6851
  const commands = [...own, ...extra];
6719
6852
  out.push({
6720
6853
  name: pkg.slice(root.length + 1),
6721
6854
  pkg,
6722
6855
  replaces: replacesOf(manifest),
6723
- commands: refused2 ? commands.map((command) => ({ ...command, refused: refused2 })) : commands
6856
+ commands: refused3 ? commands.map((command) => ({ ...command, refused: refused3 })) : commands
6724
6857
  });
6725
6858
  }
6726
6859
  }
@@ -7335,18 +7468,19 @@ var UnlinkedKeeper = class {
7335
7468
  const keeper = this;
7336
7469
  const { replacing } = this;
7337
7470
  const replace = async (target, op) => {
7338
- const before = replacing.get(target);
7339
7471
  const { promise, resolve: resolve2 } = Promise.withResolvers();
7340
- const mine = {
7341
- done: Promise.all([before?.done, promise]).then(() => void 0)
7472
+ let mine;
7473
+ const gated = () => {
7474
+ const before = replacing.get(target);
7475
+ mine = { done: Promise.all([before?.done, promise]).then(() => void 0) };
7476
+ replacing.set(target, mine);
7342
7477
  };
7343
- replacing.set(target, mine);
7344
7478
  try {
7345
- await op();
7479
+ await op(gated);
7346
7480
  } finally {
7347
7481
  keeper.replaced += 1;
7348
7482
  resolve2();
7349
- if (replacing.get(target) === mine) replacing.delete(target);
7483
+ if (mine && replacing.get(target) === mine) replacing.delete(target);
7350
7484
  }
7351
7485
  };
7352
7486
  const unreplaced = async (path, op) => {
@@ -7391,8 +7525,8 @@ var UnlinkedKeeper = class {
7391
7525
  async rename(from, to) {
7392
7526
  const target = fs.resolvePath("/", to);
7393
7527
  if (target === fs.resolvePath("/", from)) return fs.rename(from, to);
7394
- await replace(target, async () => {
7395
- const pinned = await keeper.pin(target);
7528
+ await replace(target, async (gated) => {
7529
+ const pinned = await keeper.pin(target, gated);
7396
7530
  await keeper.settle(pinned, () => fs.rename(from, to));
7397
7531
  });
7398
7532
  },
@@ -7409,7 +7543,7 @@ var UnlinkedKeeper = class {
7409
7543
  }
7410
7544
  pinned.commit();
7411
7545
  }
7412
- async pin(target) {
7546
+ heldWithin(target) {
7413
7547
  const held = /* @__PURE__ */ new Map();
7414
7548
  for (const holder of this.holders) {
7415
7549
  if (holder.owns(target)) continue;
@@ -7418,11 +7552,19 @@ var UnlinkedKeeper = class {
7418
7552
  held.set(path, [...held.get(path) ?? [], holder]);
7419
7553
  }
7420
7554
  }
7421
- const paths = [...held.keys()].sort();
7555
+ return held;
7556
+ }
7557
+ async pin(target, gated = () => void 0) {
7558
+ const paths = [...this.heldWithin(target).keys()].sort();
7422
7559
  const releases = [];
7423
7560
  for (const path of paths) releases.push(await this.gate.acquire(path));
7561
+ gated();
7562
+ const now = this.heldWithin(target);
7563
+ const held = new Map(
7564
+ paths.flatMap((path) => now.has(path) ? [[path, now.get(path)]] : [])
7565
+ );
7424
7566
  const hidden = /* @__PURE__ */ new Map();
7425
- for (const path of paths) {
7567
+ for (const path of held.keys()) {
7426
7568
  const at = await this.hide(path);
7427
7569
  if (at !== void 0) hidden.set(path, at);
7428
7570
  }
@@ -8305,8 +8447,8 @@ var RealmProxy = class {
8305
8447
  }
8306
8448
  async connect(conn, incoming, req, idle) {
8307
8449
  const target = tunnelTarget(req);
8308
- const refused2 = target.port === 443 ? await this.tunnelReady(target) : void 0;
8309
- if (refused2) throw refused2;
8450
+ const refused3 = target.port === 443 ? await this.tunnelReady(target) : void 0;
8451
+ if (refused3) throw refused3;
8310
8452
  await conn.write(latin1Bytes("HTTP/1.1 200 Connection Established\r\n\r\n"), this.stop.signal);
8311
8453
  try {
8312
8454
  const first = await incoming.peek(this.stop.signal);
@@ -9960,8 +10102,8 @@ var DriverConnection = class _DriverConnection {
9960
10102
  } finally {
9961
10103
  clearTimeout(timer);
9962
10104
  }
9963
- const refused2 = driverVersionError(hello.protocol);
9964
- if (refused2) throw errnoError("EPROTO", refused2);
10105
+ const refused3 = driverVersionError(hello.protocol);
10106
+ if (refused3) throw errnoError("EPROTO", refused3);
9965
10107
  if (hello.error) throw errnoError(hello.errno ?? "EIO", hello.error);
9966
10108
  return new _DriverConnection(port, hello.capabilities ?? {}, waiting, timeoutMs, options);
9967
10109
  }
@@ -11783,8 +11925,8 @@ async function guarded(entry, path, req) {
11783
11925
  return { paths };
11784
11926
  } catch (err) {
11785
11927
  const refusal = err.code === "EACCES";
11786
- const refused2 = req.op === "exists" && refusal ? json2(false) : toErrno(err);
11787
- return { refused: refused2 };
11928
+ const refused3 = req.op === "exists" && refusal ? json2(false) : toErrno(err);
11929
+ return { refused: refused3 };
11788
11930
  }
11789
11931
  }
11790
11932
  async function createExclusive(fs, path, owner) {
@@ -11895,13 +12037,13 @@ async function dispatchSyncFs(req) {
11895
12037
  }
11896
12038
  }
11897
12039
  var DENIED = /* @__PURE__ */ new Set(["EACCES", "EPERM"]);
11898
- async function rmPermitted(entry, path, req, refused2) {
12040
+ async function rmPermitted(entry, path, req, refused3) {
11899
12041
  const st = await entry.fs.lstat(path).catch(() => void 0);
11900
- if (!st?.isDirectory) return refused2;
12042
+ if (!st?.isDirectory) return refused3;
11901
12043
  const unlisted = await guarded(entry, path, { ...req, op: "readdir" });
11902
12044
  if ("refused" in unlisted) return unlisted.refused;
11903
12045
  const names = await entry.fs.readdir(path).catch(() => void 0);
11904
- if (!names) return refused2;
12046
+ if (!names) return refused3;
11905
12047
  let first;
11906
12048
  for (const name2 of names) {
11907
12049
  const child = await dispatchOne(entry, {
@@ -11952,14 +12094,14 @@ async function newDevName(entry, path, req) {
11952
12094
  const named = NAMING.has(req.op);
11953
12095
  if (!named && !CREATIONS.has(req.op)) return void 0;
11954
12096
  const target = named ? entry.fs.resolvePath(entry.cwd, req.arg2 ?? "") : path;
11955
- const refused2 = devCreation(target, entry.cred?.());
11956
- if (!refused2) return void 0;
12097
+ const refused3 = devCreation(target, entry.cred?.());
12098
+ if (!refused3) return void 0;
11957
12099
  const there = await entry.fs.lstat(target).then(
11958
12100
  () => true,
11959
12101
  () => false
11960
12102
  );
11961
12103
  if (there) return void 0;
11962
- return { ok: false, errno: refused2, message: `${target}: no new names in /dev or /proc` };
12104
+ return { ok: false, errno: refused3, message: `${target}: no new names in /dev or /proc` };
11963
12105
  }
11964
12106
  async function dispatchOne(entry, req) {
11965
12107
  const { fs, cwd } = entry;
@@ -13362,6 +13504,9 @@ var FlockTable = class {
13362
13504
  held = /* @__PURE__ */ new Map();
13363
13505
  keys = /* @__PURE__ */ new WeakMap();
13364
13506
  wakers = /* @__PURE__ */ new Map();
13507
+ isFree(key, owner, kind) {
13508
+ return this.free(key, owner, kind);
13509
+ }
13365
13510
  free(key, owner, kind) {
13366
13511
  for (const [other, has] of this.held.get(key) ?? [])
13367
13512
  if (other !== owner && (kind === "exclusive" || has === "exclusive")) return false;
@@ -13488,9 +13633,18 @@ var LockTable = class {
13488
13633
  );
13489
13634
  this.wake(key);
13490
13635
  }
13636
+ wholeFree(pid, path, exclusive) {
13637
+ for (const [other, h] of this.held.get(path) ?? []) {
13638
+ if (other !== pid && (exclusive || h.exclusive)) return false;
13639
+ }
13640
+ return true;
13641
+ }
13642
+ flockFree(key, owner, kind) {
13643
+ return this.flocks.isFree(key, owner, kind);
13644
+ }
13491
13645
  lock(pid, path, exclusive, fd) {
13646
+ if (!this.wholeFree(pid, path, exclusive)) return false;
13492
13647
  const holders = this.held.get(path) ?? /* @__PURE__ */ new Map();
13493
- for (const [other, h] of holders) if (other !== pid && (exclusive || h.exclusive)) return false;
13494
13648
  const mine = holders.get(pid) ?? { exclusive, fds: /* @__PURE__ */ new Set() };
13495
13649
  mine.exclusive = exclusive;
13496
13650
  mine.fds.add(fd);
@@ -13675,12 +13829,12 @@ var AsyncOps = class {
13675
13829
  async function hostSyscall(req, ctx) {
13676
13830
  switch (req.op) {
13677
13831
  case "lock":
13678
- if (!ctx.locks) throw new KernelError("ENOSYS");
13679
- if (!ctx.locks.lock(ctx.pid, req.path, req.exclusive, req.fd))
13680
- throw new KernelError("EAGAIN");
13681
- return done2;
13832
+ return wholeLock(req, ctx);
13682
13833
  case "unlock":
13683
13834
  ctx.locks?.unlock(ctx.pid, req.path);
13835
+ if (req.fd !== void 0 && ctx.locks?.shared?.() && ctx.flockOf) {
13836
+ return flock({ op: "flock", fd: req.fd, kind: "unlock" }, ctx);
13837
+ }
13684
13838
  return done2;
13685
13839
  case "lk-set":
13686
13840
  case "lk-get":
@@ -13710,6 +13864,23 @@ async function hostSyscall(req, ctx) {
13710
13864
  return done2;
13711
13865
  }
13712
13866
  }
13867
+ async function wholeLock(req, ctx) {
13868
+ const { locks, flockOf } = ctx;
13869
+ if (!locks) throw new KernelError("ENOSYS");
13870
+ const kind = req.exclusive ? "exclusive" : "shared";
13871
+ if (locks.shared?.() && flockOf) {
13872
+ if (locks.wholeFree?.(ctx.pid, req.path, req.exclusive) === false) {
13873
+ throw new KernelError("EAGAIN");
13874
+ }
13875
+ return flock({ op: "flock", fd: req.fd, kind }, ctx);
13876
+ }
13877
+ if (flockOf && locks.flockFree) {
13878
+ const { key, owner } = await flockOf(req.fd);
13879
+ if (!locks.flockFree(key, owner, kind)) throw new KernelError("EAGAIN");
13880
+ }
13881
+ if (!locks.lock(ctx.pid, req.path, req.exclusive, req.fd)) throw new KernelError("EAGAIN");
13882
+ return done2;
13883
+ }
13713
13884
  var FLOCK_KINDS = /* @__PURE__ */ new Set(["shared", "exclusive", "unlock"]);
13714
13885
  async function flock(req, ctx) {
13715
13886
  const { locks, flockOf } = ctx;
@@ -13896,8 +14067,8 @@ var KernelLoopback = class {
13896
14067
  );
13897
14068
  } catch (err) {
13898
14069
  socket.close();
13899
- const refused2 = err instanceof KernelError && err.code === "ECONNREFUSED";
13900
- throw refused2 ? errno2("ECONNREFUSED", `nothing listens on the kernel's port ${port}`) : err;
14070
+ const refused3 = err instanceof KernelError && err.code === "ECONNREFUSED";
14071
+ throw refused3 ? errno2("ECONNREFUSED", `nothing listens on the kernel's port ${port}`) : err;
13901
14072
  }
13902
14073
  signal.addEventListener("abort", () => socket.close(), { once: true });
13903
14074
  return socket;
@@ -14433,6 +14604,7 @@ function realmCa(owner, store) {
14433
14604
  }
14434
14605
 
14435
14606
  // src/kernel/net/tls-engine.ts
14607
+ var TLS_CLIENT_INSECURE_SKIP_VERIFY = 1;
14436
14608
  var SCRATCH = 64 * 1024;
14437
14609
  var EOF = -1;
14438
14610
  var TlsError = class extends Error {
@@ -14493,6 +14665,76 @@ var TlsEngine = class {
14493
14665
  const n = fn(this.scratch, SCRATCH);
14494
14666
  return n > 0 ? this.taken(n) : n;
14495
14667
  }
14668
+ get client() {
14669
+ return typeof this.m._tls_client_new === "function" ? this.m : void 0;
14670
+ }
14671
+ clientModule() {
14672
+ const m = this.client;
14673
+ if (!m) throw new TlsError(0, "tls client: the installed tls engine has no client sessions");
14674
+ return m;
14675
+ }
14676
+ store() {
14677
+ const m = this.clientModule();
14678
+ const ptr = m._tls_ca_new();
14679
+ if (!ptr) throw this.error(m._tls_last_error(), "trust store");
14680
+ return new TlsStore(this, m, ptr);
14681
+ }
14682
+ clientSession(store, servername, alpn, flags2) {
14683
+ const m = this.clientModule();
14684
+ const wire = alpnWire(alpn);
14685
+ const name2 = this.put(new TextEncoder().encode(servername));
14686
+ try {
14687
+ const at = store?.ptr ?? 0;
14688
+ const ptr = this.withBytes(wire, (p) => m._tls_client_new(at, name2, p, wire.length, flags2));
14689
+ if (!ptr) throw this.error(m._tls_last_error(), "tls client");
14690
+ return new TlsSession(this, m, ptr);
14691
+ } finally {
14692
+ this.m._free(name2);
14693
+ }
14694
+ }
14695
+ verifyInfo(flags2) {
14696
+ const m = this.clientModule();
14697
+ const n = m._tls_verify_info(flags2, this.scratch, SCRATCH);
14698
+ const end = this.m.HEAPU8.indexOf(0, this.scratch);
14699
+ const text = new TextDecoder().decode(this.m.HEAPU8.subarray(this.scratch, end));
14700
+ return n < 0 ? `${text}\u2026` : text;
14701
+ }
14702
+ };
14703
+ function alpnWire(names) {
14704
+ const parts2 = names.map((name2) => new TextEncoder().encode(name2));
14705
+ const out = new Uint8Array(parts2.reduce((n, p) => n + p.length + 1, 0));
14706
+ let at = 0;
14707
+ for (const part of parts2) {
14708
+ out[at++] = part.length;
14709
+ out.set(part, at);
14710
+ at += part.length;
14711
+ }
14712
+ return out;
14713
+ }
14714
+ var TlsStore = class {
14715
+ engine;
14716
+ m;
14717
+ ptr;
14718
+ constructor(engine, m, ptr) {
14719
+ this.engine = engine;
14720
+ this.m = m;
14721
+ this.ptr = ptr;
14722
+ }
14723
+ add(der) {
14724
+ const ret = this.engine.withBytes(der, (p) => this.m._tls_ca_add_der(this.ptr, p, der.length));
14725
+ if (ret !== 0) throw this.engine.error(ret, "trust store certificate");
14726
+ }
14727
+ addBundle(bytes) {
14728
+ const n = this.engine.withBytes(
14729
+ bytes,
14730
+ (p) => this.m._tls_ca_add_bundle(this.ptr, p, bytes.length)
14731
+ );
14732
+ if (n < 0) throw this.engine.error(n, "trust store bundle");
14733
+ return n;
14734
+ }
14735
+ release() {
14736
+ this.m._tls_ca_free(this.ptr);
14737
+ }
14496
14738
  };
14497
14739
  var TlsLeaf = class {
14498
14740
  engine;
@@ -14557,6 +14799,33 @@ var TlsSession = class {
14557
14799
  free() {
14558
14800
  this.m._tls_session_free(this.ptr);
14559
14801
  }
14802
+ get c() {
14803
+ return this.m;
14804
+ }
14805
+ handshake() {
14806
+ const ret = this.c._tls_handshake(this.ptr);
14807
+ if (ret < 0) throw this.engine.error(ret, "tls handshake");
14808
+ return ret === 1;
14809
+ }
14810
+ get verifyResult() {
14811
+ return this.c._tls_verify_result(this.ptr);
14812
+ }
14813
+ get version() {
14814
+ return this.c._tls_version(this.ptr);
14815
+ }
14816
+ get alpn() {
14817
+ const out = this.engine.intoScratch((p, max) => this.c._tls_alpn(this.ptr, p, max));
14818
+ return out instanceof Uint8Array ? new TextDecoder().decode(out) : void 0;
14819
+ }
14820
+ peerChain() {
14821
+ const chain2 = [];
14822
+ const count2 = this.c._tls_peer_count(this.ptr);
14823
+ for (let i = 0; i < count2; i++) {
14824
+ const der = this.engine.intoScratch((p, max) => this.c._tls_peer_der(this.ptr, i, p, max));
14825
+ if (der instanceof Uint8Array) chain2.push(der);
14826
+ }
14827
+ return chain2;
14828
+ }
14560
14829
  };
14561
14830
  var loading = /* @__PURE__ */ new WeakMap();
14562
14831
  function loadTlsEngine(load) {
@@ -14769,6 +15038,16 @@ function packageTlsEngine(fs, modules) {
14769
15038
  return factory.default({ wasmBinary, locateFile: (path) => path });
14770
15039
  };
14771
15040
  }
15041
+ function packageTlsRoots(fs, modules) {
15042
+ const file = `${modules.replace(/\/+$/, "")}/${TLS_ENGINE_PACKAGE}/dist/roots.der`;
15043
+ return async () => {
15044
+ try {
15045
+ return await fs.readFileBuffer(file);
15046
+ } catch {
15047
+ throw new Error(`TLS client sessions need ${TLS_ENGINE_PACKAGE}'s roots.der in ${modules}`);
15048
+ }
15049
+ };
15050
+ }
14772
15051
  function kernelCa(store) {
14773
15052
  return () => realmCa(CA_OWNER, store);
14774
15053
  }
@@ -14800,6 +15079,7 @@ async function writeCaFile(fs, ca, locks = globalThis.navigator?.locks) {
14800
15079
  function enableNetwork(net, options) {
14801
15080
  let proxy;
14802
15081
  const transport = options.transport ?? missingTransport();
15082
+ if (options.roots) net.tlsClient = { engine: options.engine, roots: options.roots };
14803
15083
  const start2 = () => {
14804
15084
  const tls = new TlsTerminator({
14805
15085
  ca: options.ca,
@@ -16579,6 +16859,285 @@ function encodeReceived(got) {
16579
16859
  return out;
16580
16860
  }
16581
16861
 
16862
+ // src/kernel/net/tls-client.ts
16863
+ var WRITE_CHUNK = 16 * 1024;
16864
+ var BADCERT = [
16865
+ [8, "UNABLE_TO_GET_ISSUER_CERT_LOCALLY"],
16866
+ [1, "CERT_HAS_EXPIRED"],
16867
+ [512, "CERT_NOT_YET_VALID"],
16868
+ [2, "CERT_REVOKED"],
16869
+ [4, "ERR_TLS_CERT_ALTNAME_INVALID"],
16870
+ [2048, "INVALID_PURPOSE"],
16871
+ [4096, "INVALID_PURPOSE"]
16872
+ ];
16873
+ function verifyCode(flags2) {
16874
+ if (flags2 === 0) return void 0;
16875
+ if (flags2 === -1) return "UNABLE_TO_VERIFY_LEAF_SIGNATURE";
16876
+ return BADCERT.find(([bit]) => (flags2 & bit) !== 0)?.[1] ?? "UNABLE_TO_VERIFY_LEAF_SIGNATURE";
16877
+ }
16878
+ var Ciphertext = class {
16879
+ queue = [];
16880
+ ended = false;
16881
+ conn;
16882
+ session;
16883
+ constructor(conn, session) {
16884
+ this.conn = conn;
16885
+ this.session = session;
16886
+ }
16887
+ hand(bytes) {
16888
+ if (bytes.length > 0) this.queue.push(bytes);
16889
+ }
16890
+ async more() {
16891
+ if (this.queue.length === 0 && !this.ended) {
16892
+ const bytes = await this.conn.read();
16893
+ if (bytes) this.queue.push(bytes);
16894
+ else this.ended = true;
16895
+ }
16896
+ if (this.queue.length === 0) {
16897
+ this.session.feedEnd();
16898
+ return false;
16899
+ }
16900
+ while (this.queue.length > 0) {
16901
+ const head = this.queue[0];
16902
+ const n = this.session.feed(head);
16903
+ if (n < head.length) {
16904
+ this.queue[0] = head.subarray(n);
16905
+ break;
16906
+ }
16907
+ this.queue.shift();
16908
+ }
16909
+ return true;
16910
+ }
16911
+ };
16912
+ async function send(conn, session) {
16913
+ for (; ; ) {
16914
+ const out = session.take();
16915
+ if (out.length === 0) return;
16916
+ for (let at = 0; at < out.length; ) {
16917
+ const n = await conn.write(out.subarray(at));
16918
+ if (!(n > 0)) throw new KernelError("EPIPE");
16919
+ at += n;
16920
+ }
16921
+ }
16922
+ }
16923
+ function refused2(engine, session, err) {
16924
+ const flags2 = session.verifyResult;
16925
+ const code = verifyCode(flags2);
16926
+ if (code && flags2 !== -1)
16927
+ return new KernelError("EPROTO", `${code}: ${engine.verifyInfo(flags2).trim()}`);
16928
+ const text = err instanceof TlsError ? err.message : String(err);
16929
+ return new KernelError("EPROTO", `ERR_SSL_HANDSHAKE_FAILURE: ${text}`);
16930
+ }
16931
+ async function handshake(conn, o, session, inbox) {
16932
+ for (; ; ) {
16933
+ let done4;
16934
+ try {
16935
+ done4 = session.handshake();
16936
+ } catch (err) {
16937
+ await send(conn, session).catch(() => void 0);
16938
+ throw refused2(o.engine, session, err);
16939
+ }
16940
+ await send(conn, session);
16941
+ if (done4) return;
16942
+ if (!await inbox.more()) {
16943
+ throw new KernelError(
16944
+ "ECONNRESET",
16945
+ "the server closed the connection during the TLS handshake"
16946
+ );
16947
+ }
16948
+ }
16949
+ }
16950
+ function infoOf(o, session) {
16951
+ const flags2 = session.verifyResult;
16952
+ const code = verifyCode(flags2);
16953
+ return {
16954
+ protocol: session.version === 772 ? "TLSv1.3" : "TLSv1.2",
16955
+ alpnProtocol: session.alpn ?? false,
16956
+ authorized: code === void 0,
16957
+ ...code ? { authorizationError: code, authorizationText: o.engine.verifyInfo(flags2).trim() } : {},
16958
+ peerCertificates: session.peerChain()
16959
+ };
16960
+ }
16961
+ function plaintext(conn, session, inbox) {
16962
+ let freed = false;
16963
+ let writeClosed = false;
16964
+ const free = () => {
16965
+ if (freed) return;
16966
+ freed = true;
16967
+ session.free();
16968
+ };
16969
+ return {
16970
+ localAddr: conn.localAddr,
16971
+ remoteAddr: conn.remoteAddr,
16972
+ async read() {
16973
+ for (; ; ) {
16974
+ if (freed) return null;
16975
+ const got = session.read();
16976
+ await send(conn, session);
16977
+ if (got instanceof Uint8Array) return got;
16978
+ if (got === "eof") return null;
16979
+ await inbox.more();
16980
+ }
16981
+ },
16982
+ async write(bytes) {
16983
+ if (freed) throw new KernelError("EPIPE");
16984
+ for (; ; ) {
16985
+ const n = session.write(bytes.subarray(0, WRITE_CHUNK));
16986
+ await send(conn, session);
16987
+ if (n > 0) return n;
16988
+ }
16989
+ },
16990
+ closeWrite() {
16991
+ if (writeClosed || freed) return;
16992
+ writeClosed = true;
16993
+ session.close();
16994
+ void send(conn, session).catch(() => void 0).finally(() => conn.closeWrite());
16995
+ },
16996
+ close() {
16997
+ free();
16998
+ conn.close();
16999
+ }
17000
+ };
17001
+ }
17002
+ async function tlsClient(conn, o, taken = new Uint8Array(0)) {
17003
+ const flags2 = o.insecure ? TLS_CLIENT_INSECURE_SKIP_VERIFY : 0;
17004
+ const session = o.engine.clientSession(o.store, o.servername, o.alpn, flags2);
17005
+ const inbox = new Ciphertext(conn, session);
17006
+ inbox.hand(taken);
17007
+ try {
17008
+ await handshake(conn, o, session, inbox);
17009
+ return { conn: plaintext(conn, session, inbox), info: infoOf(o, session) };
17010
+ } catch (err) {
17011
+ session.free();
17012
+ throw err;
17013
+ }
17014
+ }
17015
+
17016
+ // src/kernel/net/tls-uplink.ts
17017
+ var isIP = (text) => ipv4Bytes(text) !== void 0 || text.includes(":") && ipv6Groups(text) !== void 0;
17018
+ var LABEL2 = /^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/;
17019
+ function serverName(name2) {
17020
+ if (isIP(name2.replace(/^\[|\]$/g, ""))) return name2.replace(/^\[|\]$/g, "");
17021
+ const bare = name2.endsWith(".") ? name2.slice(0, -1) : name2;
17022
+ if (bare.length === 0 || bare.length > 253 || !bare.split(".").every((l) => LABEL2.test(l))) {
17023
+ throw new KernelError(
17024
+ "EINVAL",
17025
+ `ERR_INVALID_ARG_VALUE: not a host name: ${JSON.stringify(name2)}`
17026
+ );
17027
+ }
17028
+ return name2;
17029
+ }
17030
+ var defaults = /* @__PURE__ */ new WeakMap();
17031
+ function defaultStore(engine, roots) {
17032
+ let store = defaults.get(engine);
17033
+ if (!store) {
17034
+ const made2 = roots().then((bundle) => {
17035
+ const s = engine.store();
17036
+ s.addBundle(bundle);
17037
+ return s;
17038
+ });
17039
+ store = made2;
17040
+ defaults.set(engine, made2);
17041
+ made2.catch(() => {
17042
+ if (defaults.get(engine) === made2) defaults.delete(engine);
17043
+ });
17044
+ }
17045
+ return store;
17046
+ }
17047
+ function base64Der(text) {
17048
+ const bin = atob(text);
17049
+ const out = new Uint8Array(bin.length);
17050
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
17051
+ return out;
17052
+ }
17053
+ function encode(bytes) {
17054
+ let bin = "";
17055
+ for (const b of bytes) bin += String.fromCharCode(b);
17056
+ return btoa(bin);
17057
+ }
17058
+ function sessionOf(info, servername) {
17059
+ return {
17060
+ path: "kernel",
17061
+ substitutes: false,
17062
+ protocol: info.protocol,
17063
+ alpnProtocol: info.alpnProtocol,
17064
+ authorized: info.authorized,
17065
+ ...info.authorizationError ? {
17066
+ authorizationError: info.authorizationError,
17067
+ authorizationText: info.authorizationText
17068
+ } : {},
17069
+ servername,
17070
+ peerCertificates: info.peerCertificates.map(encode)
17071
+ };
17072
+ }
17073
+ async function setUp(support, req) {
17074
+ const engine = await support.engine();
17075
+ if (!engine.client)
17076
+ throw new KernelError("ENOTSUP", "the installed tls engine has no client sessions");
17077
+ const custom = Array.isArray(req.ca) ? req.ca : void 0;
17078
+ if (!custom) return { engine, store: await defaultStore(engine, support.roots), own: void 0 };
17079
+ if (custom.length === 0)
17080
+ throw new KernelError("EINVAL", "ERR_INVALID_ARG_VALUE: ca has no certificate");
17081
+ const own = engine.store();
17082
+ try {
17083
+ for (const der of custom) own.add(base64Der(der));
17084
+ } catch (err) {
17085
+ own.release();
17086
+ throw new KernelError("EINVAL", `ERR_INVALID_ARG_VALUE: ca: ${err.message}`);
17087
+ }
17088
+ return { engine, store: own, own };
17089
+ }
17090
+ function secure(support, req, servername) {
17091
+ return async (raw) => {
17092
+ const { engine, store, own } = await setUp(support, req);
17093
+ try {
17094
+ return await tlsClient(raw, {
17095
+ engine,
17096
+ store,
17097
+ servername,
17098
+ alpn: req.alpn ?? [],
17099
+ insecure: req.insecure === true
17100
+ });
17101
+ } finally {
17102
+ own?.release();
17103
+ }
17104
+ };
17105
+ }
17106
+ function supportOf(net) {
17107
+ const support = net.tlsClient;
17108
+ if (!support) throw new KernelError("ENOTSUP", "no tls engine for client sessions");
17109
+ return support;
17110
+ }
17111
+ async function uplinkAddress(proc, host) {
17112
+ const bare = host.replace(/^\[|\]$/g, "");
17113
+ if (isIP(bare)) return bare;
17114
+ const [first] = await proc.resolve(host, 0, () => proc.blocking());
17115
+ if (!first) throw new KernelError("ENOENT", `ENOTFOUND: ${host}`);
17116
+ return first;
17117
+ }
17118
+ async function connectSecure(proc, socket, host, port, req) {
17119
+ const servername = serverName(req.servername || host);
17120
+ if (isLoopbackHost(servername) || isLoopbackHost(host)) throw new KernelError("ENOTSUP");
17121
+ const address = await uplinkAddress(proc, host);
17122
+ const route = proc.net.uplinkFor(address);
17123
+ if (!route)
17124
+ throw new KernelError("ENOTSUP", "TLS in the kernel needs a destination the uplink routes");
17125
+ const support = supportOf(proc.net);
17126
+ let info;
17127
+ const make = secure(support, req, servername);
17128
+ await socket.connectSecure({ family: "inet", host: address, port }, route, async (conn) => {
17129
+ info = await conn.upgrade(make);
17130
+ });
17131
+ return sessionOf(info, servername);
17132
+ }
17133
+ async function upgradeSecure(proc, socket, req) {
17134
+ const peer = socket.peer;
17135
+ const host = req.servername || (peer?.family === "inet" ? peer.host : "");
17136
+ const servername = serverName(host);
17137
+ const info = await socket.upgradeSecure(secure(supportOf(proc.net), req, servername));
17138
+ return sessionOf(info, servername);
17139
+ }
17140
+
16582
17141
  // src/kernel/unix-dgram.ts
16583
17142
  var SOL_SOCKET3 = 1;
16584
17143
  var SO_TYPE3 = 3;
@@ -16740,7 +17299,8 @@ var SOCKET_OPS = [
16740
17299
  "sock-resolve",
16741
17300
  "sock-sendto",
16742
17301
  "sock-recvfrom",
16743
- "sock-tls"
17302
+ "sock-tls",
17303
+ "sock-tls-upgrade"
16744
17304
  ];
16745
17305
  function socketAt(fds, fd) {
16746
17306
  const file = anySocketAt(fds, fd);
@@ -16813,7 +17373,9 @@ async function socketSyscall(req, proc) {
16813
17373
  return ok3(addresses);
16814
17374
  }
16815
17375
  case "sock-tls":
16816
- return ok3(tlsOverTransport(req, proc));
17376
+ return ok3(await secureConnect(req, proc));
17377
+ case "sock-tls-upgrade":
17378
+ return ok3(await upgradeSecure(proc, socketAt(fds, req.fd), req));
16817
17379
  default:
16818
17380
  return datagram(req, proc);
16819
17381
  }
@@ -16935,6 +17497,36 @@ var NOT_HTTP_PORTS = /* @__PURE__ */ new Set([
16935
17497
  8883
16936
17498
  ]);
16937
17499
  var HOST_NAME = /^[A-Za-z0-9.-]+$|^\[?[0-9A-Fa-f:.]+\]?$/;
17500
+ function wantsKernel(req) {
17501
+ if (req.path === "kernel") return true;
17502
+ if (req.path === "transport") return false;
17503
+ return Array.isArray(req.ca) || req.alpn !== void 0 && req.alpn.length > 0 && !req.alpn.includes("http/1.1") || NOT_HTTP_PORTS.has(req.port);
17504
+ }
17505
+ async function secureConnect(req, proc) {
17506
+ if (!Number.isInteger(req.port) || req.port < 1 || req.port > 65535)
17507
+ throw new KernelError("EINVAL");
17508
+ const kernelPath = wantsKernel(req) && await uplinked(proc, req.host);
17509
+ if (!kernelPath) {
17510
+ if (req.path === "kernel" || Array.isArray(req.ca)) throw new KernelError("ENOTSUP");
17511
+ return { ...tlsOverTransport(req, proc), path: "transport", substitutes: true };
17512
+ }
17513
+ const socket = proc.net.socket("inet");
17514
+ const fd = proc.fds.install(new OpenFile(socket), 3);
17515
+ try {
17516
+ return { fd, ...await connectSecure(proc, socket, req.host, req.port, req) };
17517
+ } catch (e) {
17518
+ await Promise.resolve(proc.fds.close(fd));
17519
+ throw e;
17520
+ }
17521
+ }
17522
+ async function uplinked(proc, host) {
17523
+ if (!proc.net.tlsClient || isLoopbackHost(host)) return false;
17524
+ try {
17525
+ return proc.net.uplinkFor(await uplinkAddress(proc, host)) !== void 0;
17526
+ } catch {
17527
+ return false;
17528
+ }
17529
+ }
16938
17530
  function tlsOverTransport(req, proc) {
16939
17531
  if (req.ca) throw new KernelError("ENOTSUP");
16940
17532
  if (req.alpn && req.alpn.length > 0 && !req.alpn.includes("http/1.1")) {
@@ -19935,10 +20527,10 @@ var JobTable = class {
19935
20527
  signalForeground(tty, fallback, sig) {
19936
20528
  this.killGroup(this.tcgetpgrp(tty, fallback), sig);
19937
20529
  }
19938
- fromKeyboard(send) {
20530
+ fromKeyboard(send2) {
19939
20531
  this.keyboard = true;
19940
20532
  try {
19941
- send();
20533
+ send2();
19942
20534
  } finally {
19943
20535
  this.keyboard = false;
19944
20536
  }
@@ -20249,6 +20841,12 @@ var LockService = class {
20249
20841
  lock(pid, path, exclusive, fd) {
20250
20842
  return this.table.lock(pid, path, exclusive, fd);
20251
20843
  }
20844
+ wholeFree(pid, path, exclusive) {
20845
+ return this.table.wholeFree(pid, path, exclusive);
20846
+ }
20847
+ flockFree(key, owner, kind) {
20848
+ return this.table.flockFree(key, owner, kind);
20849
+ }
20252
20850
  unlock(pid, path) {
20253
20851
  this.table.unlock(pid, path);
20254
20852
  }
@@ -20924,7 +21522,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
20924
21522
  await changed(signal);
20925
21523
  }
20926
21524
  };
20927
- const send = async (out, signal) => {
21525
+ const send2 = async (out, signal) => {
20928
21526
  const write = file.write;
20929
21527
  for (let at = 0; at < out.length; ) {
20930
21528
  try {
@@ -20959,7 +21557,7 @@ function scrubbed(inner, scrubber, idleMs = SCRUB_IDLE_MS) {
20959
21557
  raise();
20960
21558
  if (timer !== void 0) clearTimeout(timer);
20961
21559
  timer = void 0;
20962
- await send(stream.push(taken), signal);
21560
+ await send2(stream.push(taken), signal);
20963
21561
  } finally {
20964
21562
  busy = false;
20965
21563
  if (quiet2()) wake();
@@ -21305,19 +21903,19 @@ var SettlingChildren = class {
21305
21903
  this.held = this.held.filter((h) => this.blocking(h.pgid));
21306
21904
  for (const h of ready2) h.send();
21307
21905
  }
21308
- deliver(sig, pgid, send, foreground) {
21906
+ deliver(sig, pgid, send2, foreground) {
21309
21907
  if (!KEY_SIGNALS.has(sig)) {
21310
- send();
21908
+ send2();
21311
21909
  } else if (this.blocking(pgid)) {
21312
- this.held.push({ pgid, send });
21910
+ this.held.push({ pgid, send: send2 });
21313
21911
  } else if (foreground) {
21314
- send();
21912
+ send2();
21315
21913
  const moved2 = () => {
21316
- if (foreground() !== pgid) send();
21914
+ if (foreground() !== pgid) send2();
21317
21915
  };
21318
21916
  this.parked.push({ pgid, send: moved2 });
21319
21917
  } else {
21320
- send();
21918
+ send2();
21321
21919
  }
21322
21920
  }
21323
21921
  blocking(pgid) {
@@ -21462,9 +22060,9 @@ function serveFilesystem(port, handlers, capabilities = {}, options = {}) {
21462
22060
  let open = false;
21463
22061
  const reply = (message3, transfer = []) => port.postMessage(message3, transfer);
21464
22062
  async function hello(message3) {
21465
- const refused2 = driverVersionError(message3.protocol);
21466
- if (refused2) {
21467
- reply({ hello: { protocol: DRIVER_PROTOCOL, error: refused2, errno: "EPROTO" } });
22063
+ const refused3 = driverVersionError(message3.protocol);
22064
+ if (refused3) {
22065
+ reply({ hello: { protocol: DRIVER_PROTOCOL, error: refused3, errno: "EPROTO" } });
21468
22066
  return;
21469
22067
  }
21470
22068
  try {
@@ -23533,9 +24131,9 @@ function interpreter(head) {
23533
24131
  if (words2[0] === "-S") words2.shift();
23534
24132
  return baseName2(words2[0] ?? "");
23535
24133
  }
23536
- function expandDefaults(defaults, env) {
24134
+ function expandDefaults(defaults2, env) {
23537
24135
  const out = {};
23538
- for (const [key, value2] of Object.entries(defaults ?? {})) {
24136
+ for (const [key, value2] of Object.entries(defaults2 ?? {})) {
23539
24137
  let missing4 = false;
23540
24138
  const expanded = value2.replace(ENV_REFERENCE, (_, name2) => {
23541
24139
  const set3 = Object.hasOwn(env, name2) ? env[name2] : void 0;
@@ -23785,6 +24383,7 @@ var Launcher = class {
23785
24383
  enableNetwork(this.net, {
23786
24384
  transport: this.transport,
23787
24385
  engine: kernelTlsEngine(packageTlsEngine(this.verifiedFs(options.fs), this.modulesDir)),
24386
+ roots: packageTlsRoots(this.verifiedFs(options.fs), this.modulesDir),
23788
24387
  ca: this.ca
23789
24388
  });
23790
24389
  enableCdp(this.net, this.cdp);
@@ -24197,13 +24796,13 @@ var Launcher = class {
24197
24796
  if (planned?.target.copy) await need(g, "exec", planned.target.copy, R_OK | X_OK);
24198
24797
  }
24199
24798
  async checkedPlan(req, { ppid, cred, scope }, fds) {
24200
- const refused2 = async (err) => {
24799
+ const refused3 = async (err) => {
24201
24800
  await fds.closeAll();
24202
24801
  throw err.code === "EACCES" ? new SpawnError("EACCES") : err;
24203
24802
  };
24204
- const file = await this.execFile(req.file, req.cwd, this.execGuard(cred, ppid)).catch(refused2);
24803
+ const file = await this.execFile(req.file, req.cwd, this.execGuard(cred, ppid)).catch(refused3);
24205
24804
  const planned = await this.plan(file, req.argv, req.cwd, scope, req.argv0);
24206
- await this.mayExec(cred, { ...req, file, pid: ppid }, planned).catch(refused2);
24805
+ await this.mayExec(cred, { ...req, file, pid: ppid }, planned).catch(refused3);
24207
24806
  if (planned) return planned;
24208
24807
  await fds.closeAll();
24209
24808
  throw new SpawnError(await this.unrunnable(file, req.cwd, scope));
@@ -25038,10 +25637,10 @@ var Launcher = class {
25038
25637
  return childHandle(await this.admitted(parent.program.abi !== "js", given, fresh2));
25039
25638
  };
25040
25639
  }
25041
- keySignal(tty, fallback, sig, send) {
25640
+ keySignal(tty, fallback, sig, send2) {
25042
25641
  const pgid = this.jobs.tcgetpgrp(tty, fallback);
25043
25642
  const foreground = () => this.jobs.tcgetpgrp(tty, fallback);
25044
- const keyed = () => this.jobs.fromKeyboard(send);
25643
+ const keyed = () => this.jobs.fromKeyboard(send2);
25045
25644
  this.settling.deliver(sig, pgid, keyed, tty.reading ? void 0 : foreground);
25046
25645
  }
25047
25646
  async resolvePrefixes() {