@amritk/nish-x86_64-linux 0.38.0 → 0.40.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.
Files changed (86) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +455 -65
  4. package/package.json +1 -1
  5. package/runtime/core/host.d.ts +11 -0
  6. package/runtime/core/host.mjs +35 -0
  7. package/runtime/nish.d.ts +320 -33
  8. package/runtime/nish.h +84 -10
  9. package/runtime/nish.mjs +69 -6
  10. package/runtime/node.mjs +117 -0
  11. package/runtime/page-frame.d.ts +123 -0
  12. package/runtime/page-frame.mjs +736 -0
  13. package/runtime/page-game.d.ts +132 -0
  14. package/runtime/page-game.mjs +738 -0
  15. package/runtime/runtime-aes.c +97 -12
  16. package/runtime/runtime-async.c +43 -10
  17. package/runtime/runtime-bytes.c +88 -4
  18. package/runtime/runtime-checksum.c +207 -15
  19. package/runtime/runtime-net.c +64 -3
  20. package/runtime/runtime-os.c +174 -27
  21. package/runtime/runtime-region.c +94 -10
  22. package/runtime/runtime-sandbox.c +404 -17
  23. package/runtime/runtime-sha256.c +11 -4
  24. package/runtime/runtime-wasm.c +437 -0
  25. package/runtime/runtime.c +5 -0
  26. package/runtime/vite.mjs +1 -1
  27. package/scripts/build.sh +42 -8
  28. package/std/README.md +78 -91
  29. package/std/array.ts +36 -3
  30. package/std/collections.ts +51 -0
  31. package/std/compress/checksum.ts +13 -0
  32. package/std/compress/deflate.ts +0 -2
  33. package/std/crypto/hmac.ts +37 -10
  34. package/std/crypto/p256.ts +1629 -2732
  35. package/std/crypto/p384.ts +3 -1
  36. package/std/crypto/pki.ts +151 -13
  37. package/std/crypto/sha256.ts +34 -6
  38. package/std/crypto/x25519.ts +153 -64
  39. package/std/crypto/x509.ts +120 -10
  40. package/std/host/game.ts +273 -0
  41. package/std/input.ts +56 -0
  42. package/std/json-tokenizer.ts +344 -111
  43. package/std/json-typed.ts +256 -12
  44. package/std/json-value.ts +144 -3
  45. package/std/json.ts +63 -8
  46. package/std/net/fetch.ts +22 -4
  47. package/std/net/handler.ts +130 -16
  48. package/std/net/http-server.ts +3382 -0
  49. package/std/net/http1-client-codec.ts +6 -2
  50. package/std/net/http1-codec.ts +636 -162
  51. package/std/net/http1-server.ts +569 -42
  52. package/std/net/http2-cleartext.ts +526 -0
  53. package/std/net/http2-tls.ts +48 -0
  54. package/std/net/http2.ts +131 -14
  55. package/std/net/http3-server.ts +29 -3
  56. package/std/net/http3.ts +180 -7
  57. package/std/net/postgres-async.ts +1304 -86
  58. package/std/net/postgres-carrier.ts +343 -10
  59. package/std/net/postgres.ts +122 -7
  60. package/std/net/prefork.ts +195 -11
  61. package/std/net/quic-datagram.ts +30 -0
  62. package/std/net/quic-listener.ts +38 -12
  63. package/std/net/quic-packet.ts +19 -6
  64. package/std/net/quic-recovery.ts +373 -27
  65. package/std/net/quic-stream.ts +195 -37
  66. package/std/net/quic.ts +516 -22
  67. package/std/net/router.ts +407 -38
  68. package/std/net/serve.ts +1022 -110
  69. package/std/net/tls/codec.ts +110 -32
  70. package/std/net/tls/record-server.ts +37 -7
  71. package/std/net/tls/verify.ts +19 -1
  72. package/std/net/tls-tcp.ts +56 -1
  73. package/std/net/tls.ts +196 -50
  74. package/std/net/url.ts +83 -35
  75. package/std/net/websocket.ts +129 -19
  76. package/std/net/webtransport.ts +185 -1
  77. package/std/raster.ts +837 -0
  78. package/std/regex.ts +69 -47
  79. package/std/region.ts +62 -11
  80. package/std/release.ts +593 -0
  81. package/std/secret.ts +26 -59
  82. package/std/synth.ts +143 -0
  83. package/std/text.ts +233 -0
  84. package/std/threads.ts +298 -0
  85. package/std/yaml-json.ts +368 -28
  86. package/std/yaml.ts +122 -27
@@ -75,6 +75,19 @@
75
75
  * that the workers run unpinned, and the listeners are plain `SO_REUSEPORT`
76
76
  * ones. Both are off by default.
77
77
  *
78
+ * **QUIC.** `listenUdp`, with `listenPort`, binds one UDP socket per worker
79
+ * on the same port before the TCP listeners, held like them, as a group the
80
+ * kernel steers by connection ID (`udpBind` flag 4): a datagram whose
81
+ * destination ID starts with byte k reaches worker k. Worker k reads its
82
+ * socket with `preforkUdpListener(args)` and the group's size N with
83
+ * `preforkUdpCount(args)` (`--nish-prefork-udp=<fd>,<N>`, before the listener
84
+ * flag), and sets `QuicServerConfig.workerIndex` to k and `.workerCount` to N
85
+ * so every ID it issues starts with k. A connection then stays with its
86
+ * worker when the client's address or port changes. More than 255 workers
87
+ * panics; where the kernel refuses the steering (off Linux, or under a
88
+ * seccomp profile that refuses it) the supervisor says so on stderr and runs
89
+ * one worker.
90
+ *
78
91
  * **How many.** `NISH_WORKERS` when it is a positive whole number, else
79
92
  * `PreforkConfig.workers` when that is positive, else
80
93
  * `availableParallelism()` on Linux and 1 elsewhere: Darwin shares a
@@ -113,6 +126,7 @@ import {
113
126
  pollCreate,
114
127
  pollWait,
115
128
  tcpListenFlags,
129
+ udpBind,
116
130
  unixSocketPair,
117
131
  } from "nish:net"
118
132
  import {
@@ -144,6 +158,12 @@ export const PREFORK_CHANNELS_FLAG: string = "--nish-prefork-channels="
144
158
  * descriptor.
145
159
  */
146
160
  export const PREFORK_LISTENER_FLAG: string = "--nish-prefork-listener="
161
+ /**
162
+ * The flag that hands a worker its UDP socket and the size of the steered
163
+ * group, `<fd>,<N>`, before the listener flag, when `listenUdp` is on: read
164
+ * it with `preforkUdpListener` and `preforkUdpCount`.
165
+ */
166
+ export const PREFORK_UDP_FLAG: string = "--nish-prefork-udp="
147
167
 
148
168
  /** What `preforkWith` answers in the supervisor once its workers are gone. */
149
169
  export const PREFORK_STOPPED: i32 = -1
@@ -206,6 +226,16 @@ export class PreforkConfig {
206
226
  * a connection received past the listeners falls back to the kernel's hash.
207
227
  */
208
228
  pin: boolean = false
229
+ /**
230
+ * With `listenPort`, also bind one UDP socket per worker on the same port,
231
+ * before the TCP listeners, as a group the kernel steers by QUIC
232
+ * connection ID (`udpBind` flag 4): a datagram goes to worker k when byte 0
233
+ * of its destination connection ID is k, so a QUIC connection stays with
234
+ * the worker that issued its IDs when the client's address changes. Linux
235
+ * only, and at most 255 workers (more panics). Where the kernel refuses
236
+ * the steering, the supervisor says so on stderr and runs one worker.
237
+ */
238
+ listenUdp: boolean = false
209
239
  }
210
240
 
211
241
  /** True when `s` is one or more ASCII digits and nothing else. */
@@ -270,8 +300,8 @@ export const preforkIndex = (args: string[]): i32 => {
270
300
  }
271
301
 
272
302
  /**
273
- * `args` (`process.argv`) without the worker flag and the channels and
274
- * listener flags before it, the same in every process.
303
+ * `args` (`process.argv`) without the worker flag and the channels,
304
+ * listener and UDP flags before it, the same in every process.
275
305
  *
276
306
  * @param args the process's arguments, `process.argv`
277
307
  * @returns a new list of the arguments the user gave, without the flags the
@@ -287,6 +317,9 @@ export const preforkArgs = (args: string[]): string[] => {
287
317
  if (keep > 1 && args[keep - 1].startsWith(PREFORK_LISTENER_FLAG)) {
288
318
  keep = keep - 1
289
319
  }
320
+ if (keep > 1 && args[keep - 1].startsWith(PREFORK_UDP_FLAG)) {
321
+ keep = keep - 1
322
+ }
290
323
  }
291
324
  const out: string[] = []
292
325
  for (let i: i32 = 0; i < toI32(args.length); i++) {
@@ -368,6 +401,106 @@ export const preforkListener = (args: string[]): i32 => {
368
401
  return -1
369
402
  }
370
403
 
404
+ /** The most workers a steered UDP group may have: the steering reads one byte. */
405
+ const PREFORK_UDP_MAX: i32 = 255
406
+
407
+ /**
408
+ * Field `at` (0 the descriptor, 1 the count) of a worker's well-formed UDP
409
+ * flag, `<fd>,<N>` with N from 1 to `PREFORK_UDP_MAX`; -1 without one.
410
+ */
411
+ const preforkUdpField = (args: string[], at: i32): i32 => {
412
+ if (preforkIndex(args) < 0) {
413
+ return -1
414
+ }
415
+ for (let back: i32 = 2; back <= 4 && back < toI32(args.length); back++) {
416
+ const flag: string = args[toI32(args.length) - back]
417
+ if (flag.startsWith(PREFORK_UDP_FLAG)) {
418
+ const value: string = flag.substring(PREFORK_UDP_FLAG.length)
419
+ const comma: i32 = toI32(value.indexOf(","))
420
+ const fd: string = comma < 0 ? "" : value.slice(0, comma)
421
+ const size: string = comma < 0 ? "" : value.slice(comma + 1)
422
+ if (!preforkDigits(fd) || !preforkDigits(size)) {
423
+ return -1
424
+ }
425
+ const count: i32 = parseInt(size)
426
+ if (count < 1 || count > PREFORK_UDP_MAX) {
427
+ return -1
428
+ }
429
+ return at === 0 ? parseInt(fd) : count
430
+ }
431
+ }
432
+ return -1
433
+ }
434
+
435
+ /**
436
+ * In a worker, the UDP socket the supervisor bound for it (`listenUdp`); -1
437
+ * when none, or when the flag is not the supervisor's `<fd>,<N>`.
438
+ *
439
+ * @param args the worker's arguments, `process.argv`
440
+ * @returns the bound UDP socket's descriptor to serve QUIC on, or -1
441
+ */
442
+ export const preforkUdpListener = (args: string[]): i32 => preforkUdpField(args, 0)
443
+
444
+ /**
445
+ * In a worker, how many workers share its steered UDP port (`listenUdp`): the
446
+ * `QuicServerConfig.workerCount` to pair with `preforkIndex` as its
447
+ * `workerIndex`. 0 exactly when `preforkUdpListener` answers -1.
448
+ *
449
+ * @param args the worker's arguments, `process.argv`
450
+ * @returns the group's size, 1 to 255, or 0 without a UDP socket
451
+ */
452
+ export const preforkUdpCount = (args: string[]): i32 => {
453
+ const count: i32 = preforkUdpField(args, 1)
454
+ return count > 0 ? count : 0
455
+ }
456
+
457
+ /**
458
+ * The UDP group of `listenUdp`, socket i for worker i, bound before anything
459
+ * else on the port: steered by connection ID (`udpBind` flag 4 with the count
460
+ * in bits 8 to 15) for more than one worker. When the kernel refuses the
461
+ * steering, one plain socket and a line on stderr, so the supervisor runs one
462
+ * worker; empty, with a line on stderr and nothing left bound, when even that
463
+ * cannot bind.
464
+ */
465
+ const preforkBindUdp = (config: PreforkConfig, count: i32): i32[] => {
466
+ const host: string = config.listenHost
467
+ const out: i32[] = []
468
+ // Flag 1 (SO_REUSEPORT) and 4 (steer), the group's size in bits 8 to 15.
469
+ const steered: i32 = (count << 8) | 4 | 1
470
+ const first: i32 = udpBind(host, config.listenPort, count > 1 ? steered : 1)
471
+ if (first < 0 && count > 1) {
472
+ const plain: i32 = udpBind(host, config.listenPort, 1)
473
+ if (plain >= 0) {
474
+ console.error(`nish/net/prefork: QUIC steering refused (${first}), running one worker`)
475
+ out.push(plain)
476
+ return out
477
+ }
478
+ }
479
+ if (first < 0) {
480
+ console.error(`nish/net/prefork: cannot bind UDP ${host}:${config.listenPort} (${first})`)
481
+ return out
482
+ }
483
+ out.push(first)
484
+ const port: i32 = config.listenPort === 0 ? netLocalPort(first) : config.listenPort
485
+ if (port <= 0) {
486
+ console.error(`nish/net/prefork: cannot read the UDP port bound (${port})`)
487
+ netClose(first)
488
+ return []
489
+ }
490
+ for (let i: i32 = 1; i < count; i++) {
491
+ const fd: i32 = udpBind(host, port, steered)
492
+ if (fd < 0) {
493
+ console.error(`nish/net/prefork: cannot bind UDP ${host}:${port} (${fd})`)
494
+ for (let j: i32 = 0; j < toI32(out.length); j++) {
495
+ netClose(out[j])
496
+ }
497
+ return []
498
+ }
499
+ out.push(fd)
500
+ }
501
+ return out
502
+ }
503
+
371
504
  /** Milliseconds on the monotonic clock. */
372
505
  const preforkNowMs = (): i64 => monotonicNanos() / 1000000
373
506
 
@@ -449,6 +582,11 @@ class PreforkSupervisor {
449
582
  private cascading: boolean = false
450
583
  /** Worker i's listener at i, held for the whole run; empty without `listenPort`. */
451
584
  private listeners: i32[]
585
+ /**
586
+ * Worker i's UDP socket at i, held for the whole run so its index in the
587
+ * steered group never moves; empty without `listenUdp`.
588
+ */
589
+ private udp: i32[]
452
590
 
453
591
  /**
454
592
  * A supervisor with one empty slot per worker and no worker started yet.
@@ -459,10 +597,13 @@ class PreforkSupervisor {
459
597
  * @param count how many workers to keep running
460
598
  * @param loop the readiness loop each supervisor channel is added to; the
461
599
  * caller owns and closes it
600
+ * @param udp the UDP group `preforkBindUdp` bound, one per worker, kept and
601
+ * closed with the listeners; empty without `listenUdp`
462
602
  */
463
- constructor(config: PreforkConfig, args: string[], count: i32, loop: i32) {
603
+ constructor(config: PreforkConfig, args: string[], count: i32, loop: i32, udp: i32[]) {
464
604
  this.config = config
465
605
  this.loop = loop
606
+ this.udp = udp
466
607
  this.service = config.serviceWorker
467
608
  this.toService = []
468
609
  this.fromWorkers = []
@@ -522,6 +663,10 @@ class PreforkSupervisor {
522
663
  argv.push(this.args[i])
523
664
  }
524
665
  const channels: boolean = fds.length > 0
666
+ if (this.udp.length > 0) {
667
+ fds.push(this.udp[index])
668
+ argv.push(`${PREFORK_UDP_FLAG}${2 + fds.length},${this.udp.length}`)
669
+ }
525
670
  if (this.listeners.length > 0) {
526
671
  fds.push(this.listeners[index])
527
672
  argv.push(`${PREFORK_LISTENER_FLAG}${2 + fds.length}`)
@@ -764,7 +909,14 @@ class PreforkSupervisor {
764
909
  listen(steer: boolean): boolean {
765
910
  const config: PreforkConfig = this.config
766
911
  const flags: i32 = config.listenFlags | 1 | (steer ? 4 : 0)
767
- let port: i32 = config.listenPort
912
+ // With `listenUdp`, port 0 was chosen by the UDP group, bound first.
913
+ let port: i32 =
914
+ config.listenPort === 0 && this.udp.length > 0 ? netLocalPort(this.udp[0]) : config.listenPort
915
+ if (config.listenPort === 0 && this.udp.length > 0 && port <= 0) {
916
+ console.error(`nish/net/prefork: cannot read the UDP port bound (${port})`)
917
+ this.closeListeners()
918
+ return false
919
+ }
768
920
  for (let i: i32 = 0; i < toI32(this.slots.length); i++) {
769
921
  const fd: i32 = tcpListenFlags(config.listenHost, port, config.listenBacklog, flags)
770
922
  if (fd < 0) {
@@ -790,6 +942,10 @@ class PreforkSupervisor {
790
942
  netClose(this.listeners[i])
791
943
  }
792
944
  this.listeners = []
945
+ for (let i: i32 = 0; i < toI32(this.udp.length); i++) {
946
+ netClose(this.udp[i])
947
+ }
948
+ this.udp = []
793
949
  }
794
950
 
795
951
  /** Send `sig` to every running worker. */
@@ -871,6 +1027,9 @@ const preforkInvalid = (config: PreforkConfig): string => {
871
1027
  if (config.listenFlags !== 0 && config.listenFlags !== 2) {
872
1028
  return "listenFlags not 0 or 2"
873
1029
  }
1030
+ if (config.listenUdp && config.listenPort < 0) {
1031
+ return "listenUdp without listenPort"
1032
+ }
874
1033
  return ""
875
1034
  }
876
1035
 
@@ -916,9 +1075,11 @@ export const preforkWith = (args: string[], config: PreforkConfig): i32 => {
916
1075
  * Panics, besides, when `serviceWorker` is not below the worker count or the
917
1076
  * count is above 64 with a service worker (63 with `listenPort`), the most
918
1077
  * `spawnWithFds` hands one child; when `pin`, on Linux, asks for more workers
919
- * than `availableParallelism()`; and, through `preforkInvalid`, on seqpacket
920
- * channels off Linux. A listener that cannot bind answers
921
- * `PREFORK_SPAWN_FAILED` before any worker starts.
1078
+ * than `availableParallelism()`; when `listenUdp` asks for more than 255
1079
+ * workers (62 with a service worker); and, through `preforkInvalid`, on
1080
+ * seqpacket channels off Linux. A listener or UDP socket that cannot bind,
1081
+ * or a refused steering that leaves one worker beside a `serviceWorker` past
1082
+ * 0, answers `PREFORK_SPAWN_FAILED` before any worker starts.
922
1083
  *
923
1084
  * @param args the process's arguments, `process.argv`
924
1085
  * @param config the supervisor's settings, every field checked (a bad one
@@ -949,9 +1110,13 @@ export const preforkSupervise = <S>(
949
1110
  }
950
1111
  return index
951
1112
  }
952
- const count: i32 = preforkWorkerCount(config.workers, getenv("NISH_WORKERS"))
953
- // A held listener is one more descriptor for every worker, the service one too.
954
- const fdMax: i32 = config.listenPort >= 0 ? 63 : 64
1113
+ let count: i32 = preforkWorkerCount(config.workers, getenv("NISH_WORKERS"))
1114
+ if (config.listenUdp && count > PREFORK_UDP_MAX) {
1115
+ panic(`nish/net/prefork: listenUdp with ${count} workers, above ${PREFORK_UDP_MAX}`)
1116
+ }
1117
+ // A held listener is one more descriptor for every worker, the service one
1118
+ // too, and a held UDP socket one more again.
1119
+ const fdMax: i32 = toI32(config.listenPort >= 0 ? 63 : 64) - toI32(config.listenUdp ? 1 : 0)
955
1120
  if (config.serviceWorker >= count || (config.serviceWorker >= 0 && count > fdMax)) {
956
1121
  panic(`nish/net/prefork: serviceWorker not below ${count} workers, or above ${fdMax} workers`)
957
1122
  }
@@ -973,7 +1138,26 @@ export const preforkSupervise = <S>(
973
1138
  }
974
1139
  return PREFORK_SPAWN_FAILED
975
1140
  }
976
- const supervisor = new PreforkSupervisor(config, args, count, loop)
1141
+ // The UDP group first: a refused steering runs one worker, so it decides
1142
+ // the count everything after it is made for.
1143
+ const udp: i32[] = config.listenUdp ? preforkBindUdp(config, count) : []
1144
+ if (config.listenUdp && udp.length === 0) {
1145
+ netClose(loop)
1146
+ return PREFORK_SPAWN_FAILED
1147
+ }
1148
+ if (config.listenUdp) {
1149
+ count = toI32(udp.length)
1150
+ }
1151
+ // The one-worker fallback has no slot for a service worker past worker 0.
1152
+ if (config.serviceWorker >= count) {
1153
+ console.error(`nish/net/prefork: serviceWorker ${config.serviceWorker} with one worker, steering refused`)
1154
+ for (let i: i32 = 0; i < toI32(udp.length); i++) {
1155
+ netClose(udp[i])
1156
+ }
1157
+ netClose(loop)
1158
+ return PREFORK_SPAWN_FAILED
1159
+ }
1160
+ const supervisor = new PreforkSupervisor(config, args, count, loop, udp)
977
1161
  if (config.listenPort >= 0 && !supervisor.listen(pin)) {
978
1162
  netClose(loop)
979
1163
  return PREFORK_SPAWN_FAILED
@@ -120,6 +120,36 @@ export class QuicDatagramQueue {
120
120
  return this.count > 0 && k >= 0 && k < toI32(this.lengths.length) ? this.lengths[k] : -1
121
121
  }
122
122
 
123
+ /**
124
+ * Forgets the oldest datagram unsent and counts it in `dropped`, for one
125
+ * that no packet can carry any more; an empty ring is left as it is.
126
+ */
127
+ dropOldest(): void {
128
+ if (this.count > 0 && this.dropped < 2147483647) {
129
+ this.dropped = this.dropped + 1
130
+ }
131
+ this.drop()
132
+ }
133
+
134
+ /**
135
+ * Moves the oldest datagram behind the newest, unsent and not counted as
136
+ * dropped, so the ones queued after it go out first; for one too large
137
+ * for now that a later packet may carry. A ring of one is left as it is.
138
+ */
139
+ deferOldest(): void {
140
+ const entries: i32 = this.capacity()
141
+ if (this.count < 2) {
142
+ return
143
+ }
144
+ if (this.count < entries) {
145
+ const k: i32 = (this.head + this.count) % entries
146
+ const length: i32 = this.lengths[this.head]
147
+ quicPacketCopy(this.data, k * this.entrySize, this.data, this.head * this.entrySize, length)
148
+ this.lengths[k] = length
149
+ }
150
+ this.head = (this.head + 1) % entries
151
+ }
152
+
123
153
  /** Forgets the oldest datagram. */
124
154
  private drop(): void {
125
155
  if (this.count > 0) {
@@ -83,8 +83,8 @@
83
83
  * **GSO and GRO** (`nish:net`'s `UDP_SEGMENT` and `UDP_GRO`). A carrier that
84
84
  * sends with segmentation offload takes a whole flight at once:
85
85
  * `quicListenerTakeFlight` writes as many datagrams as the pacer has credit for
86
- * back to back into one buffer, every one `QUIC_CONN_DATAGRAM_SIZE` bytes but
87
- * the last, which is what one `udpSendTo` with that segment size cuts back into
86
+ * back to back into one buffer, every one the connection's `datagramSize()`
87
+ * but the last, which is what one `udpSendTo` with that segment size cuts back into
88
88
  * datagrams; each is written in place, so a flight allocates nothing.
89
89
  *
90
90
  * The flight is paced as a whole: it is as long as the pacer's credit, and
@@ -158,6 +158,8 @@ import {
158
158
  QuicConnection,
159
159
  QuicServerConfig,
160
160
  quicConnResetTokenInto,
161
+ quicWorkerByte,
162
+ quicWorkerCheck,
161
163
  } from "nish/net/quic"
162
164
 
163
165
  // ---- What `handle` answers ----------------------------------------------------
@@ -405,11 +407,14 @@ export class QuicListener {
405
407
  *
406
408
  * @param config The server's configuration, kept by reference: its static keys and Retry token lifetime.
407
409
  * Keys of the wrong size, or a lifetime outside 1 to `QUIC_LISTENER_MAX_TOKEN_LIFETIME` ms, make a
408
- * listener that drops every datagram.
410
+ * listener that drops every datagram. Its `workerIndex` and `workerCount` are checked here
411
+ * (`quicWorkerCheck`, which panics on a bad pair); a valid pair puts the worker in byte 0 of each
412
+ * Retry's connection ID and holds back the reset for an ID a sibling worker issued.
409
413
  * @param entropy `QUIC_LISTENER_ENTROPY_SIZE` (32) random bytes, the seed of every unpredictable byte
410
414
  * the listener sends. Zeroed on return; any other length makes a listener that drops every datagram.
411
415
  */
412
416
  constructor(config: QuicServerConfig, entropy: u8[]) {
417
+ quicWorkerCheck(config)
413
418
  this.config = config
414
419
  this.seed = new Array<u8>(QUIC_LISTENER_ENTROPY_SIZE)
415
420
  quicPacketCopy(this.seed, 0, entropy, 0, QUIC_LISTENER_ENTROPY_SIZE)
@@ -557,6 +562,17 @@ export class QuicListener {
557
562
  return answer.kind
558
563
  }
559
564
  if (header.type === QUIC_PACKET_SHORT) {
565
+ // RFC 9000 §21.11: an ID whose worker byte names a sibling in the
566
+ // steered group is that sibling's, and a reset under the shared key
567
+ // would end its live connection. Byte 0 at or above N is no worker's.
568
+ const owner: i32 = toI32(datagram[header.dcidStart])
569
+ if (
570
+ quicWorkerByte(this.config) >= 0 &&
571
+ owner < this.config.workerCount &&
572
+ owner !== this.config.workerIndex
573
+ ) {
574
+ return answer.kind
575
+ }
560
576
  this.statelessReset(answer, len, datagram, header.dcidStart, header.dcidLength)
561
577
  return answer.kind
562
578
  }
@@ -736,6 +752,11 @@ export class QuicListener {
736
752
  const reply: u8[] = answer.reply
737
753
  quicListenerResize(reply, tagAt + QUIC_RETRY_TAG_SIZE)
738
754
  this.randomInto(reply, retryScidAt, QUIC_CONN_CID_LENGTH)
755
+ const worker: i32 = quicWorkerByte(this.config)
756
+ if (worker >= 0) {
757
+ // The retried Initial is sent to this ID, so it steers back here.
758
+ reply[retryScidAt] = toU8(worker)
759
+ }
739
760
  reply[tokenAt] = toU8(QUIC_LISTENER_TOKEN_MARKER)
740
761
  quicListenerPutNumber(reply, tokenAt + 1, this.now, 8)
741
762
  reply[tokenAt + QUIC_LISTENER_TOKEN_HEAD - 1] = toU8(odcidLength)
@@ -980,7 +1001,7 @@ export const QUIC_LISTENER_FLIGHT_QUANTUM: i32 = 4800
980
1001
  * `QUIC_LISTENER_FLIGHT_QUANTUM`.
981
1002
  */
982
1003
  const quicListenerQuantum = (conn: QuicConnection): i32 =>
983
- conn.recovery.pacerQuantum(QUIC_CONN_DATAGRAM_SIZE, QUIC_LISTENER_FLIGHT_QUANTUM)
1004
+ conn.recovery.pacerQuantum(conn.datagramSize(), QUIC_LISTENER_FLIGHT_QUANTUM)
984
1005
 
985
1006
  /**
986
1007
  * When `quicListenerTakeFlight` next lets `conn` start a flight, in the
@@ -1015,11 +1036,15 @@ export class QuicFlight {
1015
1036
  * waits for, a millisecond's earning of one to four datagrams; then each
1016
1037
  * datagram goes only when the pacer has credit for a full one (RFC 9002 §7.7)
1017
1038
  * and is charged at its real size, as `quicListenerTakePaced` does, so the
1018
- * flight is the pacer's whole credit and no more. It stops at the first
1019
- * datagram shorter than `QUIC_CONN_DATAGRAM_SIZE`, which can only be the last
1020
- * of a segmented send, at `QUIC_LISTENER_FLIGHT_MAX` datagrams, when `cap` has
1021
- * no room for another, and before a datagram whose ECN codepoint would not be
1022
- * the first's.
1039
+ * flight is the pacer's whole credit and no more. Every datagram after the
1040
+ * first is held to the first's size, the segment, and the flight stops at the
1041
+ * first datagram shorter than the segment or than the connection's
1042
+ * `datagramSize()`, which can only be the last of a segmented send, at
1043
+ * `QUIC_LISTENER_FLIGHT_MAX` datagrams, when `cap` has no room for another,
1044
+ * and before a datagram whose ECN codepoint would not be the first's. A path
1045
+ * MTU probe (see `QuicConnection.pathMtu`) goes only when `cap` has room for
1046
+ * it, so a carrier gives `QUIC_CONN_DATAGRAM_MAX` bytes or more to let the
1047
+ * connection discover a larger path.
1023
1048
  *
1024
1049
  * @param conn The connection to send for.
1025
1050
  * @param now The caller's time in milliseconds.
@@ -1048,14 +1073,15 @@ export const quicListenerTakeFlight = (
1048
1073
  while (
1049
1074
  flight.count < QUIC_LISTENER_FLIGHT_MAX &&
1050
1075
  length + QUIC_CONN_DATAGRAM_SIZE <= cap &&
1051
- conn.recovery.pacerDelay(now, QUIC_CONN_DATAGRAM_SIZE) <= 0
1076
+ conn.recovery.pacerDelay(now, conn.datagramSize()) <= 0
1052
1077
  ) {
1053
1078
  // The codepoint `takeDatagramInto` would mark the next datagram with: one send carries one.
1054
1079
  const next: i32 = conn.ecnMarking ? conn.recovery.ecnCodepoint() : 0
1055
1080
  if (flight.count > 0 && next !== flight.ecn) {
1056
1081
  return length
1057
1082
  }
1058
- const n: i32 = conn.takeDatagramInto(buf, at + length, now)
1083
+ const room: i32 = flight.count > 0 && flight.segment < cap - length ? flight.segment : cap - length
1084
+ const n: i32 = conn.takeDatagramWithin(buf, at + length, room, now)
1059
1085
  if (n <= 0) {
1060
1086
  return length
1061
1087
  }
@@ -1066,7 +1092,7 @@ export const quicListenerTakeFlight = (
1066
1092
  }
1067
1093
  flight.count = flight.count + 1
1068
1094
  length = length + n
1069
- if (n < QUIC_CONN_DATAGRAM_SIZE) {
1095
+ if (n < flight.segment || n < conn.datagramSize()) {
1070
1096
  return length
1071
1097
  }
1072
1098
  }
@@ -116,6 +116,7 @@ import {
116
116
  } from "nish/crypto/aes"
117
117
  import { chacha20HeaderMask, chacha20Poly1305Open, chacha20Poly1305Seal } from "nish/crypto/chacha20poly1305"
118
118
  import { timingSafeEqual } from "nish/crypto/ct"
119
+ import { copyBytes } from "nish/bytes"
119
120
  import {
120
121
  HkdfScratch,
121
122
  hkdfExpandLabelHeldInto,
@@ -627,8 +628,8 @@ const quicPacketCidWindowFits = (cid: u8[], length: i32): boolean =>
627
628
  length >= 0 && length <= QUIC_MAX_CID_LENGTH && length <= toI32(cid.length)
628
629
 
629
630
  /**
630
- * Writes `bytes[from .. from + length)` into `buf` at `at`; the caller has checked both windows.
631
- * A byte outside either window is skipped rather than written, so a wrong window cannot panic.
631
+ * Writes `bytes[from .. from + length)` into `buf` at `at`, as one slice copy; the caller has checked both windows.
632
+ * The part of the run outside either window is skipped rather than written, so a wrong window cannot panic.
632
633
  *
633
634
  * @param buf The buffer to write into; it is not grown.
634
635
  * @param at The byte offset in `buf` of the first byte written.
@@ -637,10 +638,22 @@ const quicPacketCidWindowFits = (cid: u8[], length: i32): boolean =>
637
638
  * @param length How many bytes to copy.
638
639
  */
639
640
  export const quicPacketCopy = (buf: u8[], at: i32, bytes: u8[], from: i32, length: i32): void => {
640
- for (let k: i32 = 0; k < length; k += 1) {
641
- if (at + k >= 0 && at + k < toI32(buf.length) && from + k >= 0 && from + k < toI32(bytes.length)) {
642
- buf[at + k] = bytes[from + k]
643
- }
641
+ let low: i32 = 0
642
+ if (low < -at) {
643
+ low = -at
644
+ }
645
+ if (low < -from) {
646
+ low = -from
647
+ }
648
+ let high: i32 = length
649
+ if (high > toI32(buf.length) - at) {
650
+ high = toI32(buf.length) - at
651
+ }
652
+ if (high > toI32(bytes.length) - from) {
653
+ high = toI32(bytes.length) - from
654
+ }
655
+ if (low < high) {
656
+ copyBytes(buf, at + low, bytes, from + low, high - low)
644
657
  }
645
658
  }
646
659