nish 0.34.1 → 0.36.0

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 (127) hide show
  1. package/README.md +7 -6
  2. package/docs/AI.md +86 -16
  3. package/docs/INSTALL.md +22 -13
  4. package/llms.txt +5 -2
  5. package/package.json +15 -5
  6. package/runtime/async.d.mts +49 -0
  7. package/runtime/async.mjs +27 -0
  8. package/runtime/nish.d.ts +4681 -427
  9. package/runtime/nish.h +6 -2
  10. package/runtime/nish.mjs +4 -0
  11. package/runtime/runtime-net.c +22 -0
  12. package/runtime/runtime-shm.c +93 -2
  13. package/runtime/vite.d.ts +30 -0
  14. package/runtime/vite.mjs +150 -0
  15. package/scripts/build.sh +108 -13
  16. package/std/README.md +131 -131
  17. package/std/base64.ts +34 -5
  18. package/std/bytes.ts +258 -42
  19. package/std/cli-args.ts +296 -70
  20. package/std/cli-flags.ts +184 -19
  21. package/std/cli.ts +475 -54
  22. package/std/collections.ts +121 -23
  23. package/std/compress/checksum.ts +44 -14
  24. package/std/compress/deflate.ts +224 -111
  25. package/std/compress/gzip.ts +217 -53
  26. package/std/compress/zlib.ts +63 -7
  27. package/std/crypto/aes.ts +80 -9
  28. package/std/crypto/base64url.ts +22 -0
  29. package/std/crypto/bcrypt-batch.ts +88 -21
  30. package/std/crypto/bcrypt.ts +60 -0
  31. package/std/crypto/chacha20poly1305.ts +53 -0
  32. package/std/crypto/ct.ts +32 -13
  33. package/std/crypto/ed25519.ts +47 -0
  34. package/std/crypto/hkdf.ts +198 -13
  35. package/std/crypto/hmac.ts +235 -31
  36. package/std/crypto/jwt.ts +192 -63
  37. package/std/crypto/p256.ts +159 -16
  38. package/std/crypto/p384.ts +28 -3
  39. package/std/crypto/pki-roots.ts +32 -2
  40. package/std/crypto/pki.ts +81 -15
  41. package/std/crypto/rsa.ts +33 -3
  42. package/std/crypto/sha1.ts +3 -0
  43. package/std/crypto/sha256.ts +24 -1
  44. package/std/crypto/sha512.ts +99 -14
  45. package/std/crypto/x25519.ts +152 -14
  46. package/std/crypto/x509-random.ts +10 -0
  47. package/std/crypto/x509.ts +67 -7
  48. package/std/json-equal.ts +19 -0
  49. package/std/json-format.ts +112 -13
  50. package/std/json-number.ts +64 -14
  51. package/std/json-pointer.ts +23 -1
  52. package/std/json-tokenizer.ts +100 -29
  53. package/std/json-typed.ts +713 -66
  54. package/std/json-value.ts +400 -124
  55. package/std/json.ts +138 -10
  56. package/std/map.ts +25 -7
  57. package/std/math.ts +36 -4
  58. package/std/net/buffer-pool.ts +42 -11
  59. package/std/net/dns-config.ts +109 -23
  60. package/std/net/dns-message.ts +62 -7
  61. package/std/net/dns-resolver.ts +247 -53
  62. package/std/net/dns.ts +203 -35
  63. package/std/net/fetch.ts +151 -61
  64. package/std/net/handler.ts +278 -80
  65. package/std/net/hpack.ts +262 -52
  66. package/std/net/http-compress.ts +125 -15
  67. package/std/net/http-fields.ts +85 -9
  68. package/std/net/http1-client-codec.ts +100 -19
  69. package/std/net/http1-codec.ts +297 -77
  70. package/std/net/http1-server.ts +430 -94
  71. package/std/net/http2-frame.ts +272 -35
  72. package/std/net/http2-tls.ts +135 -34
  73. package/std/net/http2.ts +247 -106
  74. package/std/net/http3-frame.ts +154 -17
  75. package/std/net/http3-server.ts +275 -101
  76. package/std/net/http3.ts +307 -115
  77. package/std/net/outbound.ts +37 -3
  78. package/std/net/postgres-carrier.ts +144 -8
  79. package/std/net/postgres.ts +801 -112
  80. package/std/net/prefork.ts +164 -31
  81. package/std/net/qpack.ts +105 -18
  82. package/std/net/quic-conn-ack.ts +59 -12
  83. package/std/net/quic-conn-cid.ts +124 -27
  84. package/std/net/quic-conn-params.ts +70 -10
  85. package/std/net/quic-datagram.ts +43 -3
  86. package/std/net/quic-frame.ts +286 -12
  87. package/std/net/quic-listener.ts +101 -32
  88. package/std/net/quic-packet.ts +302 -21
  89. package/std/net/quic-recovery.ts +264 -52
  90. package/std/net/quic-stream.ts +353 -91
  91. package/std/net/quic.ts +1124 -201
  92. package/std/net/router.ts +87 -40
  93. package/std/net/tls/client.ts +166 -51
  94. package/std/net/tls/codec.ts +413 -56
  95. package/std/net/tls/record-client.ts +110 -55
  96. package/std/net/tls/record-server.ts +159 -59
  97. package/std/net/tls/record.ts +109 -12
  98. package/std/net/tls/schedule.ts +235 -26
  99. package/std/net/tls/ticket.ts +159 -40
  100. package/std/net/tls/verify.ts +49 -3
  101. package/std/net/tls-tcp.ts +250 -45
  102. package/std/net/tls.ts +221 -59
  103. package/std/net/upstream.ts +81 -45
  104. package/std/net/url.ts +97 -13
  105. package/std/net/websocket.ts +122 -12
  106. package/std/net/webtransport.ts +220 -89
  107. package/std/pair.ts +10 -2
  108. package/std/random.ts +34 -9
  109. package/std/regex.ts +352 -198
  110. package/std/region.ts +70 -15
  111. package/std/secret.ts +52 -11
  112. package/std/sort.ts +17 -2
  113. package/std/sqlite.ts +256 -35
  114. package/std/sync/ring.ts +430 -40
  115. package/std/sync/shm.ts +222 -15
  116. package/std/term-io.ts +137 -64
  117. package/std/term-pixels.ts +144 -19
  118. package/std/term-probe.ts +66 -25
  119. package/std/term-rate.ts +128 -57
  120. package/std/term.ts +332 -121
  121. package/std/testing.ts +130 -32
  122. package/std/text.ts +73 -7
  123. package/std/threads.ts +229 -41
  124. package/std/yaml-json.ts +94 -82
  125. package/std/yaml-lines.ts +47 -15
  126. package/std/yaml-write.ts +24 -16
  127. package/std/yaml.ts +764 -384
package/std/net/quic.ts CHANGED
@@ -7,11 +7,15 @@
7
7
  * Sans-IO, like the rest of `nish/net`.
8
8
  *
9
9
  * import { QuicConnection, QuicServerConfig } from "nish/net/quic";
10
+ * import { tlsSignEcdsaP256 } from "nish/net/tls";
10
11
  *
11
12
  * const conn = new QuicConnection(config, entropy); // entropy: QUIC_CONN_ENTROPY_SIZE random bytes
12
13
  * conn.receiveWindow(buf, off, len, now); // every datagram the client sends; now in ms
13
14
  * const input: u8[] | null = conn.signatureInput();
14
- * if (input !== null) { conn.sign(tlsSignEcdsaP256(key, input)); }
15
+ * if (input !== null) {
16
+ * const signature: u8[] | null = tlsSignEcdsaP256(key, input); // key: Secret<u8[]>
17
+ * if (signature !== null) { conn.sign(signature); }
18
+ * }
15
19
  * let n: i32 = conn.takeDatagramInto(out, 0, now); // out: at least QUIC_CONN_DATAGRAM_SIZE bytes
16
20
  * while (n > 0) { … send out[0 .. n) to the client … ; n = conn.takeDatagramInto(out, 0, now); }
17
21
  * let id: i64 = conn.nextStreamEvent(); // a stream with news: read it, write it
@@ -30,7 +34,7 @@
30
34
  * client's are parsed and checked (RFC 9000 §7.3, §7.4) before the server's
31
35
  * flight leaves.
32
36
  *
33
- * **Streams** are `nish/net/quic-stream`'s: both kinds, opened by either
37
+ * **Streams.** They are `nish/net/quic-stream`'s: both kinds, opened by either
34
38
  * side, with flow control per stream and for the connection raised as the
35
39
  * application reads, and the stream limits raised as streams finish. The
36
40
  * application sees them through a small surface: `nextStreamEvent` names a
@@ -48,7 +52,7 @@
48
52
  * congestion window, and is never sent again. `readDatagram` hands out what
49
53
  * arrived. Each way is a fixed ring (`nish/net/quic-datagram`).
50
54
  *
51
- * **Loss recovery** (RFC 9002) is `nish/net/quic-recovery`'s: every
55
+ * **Loss recovery** (RFC 9002). It is `nish/net/quic-recovery`'s: every
52
56
  * ack-eliciting packet is recorded in its space's ring with what it carried
53
57
  * (its CRYPTO range, its STREAM chunks, HANDSHAKE_DONE and the control
54
58
  * frames), the client's ACKs give the RTT estimate and show what was lost by
@@ -97,15 +101,18 @@
97
101
  *
98
102
  * **Time.** The connection has no clock: `receive`, `takeDatagram` and
99
103
  * `handleTimer` take the caller's monotonic time in milliseconds, and
100
- * `deadline()` says when `handleTimer` is next due. Four things run on it.
104
+ * `deadline()` says when `handleTimer` is next due. Five things run on it.
101
105
  * The idle timeout (RFC 9000 §10.1) is the smaller of the two sides'
102
106
  * `max_idle_timeout`, never under `QUIC_CONN_IDLE_FLOOR` or three probe
103
107
  * timeouts; once it passes with nothing received, the connection closes
104
108
  * silently (`QUIC_STATE_TIMED_OUT`) and wipes its keys. Loss recovery's
105
109
  * timer declares packets lost by the time threshold or fires the probe
106
- * timeout. And after a key update the previous read keys are kept for a
110
+ * timeout. After a key update the previous read keys are kept for a
107
111
  * probe timeout (`recovery.probeTimeout()`), for packets the network
108
- * reordered, before the next generation's are derived (RFC 9001 §6.5). Once
112
+ * reordered, before the next generation's are derived (RFC 9001 §6.5). And
113
+ * while a new path is validated, its PATH_CHALLENGE goes again a probe
114
+ * timeout after the last, and validation gives up max(3 PTO, 6 kInitialRtt)
115
+ * after the move (RFC 9000 §8.2.4, §9.3.2). Once
109
116
  * the connection has closed, by either side, its keys are kept through the
110
117
  * closing or draining period, three probe timeouts (RFC 9000 §10.2), and
111
118
  * wiped at its end; `deadline()` is that end, then -1. A close this side
@@ -138,6 +145,32 @@
138
145
  * token from the configuration's static key (RFC 9000 §10.3.2), and every
139
146
  * ACK says a delay of zero. So a recorded exchange replays byte for byte.
140
147
  *
148
+ * **Paths** (RFC 9000 §8.2, §9). `receiveWindowFrom` takes the 18-byte
149
+ * `nish:net` address each datagram came from, and `sendAddress()` says where
150
+ * the connection's datagrams go: the first Initial's address, validated by
151
+ * the handshake, until the client's address changes. Before the handshake
152
+ * is confirmed a datagram from any other address is dropped unread, so no
153
+ * forged source moves a handshake or takes its flight. After it, a datagram
154
+ * from a new address whose newest non-probing packet authenticates moves
155
+ * the connection there (§9.3) — a later one from the old address, with a
156
+ * lower packet number, does not move it back — and a PATH_CHALLENGE, eight
157
+ * bytes from the ID seed's HMAC, padded to 1,200 bytes, validates the new
158
+ * path. Until a PATH_RESPONSE with any of the last three challenges'
159
+ * data arrives, on any path, the server sends there at most three times
160
+ * what came from it (§9.3.1); a lost challenge is drawn again, fresh, a
161
+ * probe timeout later; past max(3 PTO, 6 kInitialRtt) validation has failed
162
+ * and the connection goes back to the last validated address, where the
163
+ * client — or, for a forged source, the real client's next packet — finds
164
+ * it. Validated, a new address starts congestion control and the RTT
165
+ * estimate again, a port-only change keeps them (§9.4), and ECN is tested
166
+ * again (§13.4.2). A packet that carries only probing frames moves
167
+ * nothing: its PATH_CHALLENGE is answered on its own path, alone in a
168
+ * datagram `takeProbeInto` writes for `probeAddress`, under that path's own
169
+ * 3x limit. The client's connection ID is kept across a move (§9.5): a NAT
170
+ * rebinding gives the client no reason to change it, and this server never
171
+ * migrates itself. Every address, challenge and counter is a field made by
172
+ * the constructor and cleared by `reset`.
173
+ *
141
174
  * **What a peer cannot do.** Nothing it sends makes this module panic. A
142
175
  * datagram that does not parse, a packet that does not authenticate, a
143
176
  * duplicate packet number, a packet for keys already discarded and a 1-RTT
@@ -231,6 +264,7 @@ import {
231
264
  QUIC_FRAME_MAX_STREAMS_UNI,
232
265
  QUIC_FRAME_NEW_CONNECTION_ID,
233
266
  QUIC_FRAME_NEW_TOKEN,
267
+ QUIC_FRAME_PADDING,
234
268
  QUIC_FRAME_PATH_CHALLENGE,
235
269
  QUIC_FRAME_PATH_RESPONSE,
236
270
  QUIC_FRAME_PING,
@@ -389,6 +423,11 @@ export const QUIC_CONN_CONFIDENTIALITY_LIMIT: i64 = 8388608
389
423
  * with AEAD_LIMIT_REACHED. AES-GCM's is 2^52, ChaCha20-Poly1305's 2^36.
390
424
  */
391
425
  export const QUIC_CONN_INTEGRITY_LIMIT_GCM: i64 = 4503599627370496
426
+ /**
427
+ * ChaCha20-Poly1305's integrity limit (RFC 9001 §6.6), 2^36 packets that fail
428
+ * to authenticate over a connection, across every key, before it closes with
429
+ * AEAD_LIMIT_REACHED. The connection counts failures against the limit of the AEAD it negotiated.
430
+ */
392
431
  export const QUIC_CONN_INTEGRITY_LIMIT_CHACHA: i64 = 68719476736
393
432
  /**
394
433
  * How many skipped packet numbers the server remembers (RFC 9000 §21.4): an
@@ -398,7 +437,17 @@ export const QUIC_CONN_INTEGRITY_LIMIT_CHACHA: i64 = 68719476736
398
437
  * reaches back at least 7 × 129 = 903 packets.
399
438
  */
400
439
  export const QUIC_CONN_SKIP_RING: i32 = 8
440
+ /**
441
+ * The fewest Application Data packets between two skipped packet numbers
442
+ * (RFC 9000 §21.4). Large enough that the gaps cost the client almost
443
+ * nothing in ACK ranges.
444
+ */
401
445
  export const QUIC_CONN_SKIP_MIN: i64 = 128
446
+ /**
447
+ * How many distances past `QUIC_CONN_SKIP_MIN` a skip may fall at: the next
448
+ * skipped number is `QUIC_CONN_SKIP_MIN` plus 0 to 896 past the number after
449
+ * the last skip, so skips fall 129 to 1025 numbers apart.
450
+ */
402
451
  export const QUIC_CONN_SKIP_SPREAD: i64 = 897
403
452
  /**
404
453
  * The HMAC counter the skip distances are drawn under, past any connection
@@ -406,6 +455,24 @@ export const QUIC_CONN_SKIP_SPREAD: i64 = 897
406
455
  * both without either telling anything about the other.
407
456
  */
408
457
  const QUIC_CONN_SKIP_SEQUENCE: i64 = QUIC_MAX_VARINT + 1
458
+ /**
459
+ * The HMAC counter PATH_CHALLENGE data is drawn under: past every connection
460
+ * ID's sequence and every skip's (`QUIC_CONN_SKIP_SEQUENCE` plus fewer than
461
+ * 2^61 draws), so no challenge repeats an ID or a skip distance.
462
+ */
463
+ const QUIC_CONN_CHALLENGE_SEQUENCE: i64 = QUIC_CONN_SKIP_SEQUENCE + QUIC_CONN_SKIP_SEQUENCE / 2
464
+ /** A `nish:net` address: sixteen bytes of IPv6 (IPv4 mapped), then the port, big-endian. */
465
+ export const QUIC_CONN_ADDRESS_SIZE: i32 = 18
466
+ /** PATH_CHALLENGE data kept to match a PATH_RESPONSE against: the latest and the two sent before it. */
467
+ const QUIC_CONN_CHALLENGES: i32 = 3
468
+ /**
469
+ * The smallest datagram sent on a path being validated: below it, what the
470
+ * path's 3x limit leaves is not worth a packet, and the server waits for the
471
+ * client to send more (RFC 9000 §8.1, §9.3.1).
472
+ */
473
+ const QUIC_CONN_PATH_MIN: i64 = 64
474
+ /** RFC 9000 §8.2.4's floor on path validation: six times the initial RTT, in milliseconds. */
475
+ const QUIC_CONN_VALIDATION_FLOOR: i64 = 1998
409
476
  /**
410
477
  * How many ack-eliciting datagrams a probe timeout sends in the Initial and
411
478
  * Handshake spaces (RFC 9002 §6.2.4 allows up to two). The server's first
@@ -556,6 +623,14 @@ export class QuicStreamData {
556
623
  data: u8[]
557
624
  fin: boolean = false
558
625
 
626
+ /**
627
+ * A run as `readStream` hands it out.
628
+ *
629
+ * @param streamId The RFC 9000 stream ID the bytes arrived on.
630
+ * @param data The bytes, in stream order; the run owns this array, so the caller may keep it. Empty
631
+ * for a run that only carries the FIN.
632
+ * @param fin True when the run ends at the stream's FIN, so nothing more follows on `streamId`.
633
+ */
559
634
  constructor(streamId: i64, data: u8[], fin: boolean) {
560
635
  this.streamId = streamId
561
636
  this.data = data
@@ -572,11 +647,22 @@ export class QuicStreamData {
572
647
  * before the Handshake one starts.
573
648
  */
574
649
  class QuicConnReassembly {
650
+ /** @internal Read in quic.ts outside the class. */
575
651
  ring: u8[]
652
+ /**
653
+ * @internal Only its own class reads it; kept public with `ring`, its family, read in quic.ts outside
654
+ * the class.
655
+ */
576
656
  have: u8[]
577
- /** The level whose bytes the ring holds. */
657
+ /**
658
+ * The level whose bytes the ring holds.
659
+ * @internal Read in quic.ts outside the class.
660
+ */
578
661
  level: i32 = 0
579
- /** How many bytes of the level have been handed to TLS. */
662
+ /**
663
+ * How many bytes of the level have been handed to TLS.
664
+ * @internal Read in quic.ts outside the class.
665
+ */
580
666
  delivered: i64 = 0
581
667
 
582
668
  constructor(capacity: i32) {
@@ -584,26 +670,32 @@ class QuicConnReassembly {
584
670
  this.have = new Array<u8>((capacity + 7) >> 3)
585
671
  }
586
672
 
587
- /** Empties the ring for level `level`. */
673
+ /**
674
+ * Empties the ring for level `level`.
675
+ * @internal Read in quic.ts outside the class.
676
+ */
588
677
  reset(level: i32): void {
589
678
  this.level = level
590
679
  this.delivered = 0
591
680
  this.have.fill(toU8(0))
592
681
  }
593
682
 
594
- /** The ring slot of stream offset `offset`. */
683
+ /**
684
+ * The ring slot of stream offset `offset`.
685
+ * @internal Read in quic.ts outside the class.
686
+ */
595
687
  slot(offset: i64): i32 {
596
688
  const capacity: i32 = toI32(this.ring.length)
597
689
  return capacity > 0 ? toI32(offset % toI64(capacity)) : 0
598
690
  }
599
691
 
600
692
  /** Whether the byte in ring slot `s` arrived and is not yet handed out. */
601
- arrived(s: i32): boolean {
693
+ private arrived(s: i32): boolean {
602
694
  return quicStreamBit(this.have, s)
603
695
  }
604
696
 
605
697
  /** Marks ring slot `s` as holding a byte, or not. */
606
- mark(s: i32, on: boolean): void {
698
+ private mark(s: i32, on: boolean): void {
607
699
  quicStreamSetBit(this.have, s, on)
608
700
  }
609
701
 
@@ -611,6 +703,7 @@ class QuicConnReassembly {
611
703
  * Takes `data[from .. from + length)`, which sits at stream offset
612
704
  * `offset`. Answers `false`, taking nothing, when it reaches `capacity` or
613
705
  * more past what was delivered. Bytes already delivered are skipped.
706
+ * @internal Read in quic.ts outside the class.
614
707
  */
615
708
  insert(offset: i64, data: u8[], from: i32, length: i32): boolean {
616
709
  const capacity: i32 = toI32(this.ring.length)
@@ -631,7 +724,10 @@ class QuicConnReassembly {
631
724
  return true
632
725
  }
633
726
 
634
- /** How many bytes from `delivered` have arrived without a gap, up to the end of the ring's array. */
727
+ /**
728
+ * How many bytes from `delivered` have arrived without a gap, up to the end of the ring's array.
729
+ * @internal Read in quic.ts outside the class.
730
+ */
635
731
  run(): i32 {
636
732
  const capacity: i32 = toI32(this.ring.length)
637
733
  const start: i32 = this.slot(this.delivered)
@@ -642,7 +738,10 @@ class QuicConnReassembly {
642
738
  return n
643
739
  }
644
740
 
645
- /** Hands out the `n` bytes `run` counted: their bits cleared, `delivered` moved past them. */
741
+ /**
742
+ * Hands out the `n` bytes `run` counted: their bits cleared, `delivered` moved past them.
743
+ * @internal Read in quic.ts outside the class.
744
+ */
646
745
  consume(n: i32): void {
647
746
  const start: i32 = this.slot(this.delivered)
648
747
  for (let k: i32 = 0; k < n; k += 1) {
@@ -670,6 +769,7 @@ class QuicConnSpace {
670
769
  nextPn: i64 = 0
671
770
  /** The largest packet number the client acknowledged here, or -1. */
672
771
  largestAcked: i64 = -1
772
+ /** @internal Read in quic.ts outside the class. */
673
773
  received: QuicAckRanges
674
774
  /**
675
775
  * Every CRYPTO byte TLS wrote at this level, from stream offset 0, its
@@ -677,8 +777,10 @@ class QuicConnSpace {
677
777
  * a lost range can be sent again; the array is reused by the next
678
778
  * connection in the slot. The bytes from `cryptoOutHead` (offset
679
779
  * `cryptoOutOffset`) are not sent yet.
780
+ * @internal Read in quic.ts outside the class.
680
781
  */
681
782
  cryptoOut: u8[]
783
+ /** @internal Read in quic.ts outside the class. */
682
784
  cryptoOutLength: i32 = 0
683
785
  /**
684
786
  * How many ack-eliciting probe packets this space still owes, which the
@@ -686,25 +788,47 @@ class QuicConnSpace {
686
788
  * §6.2.4), or an early resend (§6.2.3).
687
789
  */
688
790
  probes: i32 = 0
791
+ /** @internal Read in quic.ts outside the class. */
689
792
  cryptoOutOffset: i64 = 0
690
- /** How many CRYPTO bytes the client sent here that were handed to TLS, for a duplicate arriving after the next level started. */
793
+ /**
794
+ * How many CRYPTO bytes the client sent here that were handed to TLS, for a duplicate arriving after the next level started.
795
+ * @internal Read in quic.ts outside the class.
796
+ */
691
797
  cryptoInDelivered: i64 = 0
692
- /** CRYPTO bytes declared lost, to send before new ones: `[cryptoResendLow, cryptoResendHigh)`, or -1. */
798
+ /**
799
+ * CRYPTO bytes declared lost, to send before new ones: `[cryptoResendLow, cryptoResendHigh)`, or -1.
800
+ * @internal Read in quic.ts outside the class.
801
+ */
693
802
  cryptoResendLow: i64 = -1
803
+ /** @internal Read in quic.ts outside the class. */
694
804
  cryptoResendHigh: i64 = -1
695
805
  /** Each packet's CRYPTO frame (offset, and length 0 for none), and its `QUIC_CONN_SENT_*` bits. */
696
- sentCryptoOffset: i64[]
697
- sentCryptoLength: i32[]
698
- sentFlags: u8[]
699
- /** Each packet's STREAM chunks, `QUIC_CONN_PACKET_STREAMS` to a row: how many, then each one's stream, offset, length and FIN. */
806
+ private sentCryptoOffset: i64[]
807
+ private sentCryptoLength: i32[]
808
+ private sentFlags: u8[]
809
+ /**
810
+ * Each packet's STREAM chunks, `QUIC_CONN_PACKET_STREAMS` to a row: how many, then each one's stream, offset, length and FIN.
811
+ * @internal Only its own class reads it; kept public with `sentStreamId`, its family, read in quic.ts
812
+ * outside the class.
813
+ */
700
814
  sentStreamCount: i32[]
815
+ /** @internal Read in quic.ts outside the class. */
701
816
  sentStreamId: i64[]
817
+ /** @internal Read in quic.ts outside the class. */
702
818
  sentStreamOffset: i64[]
819
+ /** @internal Read in quic.ts outside the class. */
703
820
  sentStreamLength: i32[]
821
+ /** @internal Read in quic.ts outside the class. */
704
822
  sentStreamFin: u8[]
705
- /** Each packet's control frames, `QUIC_CONN_PACKET_CONTROL` to a row: their kind and value (a sequence number or a stream). */
823
+ /**
824
+ * Each packet's control frames, `QUIC_CONN_PACKET_CONTROL` to a row: their kind and value (a sequence number or a stream).
825
+ * @internal Only its own class reads it; kept public with `sentControlKind`, its family, read in quic.ts
826
+ * outside the class.
827
+ */
706
828
  sentControlCount: i32[]
829
+ /** @internal Read in quic.ts outside the class. */
707
830
  sentControlKind: u8[]
831
+ /** @internal Read in quic.ts outside the class. */
708
832
  sentControlValue: i64[]
709
833
  /**
710
834
  * Where this space's packet keys live, made once for the slot (QUIC-3):
@@ -712,17 +836,31 @@ class QuicConnSpace {
712
836
  * second of each, which a key update derives the next generation into.
713
837
  */
714
838
  keySlots: QuicKeysSlot[]
715
- /** `TLS_LEVEL_INITIAL`, `_HANDSHAKE` or `_APPLICATION`, which is also the space's index. */
839
+ /**
840
+ * `TLS_LEVEL_INITIAL`, `_HANDSHAKE` or `_APPLICATION`, which is also the space's index.
841
+ * @internal Read in quic.ts outside the class.
842
+ */
716
843
  level: i32 = 0
844
+ /** @internal Read in quic.ts outside the class. */
717
845
  cryptoOutHead: i32 = 0
718
- /** The packet `buildDatagram` is putting together here: where it starts in the datagram, or -1 for none, and its payload's end. */
846
+ /**
847
+ * The packet `buildDatagram` is putting together here: where it starts in the datagram, or -1 for none, and its payload's end.
848
+ * @internal Read in quic.ts outside the class.
849
+ */
719
850
  builtStart: i32 = -1
851
+ /** @internal Read in quic.ts outside the class. */
720
852
  builtEnd: i32 = 0
721
- /** The row the packet being built is described in: one past the last slot. */
853
+ /**
854
+ * The row the packet being built is described in: one past the last slot.
855
+ * @internal Read in quic.ts outside the class.
856
+ */
722
857
  staging: i32 = 0
723
858
  /** Whether the keys were discarded (RFC 9001 §4.9): nothing is sent or received here again. */
724
859
  discarded: boolean = false
725
- /** Whether the packet being built elicits an acknowledgement, and so is recorded. */
860
+ /**
861
+ * Whether the packet being built elicits an acknowledgement, and so is recorded.
862
+ * @internal Read in quic.ts outside the class.
863
+ */
726
864
  stagedEliciting: boolean = false
727
865
 
728
866
  constructor(level: i32) {
@@ -753,7 +891,10 @@ class QuicConnSpace {
753
891
  this.sentControlValue = new Array<i64>(chunkRows * QUIC_CONN_PACKET_CONTROL)
754
892
  }
755
893
 
756
- /** Puts the space back as a new connection has it, keeping its arrays, for a slot reused for another peer. */
894
+ /**
895
+ * Puts the space back as a new connection has it, keeping its arrays, for a slot reused for another peer.
896
+ * @internal Read in quic.ts outside the class.
897
+ */
757
898
  reset(): void {
758
899
  this.readKeys = null
759
900
  this.writeKeys = null
@@ -775,6 +916,7 @@ class QuicConnSpace {
775
916
  * Appends `bytes[0 .. length)` to the CRYPTO stream kept, writing into the
776
917
  * array's old room before growing it: TLS's output buffer is read in
777
918
  * place, so its flight is not copied on the way.
919
+ * @internal Read in quic.ts outside the class.
778
920
  */
779
921
  appendCrypto(bytes: u8[], length: i32): void {
780
922
  for (let k: i32 = 0; k < length && k < toI32(bytes.length); k += 1) {
@@ -792,45 +934,69 @@ class QuicConnSpace {
792
934
  * Key slot `k` of this space: in the Initial and Handshake spaces 0 holds
793
935
  * the read keys and 1 the write keys; in Application Data 0 and 1 hold
794
936
  * the read keys' generations and 2 and 3 the write keys'.
937
+ *
938
+ * @param k The slot index, 0 to 1 in the Initial and Handshake spaces and 0 to 3 in Application Data.
939
+ * @returns The slot itself, borrowed from the space and reused across keys; slot 0 for a `k` out of range.
795
940
  */
796
941
  keySlot(k: i32): QuicKeysSlot {
797
942
  const at: i32 = k >= 0 && k < toI32(this.keySlots.length) ? k : 0
798
943
  return this.keySlots[at]
799
944
  }
800
945
 
801
- /** Zeroes every key this space's slots hold, the AES schedules included. */
946
+ /**
947
+ * Zeroes every key this space's slots hold, the AES schedules included.
948
+ * @internal Read in quic.ts outside the class.
949
+ */
802
950
  wipeKeySlots(): void {
803
951
  for (const slot of this.keySlots) {
804
952
  slot.wipe()
805
953
  }
806
954
  }
807
955
 
808
- /** The number of STREAM chunks row `row` holds, or 0. */
956
+ /**
957
+ * The number of STREAM chunks row `row` holds, or 0.
958
+ * @internal Read in quic.ts outside the class.
959
+ */
809
960
  streamCount(row: i32): i32 {
810
961
  return row >= 0 && row < toI32(this.sentStreamCount.length) ? this.sentStreamCount[row] : 0
811
962
  }
812
963
 
813
- /** The number of control frames row `row` holds, or 0. */
964
+ /**
965
+ * The number of control frames row `row` holds, or 0.
966
+ * @internal Read in quic.ts outside the class.
967
+ */
814
968
  controlCount(row: i32): i32 {
815
969
  return row >= 0 && row < toI32(this.sentControlCount.length) ? this.sentControlCount[row] : 0
816
970
  }
817
971
 
818
- /** The CRYPTO frame's length in row `row`, or 0. */
972
+ /**
973
+ * The CRYPTO frame's length in row `row`, or 0.
974
+ * @internal Read in quic.ts outside the class.
975
+ */
819
976
  cryptoLength(row: i32): i32 {
820
977
  return row >= 0 && row < toI32(this.sentCryptoLength.length) ? this.sentCryptoLength[row] : 0
821
978
  }
822
979
 
823
- /** The CRYPTO frame's offset in row `row`, or 0. */
980
+ /**
981
+ * The CRYPTO frame's offset in row `row`, or 0.
982
+ * @internal Read in quic.ts outside the class.
983
+ */
824
984
  cryptoOffset(row: i32): i64 {
825
985
  return row >= 0 && row < toI32(this.sentCryptoOffset.length) ? this.sentCryptoOffset[row] : 0
826
986
  }
827
987
 
828
- /** The `QUIC_CONN_SENT_*` bits of row `row`. */
988
+ /**
989
+ * The `QUIC_CONN_SENT_*` bits of row `row`.
990
+ * @internal Read in quic.ts outside the class.
991
+ */
829
992
  flags(row: i32): i32 {
830
993
  return row >= 0 && row < toI32(this.sentFlags.length) ? toI32(this.sentFlags[row]) : 0
831
994
  }
832
995
 
833
- /** Empties the staging row, for the next packet. */
996
+ /**
997
+ * Empties the staging row, for the next packet.
998
+ * @internal Read in quic.ts outside the class.
999
+ */
834
1000
  clearStaged(): void {
835
1001
  this.stagedEliciting = false
836
1002
  this.setCrypto(this.staging, QUIC_CONN_NONE, QUIC_CONN_FROM)
@@ -839,14 +1005,17 @@ class QuicConnSpace {
839
1005
  }
840
1006
 
841
1007
  /** Sets row `row`'s CRYPTO frame. */
842
- setCrypto(row: i32, offset: i64, length: i32): void {
1008
+ private setCrypto(row: i32, offset: i64, length: i32): void {
843
1009
  if (row >= 0 && row < toI32(this.sentCryptoOffset.length) && row < toI32(this.sentCryptoLength.length)) {
844
1010
  this.sentCryptoOffset[row] = offset
845
1011
  this.sentCryptoLength[row] = length
846
1012
  }
847
1013
  }
848
1014
 
849
- /** Sets row `row`'s bits. */
1015
+ /**
1016
+ * Sets row `row`'s bits.
1017
+ * @internal Read in quic.ts outside the class.
1018
+ */
850
1019
  setFlags(row: i32, flags: i32): void {
851
1020
  if (row >= 0 && row < toI32(this.sentFlags.length)) {
852
1021
  this.sentFlags[row] = toU8(flags)
@@ -854,7 +1023,7 @@ class QuicConnSpace {
854
1023
  }
855
1024
 
856
1025
  /** Sets how many STREAM chunks and control frames row `row` holds. */
857
- setCounts(row: i32, streams: i32, control: i32): void {
1026
+ private setCounts(row: i32, streams: i32, control: i32): void {
858
1027
  if (row >= 0 && row < toI32(this.sentStreamCount.length) && row < toI32(this.sentControlCount.length)) {
859
1028
  this.sentStreamCount[row] = streams
860
1029
  this.sentControlCount[row] = control
@@ -862,7 +1031,7 @@ class QuicConnSpace {
862
1031
  }
863
1032
 
864
1033
  /** Sets STREAM chunk `j` of row `row`. */
865
- setChunk(row: i32, j: i32, id: i64, offset: i64, length: i32, fin: boolean): void {
1034
+ private setChunk(row: i32, j: i32, id: i64, offset: i64, length: i32, fin: boolean): void {
866
1035
  const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
867
1036
  if (
868
1037
  at >= 0 &&
@@ -879,7 +1048,7 @@ class QuicConnSpace {
879
1048
  }
880
1049
 
881
1050
  /** Sets control frame `j` of row `row`. */
882
- setControl(row: i32, j: i32, kind: i32, value: i64): void {
1051
+ private setControl(row: i32, j: i32, kind: i32, value: i64): void {
883
1052
  const at: i32 = row * QUIC_CONN_PACKET_CONTROL + j
884
1053
  if (at >= 0 && at < toI32(this.sentControlKind.length) && at < toI32(this.sentControlValue.length)) {
885
1054
  this.sentControlKind[at] = toU8(kind)
@@ -887,13 +1056,19 @@ class QuicConnSpace {
887
1056
  }
888
1057
  }
889
1058
 
890
- /** Stages a CRYPTO frame at `offset`, `length` bytes, in the packet being built. */
1059
+ /**
1060
+ * Stages a CRYPTO frame at `offset`, `length` bytes, in the packet being built.
1061
+ * @internal Read in quic.ts outside the class.
1062
+ */
891
1063
  stageCrypto(offset: i64, length: i32): void {
892
1064
  this.setCrypto(this.staging, offset, length)
893
1065
  this.stagedEliciting = true
894
1066
  }
895
1067
 
896
- /** Stages a STREAM chunk in the packet being built; the caller keeps under `QUIC_CONN_PACKET_STREAMS`. */
1068
+ /**
1069
+ * Stages a STREAM chunk in the packet being built; the caller keeps under `QUIC_CONN_PACKET_STREAMS`.
1070
+ * @internal Read in quic.ts outside the class.
1071
+ */
897
1072
  stageChunk(id: i64, offset: i64, length: i32, fin: boolean): void {
898
1073
  const streams: i32 = this.streamCount(this.staging)
899
1074
  this.setChunk(this.staging, streams, id, offset, length, fin)
@@ -901,7 +1076,10 @@ class QuicConnSpace {
901
1076
  this.stagedEliciting = true
902
1077
  }
903
1078
 
904
- /** Stages a control frame in the packet being built; the caller keeps under `QUIC_CONN_PACKET_CONTROL`. */
1079
+ /**
1080
+ * Stages a control frame in the packet being built; the caller keeps under `QUIC_CONN_PACKET_CONTROL`.
1081
+ * @internal Read in quic.ts outside the class.
1082
+ */
905
1083
  stageControl(kind: i32, value: i64): void {
906
1084
  const control: i32 = this.controlCount(this.staging)
907
1085
  this.setControl(this.staging, control, kind, value)
@@ -909,7 +1087,10 @@ class QuicConnSpace {
909
1087
  this.stagedEliciting = true
910
1088
  }
911
1089
 
912
- /** Copies the staging row to row `row`, the slot of the packet just sealed. */
1090
+ /**
1091
+ * Copies the staging row to row `row`, the slot of the packet just sealed.
1092
+ * @internal Read in quic.ts outside the class.
1093
+ */
913
1094
  commitStaged(row: i32): void {
914
1095
  const from: i32 = this.staging
915
1096
  this.setCrypto(row, this.cryptoOffset(from), this.cryptoLength(from))
@@ -944,7 +1125,10 @@ class QuicConnSpace {
944
1125
  }
945
1126
  }
946
1127
 
947
- /** Queues CRYPTO bytes `[offset, offset + length)` to be sent again, merged with what is queued already. */
1128
+ /**
1129
+ * Queues CRYPTO bytes `[offset, offset + length)` to be sent again, merged with what is queued already.
1130
+ * @internal Read in quic.ts outside the class.
1131
+ */
948
1132
  resendCrypto(offset: i64, length: i32): void {
949
1133
  if (length <= 0 || this.discarded) {
950
1134
  return
@@ -963,7 +1147,10 @@ class QuicConnSpace {
963
1147
  }
964
1148
  }
965
1149
 
966
- /** How many CRYPTO bytes are waiting to be sent. */
1150
+ /**
1151
+ * How many CRYPTO bytes are waiting to be sent.
1152
+ * @internal Read in quic.ts outside the class.
1153
+ */
967
1154
  cryptoUnsent(): i32 {
968
1155
  return this.cryptoOutLength - this.cryptoOutHead
969
1156
  }
@@ -1031,6 +1218,11 @@ const quicConnWipePacketKey = (keys: QuicKeys | null): void => {
1031
1218
  * `nish/net/quic-listener` derives the same token from a packet's ID alone
1032
1219
  * once the connection is gone, which is what lets a server that lost its
1033
1220
  * state end the connection.
1221
+ *
1222
+ * @param key The server's static reset key, `QUIC_CONN_STATIC_KEY_SIZE` bytes
1223
+ * (`QuicServerConfig.statelessResetKey`).
1224
+ * @param cid The connection ID the token is for, all of its bytes.
1225
+ * @returns A fresh 16-byte token (`QUIC_RESET_TOKEN_SIZE`); the full MAC it was cut from is wiped.
1034
1226
  */
1035
1227
  export const quicStatelessResetToken = (key: u8[], cid: u8[]): u8[] => {
1036
1228
  const mac: u8[] = hmacSha256(key, cid)
@@ -1044,6 +1236,14 @@ export const quicStatelessResetToken = (key: u8[], cid: u8[]): u8[] => {
1044
1236
  * `out[outAt ..]`, computed in a connection's own HMAC scratch inside an
1045
1237
  * arena block, so issuing an ID keeps nothing (QUIC-3). The scratch and the
1046
1238
  * full MAC are wiped before it returns.
1239
+ *
1240
+ * @param mac The connection's HMAC-SHA256 scratch, wiped on return.
1241
+ * @param key The server's static reset key, `QUIC_CONN_STATIC_KEY_SIZE` bytes.
1242
+ * @param cid The array holding the connection ID.
1243
+ * @param at Where the ID starts in `cid`.
1244
+ * @param length The ID's length in bytes, at most 20: the caller's to keep, as nothing checks it.
1245
+ * @param out Where the 16-byte token goes; bytes that would fall past its end are not written.
1246
+ * @param outAt Where in `out` the token starts.
1047
1247
  */
1048
1248
  export const quicConnResetTokenInto = (
1049
1249
  mac: HmacSha256Scratch,
@@ -1080,6 +1280,44 @@ const quicConnRefill = (to: u8[], from: u8[], at: i32, length: i32): void => {
1080
1280
  }
1081
1281
  }
1082
1282
 
1283
+ /** Copies `length` bytes from `from[fromAt]` to `to[toAt]`, as far as both arrays reach. */
1284
+ const quicConnCopyAt = (to: u8[], toAt: i32, from: u8[], fromAt: i32, length: i32): void => {
1285
+ for (let k: i32 = 0; k < length; k += 1) {
1286
+ const i: i32 = toAt + k
1287
+ const j: i32 = fromAt + k
1288
+ if (i >= 0 && i < toI32(to.length) && j >= 0 && j < toI32(from.length)) {
1289
+ to[i] = from[j]
1290
+ }
1291
+ }
1292
+ }
1293
+
1294
+ /** Sets every byte of `bytes` to 0. */
1295
+ const quicConnZeroAt = (bytes: u8[]): void => {
1296
+ for (let k: i32 = 0; k < toI32(bytes.length); k += 1) {
1297
+ bytes[k] = 0
1298
+ }
1299
+ }
1300
+
1301
+ /** Whether `a` and `b` hold the same `nish:net` address; `portOnly` compares the sixteen address bytes alone. */
1302
+ const quicConnSameAddress = (a: u8[], b: u8[], portOnly: boolean): boolean => {
1303
+ const n: i32 = portOnly ? QUIC_CONN_ADDRESS_SIZE - 2 : QUIC_CONN_ADDRESS_SIZE
1304
+ if (toI32(a.length) < n || toI32(b.length) < n) {
1305
+ return false
1306
+ }
1307
+ let same: boolean = true
1308
+ for (let k: i32 = 0; k < n && k < toI32(a.length) && k < toI32(b.length); k += 1) {
1309
+ same = same && a[k] === b[k]
1310
+ }
1311
+ return same
1312
+ }
1313
+
1314
+ /** Whether a frame of `type` is a probing frame (RFC 9000 §9.1), which a packet may carry without moving the connection. */
1315
+ const quicConnProbing = (type: i32): boolean =>
1316
+ type === QUIC_FRAME_PATH_CHALLENGE ||
1317
+ type === QUIC_FRAME_PATH_RESPONSE ||
1318
+ type === QUIC_FRAME_NEW_CONNECTION_ID ||
1319
+ type === QUIC_FRAME_PADDING
1320
+
1083
1321
  /** Zeroes the bytes a `Secret` field holds, for `exposeWith` to run outside the connection's `wipe()`; answers `answer`. */
1084
1322
  const quicConnZeroHeld = (held: u8[], answer: i32): i32 => {
1085
1323
  wipe(held)
@@ -1129,33 +1367,38 @@ const quicConnConfigFits = (config: QuicServerConfig): boolean =>
1129
1367
  * that runs many connections routes datagrams by (`ownsConnectionId`).
1130
1368
  */
1131
1369
  export class QuicConnection {
1132
- config: QuicServerConfig
1370
+ private config: QuicServerConfig
1133
1371
  /** The error code the connection closed with: a transport error, `0x100 + alert`, or the application's code. */
1134
1372
  error: i64 = 0
1135
1373
  /** For a transport error: the type of the frame that caused it, or 0. */
1136
- errorFrameType: i64 = 0
1137
- serverRandom: u8[]
1374
+ private errorFrameType: i64 = 0
1375
+ private serverRandom: u8[]
1138
1376
  /** The x25519 private key `begin` takes from the entropy, until the handshake hands it to `TlsServer`. */
1139
1377
  readonly ephemeral: Secret<u8[]>
1378
+ /** The 32-byte HMAC key, taken from the entropy, that each new local connection ID is derived from; `release` wipes it. */
1140
1379
  cidSeed: u8[]
1141
- /** The DCID of the client's first Initial, which the Initial keys come from: its first `originalDcidLength` bytes. */
1380
+ /**
1381
+ * The DCID of the client's first Initial, which the Initial keys come from: its first `originalDcidLength` bytes.
1382
+ * @internal Read by http3-server.ts.
1383
+ */
1142
1384
  originalDcid: u8[]
1143
1385
  /** The SCID of the client's first Initial: where long-header packets go, and what its transport parameters must name. */
1144
- peerScid: u8[]
1386
+ private peerScid: u8[]
1145
1387
  /** The server's first connection ID, the SCID of every long-header packet it sends. */
1146
- localScid: u8[]
1388
+ private localScid: u8[]
1389
+ /** The `TlsServer` running this connection's handshake: null until the client's first Initial has opened, and again after `reset`. */
1147
1390
  tls: TlsServer | null = null
1148
1391
  /** The slot's `TlsServer`, made by its first handshake and `restart`ed by every one after (QUIC-3). */
1149
1392
  tlsSlot: TlsServer | null = null
1150
1393
  /** Its configuration, made once: the parameters it carries are `localEncoded`, rewritten for each connection. */
1151
- tlsConfig: TlsServerConfig
1394
+ private tlsConfig: TlsServerConfig
1152
1395
  /** The server's transport parameters, set for each connection, and their encoding. */
1153
1396
  localParameters: QuicTransportParameters
1154
1397
  localEncoded: u8[]
1155
1398
  /** The client's transport parameters, parsed into the slot's own object. */
1156
- parsedParameters: QuicTransportParameters
1399
+ private parsedParameters: QuicTransportParameters
1157
1400
  /** Where every key derivation and HMAC of the connection runs. */
1158
- kdf: HkdfScratch
1401
+ private kdf: HkdfScratch
1159
1402
  /** The Initial secrets of RFC 9001 §5.2, the client's and the server's. */
1160
1403
  initialClient: u8[]
1161
1404
  initialServer: u8[]
@@ -1174,8 +1417,8 @@ export class QuicConnection {
1174
1417
  readonly nextReadSecret384: Secret<u8[]>
1175
1418
  readonly writeSecret384: Secret<u8[]>
1176
1419
  /** A connection ID being issued and its stateless reset token, before the table copies them. */
1177
- cidScratch: u8[]
1178
- tokenScratch: u8[]
1420
+ private cidScratch: u8[]
1421
+ private tokenScratch: u8[]
1179
1422
  initial: QuicConnSpace
1180
1423
  handshake: QuicConnSpace
1181
1424
  application: QuicConnSpace
@@ -1185,13 +1428,13 @@ export class QuicConnection {
1185
1428
  /** The client's transport parameters, once the handshake has checked them; until then, every default. */
1186
1429
  peerParameters: QuicTransportParameters
1187
1430
  /** The defaults `peerParameters` starts from, made once and set back by `reset`. */
1188
- defaultParameters: QuicTransportParameters
1431
+ private defaultParameters: QuicTransportParameters
1189
1432
  /** Bytes received and sent, for the anti-amplification limit (RFC 9000 §8.1). */
1190
1433
  bytesReceived: i64 = 0
1191
1434
  bytesSent: i64 = 0
1192
1435
  /** The ALPN protocol the handshake chose. */
1193
1436
  alpn: string = ""
1194
- /** The client's `server_name`, or empty. */
1437
+ /** The client's `server_name` the handshake read, or empty when it sent none. */
1195
1438
  serverName: string = ""
1196
1439
  /** The streams, both ways (`nish/net/quic-stream`). */
1197
1440
  streams: QuicStreams
@@ -1199,22 +1442,58 @@ export class QuicConnection {
1199
1442
  datagramsOut: QuicDatagramQueue
1200
1443
  datagramsIn: QuicDatagramQueue
1201
1444
  /** The CRYPTO bytes the client sent, put back in order. */
1202
- cryptoIn: QuicConnReassembly
1445
+ private cryptoIn: QuicConnReassembly
1203
1446
  /** PATH_CHALLENGE data to answer: a ring of four, eight bytes each, `pathCount` from `pathHead`. */
1204
- pathData: u8[]
1205
- frame: QuicFrame
1447
+ private pathData: u8[]
1448
+ /**
1449
+ * The client's address (RFC 9000 §9), each in `nish:net`'s 18-byte form,
1450
+ * for a carrier that passes one to `receiveWindowFrom`: `pathCurrent` is
1451
+ * where this connection's datagrams go now (`sendAddress`), and
1452
+ * `pathValidated` the last address the client proved it receives at — the
1453
+ * handshake's, or one a PATH_RESPONSE answered. `pathArrival` is the
1454
+ * datagram being read's. Made once and overwritten in place.
1455
+ */
1456
+ private pathCurrent: u8[]
1457
+ pathValidated: u8[]
1458
+ private pathArrival: u8[]
1459
+ /**
1460
+ * A PATH_CHALLENGE that came from another address in a datagram that
1461
+ * moved nothing (§9.1): answered there by `takeProbeInto`, from
1462
+ * `probeData`, within `probeBudget` bytes, three times what came from
1463
+ * `probeAddress` (§8.1). Only the latest such challenge is kept. A
1464
+ * response owed on `pathCurrent` when the connection moves goes back
1465
+ * the same way (`sendResponsesBack`).
1466
+ */
1467
+ probeAddress: u8[]
1468
+ private probeData: u8[]
1469
+ /**
1470
+ * The last `QUIC_CONN_CHALLENGES` PATH_CHALLENGE data sent on the path
1471
+ * being validated, eight bytes each, `challengeCount` of them, the latest
1472
+ * at `(challengesDrawn - 1) % QUIC_CONN_CHALLENGES`: each drawn from the
1473
+ * ID seed's HMAC under `QUIC_CONN_CHALLENGE_SEQUENCE`, so unguessable.
1474
+ */
1475
+ private challengeData: u8[]
1476
+ /** Bytes received from and sent to the path being validated, for its own 3x limit (§9.3, §8.1). */
1477
+ pathReceived: i64 = 0
1478
+ pathSent: i64 = 0
1479
+ private probeBudget: i64 = 0
1480
+ /** When the PATH_CHALLENGE goes again with fresh data, and when validation gives up (§8.2.4); -1 when not validating. */
1481
+ challengeResendAt: i64 = -1
1482
+ challengeUntil: i64 = -1
1483
+ challengesDrawn: i64 = 0
1484
+ private frame: QuicFrame
1206
1485
  /** The header and the packet numbers of the packet being read, reused for every one. */
1207
- header: QuicHeader
1208
- packet: QuicPacket
1486
+ private header: QuicHeader
1487
+ private packet: QuicPacket
1209
1488
  /** For a connection `acceptRetry` set up: the DCID of the client's Initial before the Retry, and the Retry's SCID. */
1210
- retryOriginalDcid: u8[]
1211
- retryScid: u8[]
1489
+ private retryOriginalDcid: u8[]
1490
+ private retryScid: u8[]
1212
1491
  /** An empty array, which a cleared secret or ID is set to. */
1213
- none: u8[]
1492
+ private none: u8[]
1214
1493
  /** The latest time the caller gave, in milliseconds; time never runs backwards here. */
1215
1494
  now: i64 = 0
1216
1495
  /** When the idle timer last restarted (RFC 9000 §10.1), or -1 before the first packet. */
1217
- idleSince: i64 = -1
1496
+ private idleSince: i64 = -1
1218
1497
  /**
1219
1498
  * The other read keys of the Application Data space (RFC 9001 §6.3):
1220
1499
  * the next generation's while `otherIsNext`, and for a probe timeout
@@ -1222,23 +1501,23 @@ export class QuicConnection {
1222
1501
  */
1223
1502
  otherReadKeys: QuicKeys | null = null
1224
1503
  /** The lowest and highest packet numbers opened with the current read keys, or -1. */
1225
- readPhaseLowest: i64 = -1
1226
- readPhaseHighest: i64 = -1
1504
+ private readPhaseLowest: i64 = -1
1505
+ private readPhaseHighest: i64 = -1
1227
1506
  /** The first packet number sent with the current write keys. */
1228
- writePhaseFirst: i64 = 0
1507
+ private writePhaseFirst: i64 = 0
1229
1508
  /** When the previous read keys go and the next are derived, or -1. */
1230
- keyRetainUntil: i64 = -1
1509
+ private keyRetainUntil: i64 = -1
1231
1510
  /**
1232
1511
  * When a closed connection's closing or draining period ends (RFC 9000
1233
1512
  * §10.2), and `runClocks` wipes every key it kept for it, or -1: before
1234
1513
  * the close, while a close this side owes has not gone out, and once the
1235
1514
  * keys are wiped.
1236
1515
  */
1237
- closingUntil: i64 = -1
1516
+ private closingUntil: i64 = -1
1238
1517
  /** The packet number of a client key update read but not applied yet, or -1. */
1239
- phasePending: i64 = -1
1518
+ private phasePending: i64 = -1
1240
1519
  /** The largest DATAGRAM frame the client takes (its `max_datagram_frame_size`), 0 for none. */
1241
- peerMaxDatagramFrame: i64 = 0
1520
+ private peerMaxDatagramFrame: i64 = 0
1242
1521
  /**
1243
1522
  * The AEAD limits this connection keeps (RFC 9001 §6.6): packets one 1-RTT
1244
1523
  * write key seals, and packets that fail to authenticate over the
@@ -1251,17 +1530,6 @@ export class QuicConnection {
1251
1530
  /** Packets sealed under the current 1-RTT write key, and packets that failed to authenticate, against those limits. */
1252
1531
  sealedUnderKey: i64 = 0
1253
1532
  authFailures: i64 = 0
1254
- /**
1255
- * ECN (RFC 9000 §13.4): `ecnMarking` is the carrier's to set when it sends
1256
- * this connection's datagrams with the ECN bits of `datagramEcn`, which
1257
- * each `takeDatagramInto` sets for the datagram it wrote: ECT(0) while
1258
- * loss recovery's `ecnCodepoint()` asks for it, 0 otherwise and always
1259
- * while `ecnMarking` is false. Every packet of a marked datagram is counted
1260
- * as marked, and an ACK_ECN's counts are validated against them. `reset`
1261
- * keeps `ecnMarking`, which is the carrier's, and clears the rest.
1262
- */
1263
- ecnMarking: boolean = false
1264
- datagramEcn: i32 = 0
1265
1533
  /**
1266
1534
  * The next Application Data packet number skipped (RFC 9000 §21.4), or -1
1267
1535
  * before the 1-RTT keys; a test may set it to force one. `skipped` holds
@@ -1269,12 +1537,17 @@ export class QuicConnection {
1269
1537
  * the next goes, and `skipsDrawn` how many distances were drawn.
1270
1538
  */
1271
1539
  nextSkip: i64 = -1
1272
- skipped: i64[]
1540
+ private skipped: i64[]
1273
1541
  skipsDrawn: i64 = 0
1542
+ /** How many of `challengeData`'s slots hold a challenge sent on the path being validated. */
1543
+ private challengeCount: i32 = 0
1544
+ /** @internal Read by http3-server.ts. */
1274
1545
  originalDcidLength: i32 = 0
1275
- peerScidLength: i32 = 0
1276
- pathHead: i32 = 0
1546
+ private peerScidLength: i32 = 0
1547
+ private pathHead: i32 = 0
1548
+ /** How many PATH_CHALLENGE payloads wait to be answered, 0 to 4. */
1277
1549
  pathCount: i32 = 0
1550
+ /** Where the connection is in its life: one of the `QUIC_STATE_*` constants. */
1278
1551
  state: i32 = 0
1279
1552
  /** Packets dropped without closing the connection: unparseable, unauthenticated, duplicated, or for keys not held. */
1280
1553
  dropped: i32 = 0
@@ -1288,34 +1561,60 @@ export class QuicConnection {
1288
1561
  /** Handshake data sent again early, against `QUIC_CONN_EARLY_RESENDS` (RFC 9002 §6.2.3). */
1289
1562
  earlyResends: i32 = 0
1290
1563
  /** The level at which the packet just read showed the client lacks the server's handshake data, or -1. */
1291
- resendLevel: i32 = -1
1564
+ private resendLevel: i32 = -1
1565
+ /**
1566
+ * ECN (RFC 9000 §13.4): `ecnMarking` is the carrier's to set when it sends
1567
+ * this connection's datagrams with the ECN bits of `datagramEcn`, which
1568
+ * each `takeDatagramInto` sets for the datagram it wrote: ECT(0) while
1569
+ * loss recovery's `ecnCodepoint()` asks for it, 0 otherwise and always
1570
+ * while `ecnMarking` is false. Every packet of a marked datagram is counted
1571
+ * as marked, and an ACK_ECN's counts are validated against them. `reset`
1572
+ * keeps `ecnMarking`, which is the carrier's, and clears the rest.
1573
+ */
1574
+ datagramEcn: i32 = 0
1575
+ ecnMarking: boolean = false
1292
1576
  /** Whether `error` is an application code (CONNECTION_CLOSE 0x1d) rather than a transport error. */
1293
1577
  errorIsApplication: boolean = false
1294
1578
  /** Whether the one CONNECTION_CLOSE this side owes has gone out. */
1295
- closeSent: boolean = false
1579
+ private closeSent: boolean = false
1296
1580
  /** Whether the client's address is validated: a Handshake packet from it was processed. */
1297
1581
  addressValidated: boolean = false
1298
1582
  /** Whether the handshake is complete, which for a server is also confirmed (RFC 9001 §4.1.2). */
1299
1583
  handshakeComplete: boolean = false
1300
- handshakeDonePending: boolean = false
1584
+ private handshakeDonePending: boolean = false
1301
1585
  /**
1302
1586
  * Whether `afterTls` has taken the application traffic secrets out of
1303
1587
  * `TlsServer`. It takes them once: `wipeSecret` leaves them known, so a
1304
1588
  * second take would derive the 1-RTT keys from the zeros it left.
1305
1589
  */
1306
- applicationTaken: boolean = false
1590
+ private applicationTaken: boolean = false
1307
1591
  /** Whether the connection was set up by `acceptRetry`. */
1308
- retried: boolean = false
1592
+ private retried: boolean = false
1309
1593
  /** Whether an ack-eliciting packet went out since the last packet was received. */
1310
- elicitingSent: boolean = false
1594
+ private elicitingSent: boolean = false
1311
1595
  /** Whether `otherReadKeys` are the next generation's rather than the previous one's. */
1312
1596
  otherIsNext: boolean = false
1313
1597
  /** The Key Phase bit of the current read keys, and of the current write keys. */
1314
1598
  readPhase: boolean = false
1315
1599
  writePhase: boolean = false
1316
1600
  /** Whether the packet just read brought CRYPTO bytes for TLS, or retired an ID that wants replacing. */
1317
- cryptoArrived: boolean = false
1318
- topUpOwed: boolean = false
1601
+ private cryptoArrived: boolean = false
1602
+ private topUpOwed: boolean = false
1603
+ /** Whether `pathCurrent` holds the client's address: the carrier passes addresses, and a first Initial gave one. */
1604
+ pathKnown: boolean = false
1605
+ /** Whether the datagram being read came from an address other than `pathCurrent`. */
1606
+ private arrivalOther: boolean = false
1607
+ /** Whether `pathCurrent` is not validated yet: a PATH_CHALLENGE is out on it. */
1608
+ pathValidating: boolean = false
1609
+ /** Whether a PATH_CHALLENGE is due in the next datagram, and whether the one being built carries a PATH_CHALLENGE or PATH_RESPONSE. */
1610
+ private challengeOwed: boolean = false
1611
+ private pathFrameStaged: boolean = false
1612
+ /** Whether a PATH_RESPONSE is owed on `probeAddress`, and whether the datagram being read carried a challenge for it. */
1613
+ probeOwed: boolean = false
1614
+ private probeStaged: boolean = false
1615
+ /** Whether the packet being read carries a non-probing frame (§9.1), and whether a packet of the datagram moves the connection (§9.3). */
1616
+ private nonProbing: boolean = false
1617
+ private migrateOwed: boolean = false
1319
1618
 
1320
1619
  /**
1321
1620
  * A connection under `config`, with `entropy` its `QUIC_CONN_ENTROPY_SIZE`
@@ -1324,6 +1623,11 @@ export class QuicConnection {
1324
1623
  * Entropy of another length, or limits outside what `QuicServerConfig`
1325
1624
  * documents, leave the connection closing with INTERNAL_ERROR before it
1326
1625
  * reads anything; it then sends nothing.
1626
+ *
1627
+ * @param config The server's limits and keys. The connection keeps a reference and reads it for
1628
+ * its whole life, `reset`s included, so do not change it under a live connection.
1629
+ * @param entropy `QUIC_CONN_ENTROPY_SIZE` (104) random bytes for this connection's first peer;
1630
+ * zeroed in place once copied.
1327
1631
  */
1328
1632
  constructor(config: QuicServerConfig, entropy: u8[]) {
1329
1633
  this.config = config
@@ -1362,6 +1666,12 @@ export class QuicConnection {
1362
1666
  )
1363
1667
  this.cryptoIn = new QuicConnReassembly(QUIC_CONN_CRYPTO_WINDOW)
1364
1668
  this.pathData = new Array<u8>(QUIC_PATH_DATA_SIZE * 4)
1669
+ this.pathCurrent = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1670
+ this.pathValidated = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1671
+ this.pathArrival = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1672
+ this.probeAddress = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1673
+ this.probeData = new Array<u8>(QUIC_PATH_DATA_SIZE)
1674
+ this.challengeData = new Array<u8>(QUIC_PATH_DATA_SIZE * QUIC_CONN_CHALLENGES)
1365
1675
  this.frame = new QuicFrame()
1366
1676
  this.header = new QuicHeader()
1367
1677
  this.packet = new QuicPacket()
@@ -1404,6 +1714,9 @@ export class QuicConnection {
1404
1714
  * the constructor's configuration's. A slot reset this way allocates
1405
1715
  * nothing, and neither does the next handshake (QUIC-3 in
1406
1716
  * `docs/security/quic.md`).
1717
+ *
1718
+ * @param entropy `QUIC_CONN_ENTROPY_SIZE` (104) fresh random bytes for the next peer, never ones
1719
+ * used before; zeroed in place once copied.
1407
1720
  */
1408
1721
  reset(entropy: u8[]): void {
1409
1722
  this.wipeAll()
@@ -1445,6 +1758,7 @@ export class QuicConnection {
1445
1758
  this.peerScidLength = 0
1446
1759
  this.pathHead = 0
1447
1760
  this.pathCount = 0
1761
+ this.forgetPath()
1448
1762
  this.state = QUIC_STATE_WAIT_INITIAL
1449
1763
  this.dropped = 0
1450
1764
  this.keyUpdates = 0
@@ -1474,7 +1788,7 @@ export class QuicConnection {
1474
1788
  }
1475
1789
 
1476
1790
  /** Takes `entropy` (and wipes it), or closes with INTERNAL_ERROR for entropy or a configuration that does not fit. */
1477
- begin(entropy: u8[]): void {
1791
+ private begin(entropy: u8[]): void {
1478
1792
  quicCidCopy(this.serverRandom, entropy, 0, 32)
1479
1793
  exposeWith(this.ephemeral, entropy, quicConnEphemeralIn)
1480
1794
  quicCidCopy(this.localScid, entropy, 64, QUIC_CONN_CID_LENGTH)
@@ -1490,13 +1804,17 @@ export class QuicConnection {
1490
1804
  }
1491
1805
 
1492
1806
  /** Counts a dropped packet; the count stops at the largest `i32` rather than overflow. */
1493
- drop(): void {
1807
+ private drop(): void {
1494
1808
  if (this.dropped < 2147483647) {
1495
1809
  this.dropped += 1
1496
1810
  }
1497
1811
  }
1498
1812
 
1499
- /** Whether the connection has closed, either way. */
1813
+ /**
1814
+ * Whether the connection has closed, either way.
1815
+ *
1816
+ * @returns True once it is closing, draining or timed out; it stays true until `reset`.
1817
+ */
1500
1818
  closed(): boolean {
1501
1819
  return (
1502
1820
  this.state === QUIC_STATE_CLOSING ||
@@ -1514,6 +1832,10 @@ export class QuicConnection {
1514
1832
  * validated, so the anti-amplification limit does not apply. Call it
1515
1833
  * before the first `receive`; answers whether it took: not once the
1516
1834
  * connection has started, and not for an ID over 20 bytes.
1835
+ *
1836
+ * @param originalDcid The DCID of the client's first Initial, from the checked Retry token; copied.
1837
+ * @param retryScid The SCID the Retry packet carried; copied.
1838
+ * @returns True when the connection took the Retry, false (and nothing changed) otherwise.
1517
1839
  */
1518
1840
  acceptRetry(originalDcid: u8[], retryScid: u8[]): boolean {
1519
1841
  if (
@@ -1529,7 +1851,10 @@ export class QuicConnection {
1529
1851
  return true
1530
1852
  }
1531
1853
 
1532
- /** Closes the connection with transport error `code`, caused by a frame of `frameType` (0 for none). */
1854
+ /**
1855
+ * Closes the connection with transport error `code`, caused by a frame of `frameType` (0 for none).
1856
+ * @internal Read by http3.ts.
1857
+ */
1533
1858
  fail(code: i64, frameType: i64): void {
1534
1859
  if (this.closed()) {
1535
1860
  return
@@ -1545,6 +1870,9 @@ export class QuicConnection {
1545
1870
  * (CONNECTION_CLOSE 0x1d; RFC 9000 §10.2). The next `takeDatagram` answers
1546
1871
  * the close, and nothing after it. Closing twice, or after the client
1547
1872
  * closed, does nothing.
1873
+ *
1874
+ * @param code The application's error code, sent in the CONNECTION_CLOSE; keeping it to 0 to 2^62 - 1 is
1875
+ * the caller's, as nothing checks it.
1548
1876
  */
1549
1877
  close(code: i64): void {
1550
1878
  if (this.closed()) {
@@ -1565,12 +1893,12 @@ export class QuicConnection {
1565
1893
  * `deadline()` names, so that a connection nobody `release()`s does not
1566
1894
  * keep them.
1567
1895
  */
1568
- startClosingPeriod(): void {
1896
+ private startClosingPeriod(): void {
1569
1897
  this.closingUntil = this.now + this.recovery.probeTimeout() * 3
1570
1898
  }
1571
1899
 
1572
1900
  /** The space of packets of `type`, or `null` for a 0-RTT or Retry packet. */
1573
- spaceOf(type: i32): QuicConnSpace | null {
1901
+ private spaceOf(type: i32): QuicConnSpace | null {
1574
1902
  if (type === QUIC_PACKET_INITIAL) {
1575
1903
  return this.initial
1576
1904
  }
@@ -1584,7 +1912,7 @@ export class QuicConnection {
1584
1912
  }
1585
1913
 
1586
1914
  /** The space of TLS level `level`. */
1587
- spaceAt(level: i32): QuicConnSpace {
1915
+ private spaceAt(level: i32): QuicConnSpace {
1588
1916
  if (level === TLS_LEVEL_INITIAL) {
1589
1917
  return this.initial
1590
1918
  }
@@ -1596,12 +1924,22 @@ export class QuicConnection {
1596
1924
  * connection: one of its active connection IDs, or, until the handshake is
1597
1925
  * done, the DCID of the client's first Initial. A closed connection still
1598
1926
  * answers for its IDs; the caller drops it once it is done with it.
1927
+ *
1928
+ * @param dcid The destination connection ID of the datagram's first packet, all of its bytes.
1929
+ * @returns True when the datagram should be handed to this connection.
1599
1930
  */
1600
1931
  ownsConnectionId(dcid: u8[]): boolean {
1601
1932
  return this.ownsConnectionIdAt(dcid, QUIC_CONN_FROM, toI32(dcid.length))
1602
1933
  }
1603
1934
 
1604
- /** `ownsConnectionId` of the ID `buf[at .. at + length)`, read in place, so a carrier routes without a copy. */
1935
+ /**
1936
+ * `ownsConnectionId` of the ID `buf[at .. at + length)`, read in place, so a carrier routes without a copy.
1937
+ *
1938
+ * @param buf The array holding the ID, usually the received datagram.
1939
+ * @param at Where the ID starts in `buf`.
1940
+ * @param length The ID's length in bytes.
1941
+ * @returns True when the datagram should be handed to this connection.
1942
+ */
1605
1943
  ownsConnectionIdAt(buf: u8[], at: i32, length: i32): boolean {
1606
1944
  if (this.cids.ownsLocalAt(buf, at, length)) {
1607
1945
  return true
@@ -1614,7 +1952,13 @@ export class QuicConnection {
1614
1952
  )
1615
1953
  }
1616
1954
 
1617
- /** `receiveWindow` of a whole datagram. */
1955
+ /**
1956
+ * `receiveWindow` of a whole datagram.
1957
+ *
1958
+ * @param datagram The UDP payload, read and never written.
1959
+ * @param now The caller's monotonic time in milliseconds.
1960
+ * @returns 0, or the transport or application error the connection has closed with.
1961
+ */
1618
1962
  receive(datagram: u8[], now: i64): i64 {
1619
1963
  return this.receiveWindow(datagram, QUIC_CONN_FROM, toI32(datagram.length), now)
1620
1964
  }
@@ -1629,8 +1973,31 @@ export class QuicConnection {
1629
1973
  * cannot be used is dropped and counted (see the module header). Once the
1630
1974
  * connection has closed, or its idle timeout has passed by `now`, every
1631
1975
  * datagram is ignored.
1976
+ *
1977
+ * @param buf The array holding the datagram; read, never written, and not kept past the call.
1978
+ * @param off Where the datagram starts in `buf`.
1979
+ * @param len The datagram's length in bytes; a client's first Initial needs at least 1200.
1980
+ * @param now The caller's monotonic time in milliseconds.
1981
+ * @returns 0, or the error the connection has closed with (also once it was already closed).
1632
1982
  */
1633
1983
  receiveWindow(buf: u8[], off: i32, len: i32, now: i64): i64 {
1984
+ return this.receiveWindowFrom(buf, off, len, this.none, now)
1985
+ }
1986
+
1987
+ /**
1988
+ * `receiveWindow` of a datagram that came from `address`, an 18-byte
1989
+ * `nish:net` address: the connection follows the client from one address
1990
+ * to another (RFC 9000 §9) — see "Paths" in the module header. An
1991
+ * address of any other length is no address, as `receiveWindow` gives.
1992
+ *
1993
+ * @param buf The array holding the datagram; read, never written, and not kept past the call.
1994
+ * @param off Where the datagram starts in `buf`.
1995
+ * @param len The datagram's length in bytes; a client's first Initial needs at least 1200.
1996
+ * @param address The 18-byte `nish:net` address the datagram came from; copied, not kept.
1997
+ * @param now The caller's monotonic time in milliseconds.
1998
+ * @returns 0, or the error the connection has closed with (also once it was already closed).
1999
+ */
2000
+ receiveWindowFrom(buf: u8[], off: i32, len: i32, address: u8[], now: i64): i64 {
1634
2001
  this.runClocks(now)
1635
2002
  if (this.closed()) {
1636
2003
  return this.error
@@ -1644,6 +2011,10 @@ export class QuicConnection {
1644
2011
  this.drop()
1645
2012
  return 0
1646
2013
  }
2014
+ if (!this.notePath(address)) {
2015
+ this.drop()
2016
+ return 0
2017
+ }
1647
2018
  const end: i32 = off + len
1648
2019
  let at: i32 = off
1649
2020
  let counted: boolean = false
@@ -1665,6 +2036,11 @@ export class QuicConnection {
1665
2036
  if (counted) {
1666
2037
  this.bytesReceived = this.bytesReceived + toI64(len)
1667
2038
  }
2039
+ if (!this.closed()) {
2040
+ this.afterPath(counted, len)
2041
+ }
2042
+ // A challenge staged from another address belongs to this datagram only.
2043
+ this.probeStaged = false
1668
2044
  // Loss recovery's timer runs after the datagram, so an acknowledgement
1669
2045
  // it carries settles what it acknowledges before a probe is owed.
1670
2046
  this.runRecoveryTimer()
@@ -1679,7 +2055,7 @@ export class QuicConnection {
1679
2055
  * `TlsServer` — is made by `establish` once the Initial has opened, so an
1680
2056
  * Initial that does not authenticate costs only its keys.
1681
2057
  */
1682
- start(buf: u8[], header: QuicHeader): boolean {
2058
+ private start(buf: u8[], header: QuicHeader): boolean {
1683
2059
  if (
1684
2060
  header.dcidLength < 8 ||
1685
2061
  header.dcidLength > QUIC_MAX_CID_LENGTH ||
@@ -1725,7 +2101,7 @@ export class QuicConnection {
1725
2101
  * `acceptRetry` set one up, and the first ID's stateless reset token
1726
2102
  * (§18.2).
1727
2103
  */
1728
- establish(): void {
2104
+ private establish(): void {
1729
2105
  const none: u8[] = this.none
1730
2106
  const token: u8[] = this.tokenScratch
1731
2107
  quicConnResetTokenInto(
@@ -1783,8 +2159,9 @@ export class QuicConnection {
1783
2159
  params.initialMaxStreamDataUni = this.config.maxStreamsUni > 0 ? this.config.maxStreamData : 0
1784
2160
  params.maxDatagramFrameSize = this.config.maxDatagramFrameSize
1785
2161
  params.activeConnectionIdLimit = this.config.activeConnectionIdLimit
1786
- // The server never migrates and asks the client not to (§9): path
1787
- // validation beyond answering PATH_CHALLENGE is not here.
2162
+ // The server never migrates and asks the client not to (§9). A client
2163
+ // whose address changes all the same, as a NAT rebinding changes it, is
2164
+ // followed with path validation (`migrate`), as §9 allows.
1788
2165
  params.disableActiveMigration = true
1789
2166
  quicEncodeTransportParametersInto(params, this.localEncoded)
1790
2167
  // One `TlsServer` a slot, made by its first handshake (so its flight is
@@ -1813,7 +2190,7 @@ export class QuicConnection {
1813
2190
  * One packet of a datagram. Answers whether the packet was used: whether it
1814
2191
  * authenticated as this connection's.
1815
2192
  */
1816
- receivePacket(buf: u8[], header: QuicHeader): boolean {
2193
+ private receivePacket(buf: u8[], header: QuicHeader): boolean {
1817
2194
  const type: i32 = header.type
1818
2195
  const first: boolean = this.state === QUIC_STATE_WAIT_INITIAL
1819
2196
  if (first && (type !== QUIC_PACKET_INITIAL || !this.start(buf, header))) {
@@ -1830,13 +2207,14 @@ export class QuicConnection {
1830
2207
  }
1831
2208
 
1832
2209
  /** Undoes `start`, for a first Initial that turned out not to authenticate. */
1833
- unstart(): void {
2210
+ private unstart(): void {
1834
2211
  this.state = QUIC_STATE_WAIT_INITIAL
1835
2212
  this.addressValidated = false
1836
2213
  this.idleSince = -1
1837
2214
  this.initial.reset()
1838
2215
  this.originalDcidLength = 0
1839
2216
  this.peerScidLength = 0
2217
+ this.pathKnown = false
1840
2218
  }
1841
2219
 
1842
2220
  /**
@@ -1847,7 +2225,7 @@ export class QuicConnection {
1847
2225
  * the CRYPTO bytes and what it answers — runs after it. Answers whether
1848
2226
  * the packet was used.
1849
2227
  */
1850
- openPacket(buf: u8[], header: QuicHeader, first: boolean): boolean {
2228
+ private openPacket(buf: u8[], header: QuicHeader, first: boolean): boolean {
1851
2229
  const type: i32 = header.type
1852
2230
  const space: QuicConnSpace | null = this.spaceOf(type)
1853
2231
  if (space === null || !this.addressedHere(buf, header)) {
@@ -1918,7 +2296,13 @@ export class QuicConnection {
1918
2296
  * an allocation, which is what lets the block release the packet's
1919
2297
  * temporaries. Answers whether the packet was used rather than dropped.
1920
2298
  */
1921
- openScoped(buf: u8[], header: QuicHeader, space: QuicConnSpace, keys: QuicKeys, first: boolean): boolean {
2299
+ private openScoped(
2300
+ buf: u8[],
2301
+ header: QuicHeader,
2302
+ space: QuicConnSpace,
2303
+ keys: QuicKeys,
2304
+ first: boolean
2305
+ ): boolean {
1922
2306
  const packet: QuicPacket = this.packet
1923
2307
  // Every key generation shares the header-protection key (RFC 9001 §6),
1924
2308
  // so the current keys take it off whatever the Key Phase bit says.
@@ -1957,10 +2341,17 @@ export class QuicConnection {
1957
2341
  if (type === QUIC_PACKET_SHORT && !this.notePhase(pn, other)) {
1958
2342
  return true
1959
2343
  }
2344
+ const largest: i64 = space.received.largest
2345
+ this.nonProbing = false
1960
2346
  const eliciting: boolean = this.receiveFrames(space, type, payload, buf, header)
1961
2347
  if (this.closed()) {
1962
2348
  return true
1963
2349
  }
2350
+ // RFC 9000 §9.3: the client's newest non-probing packet, from another
2351
+ // address, moves the connection there; an older one, or a probe, does not.
2352
+ if (type === QUIC_PACKET_SHORT && this.arrivalOther && this.nonProbing && pn > largest) {
2353
+ this.migrateOwed = true
2354
+ }
1964
2355
  // RFC 9002 §6.2.3: a client that sends an ack-eliciting Handshake packet
1965
2356
  // while the server's Handshake data is in flight may not have it all.
1966
2357
  if (eliciting && type === QUIC_PACKET_HANDSHAKE) {
@@ -1983,7 +2374,7 @@ export class QuicConnection {
1983
2374
  * already had — and an update past `QUIC_CONN_MAX_KEY_UPDATES` is too.
1984
2375
  * Answers whether the connection is still open.
1985
2376
  */
1986
- notePhase(pn: i64, other: boolean): boolean {
2377
+ private notePhase(pn: i64, other: boolean): boolean {
1987
2378
  if (other && !this.otherIsNext) {
1988
2379
  if (this.readPhaseLowest >= 0 && pn > this.readPhaseLowest) {
1989
2380
  this.fail(QUIC_ERROR_KEY_UPDATE, QUIC_CONN_NONE)
@@ -2018,7 +2409,7 @@ export class QuicConnection {
2018
2409
  * update, before anything acknowledges the packet; the read keys move on,
2019
2410
  * and the previous ones are kept for a probe timeout.
2020
2411
  */
2021
- applyPhase(pn: i64): void {
2412
+ private applyPhase(pn: i64): void {
2022
2413
  if (this.writePhase === this.readPhase) {
2023
2414
  this.keyUpdates = this.keyUpdates + 1
2024
2415
  if (!this.updateWriteKeys()) {
@@ -2050,7 +2441,7 @@ export class QuicConnection {
2050
2441
  * key, IV and secret wiped. Answers whether it could, which it cannot only
2051
2442
  * for keys `quicKeys` did not make.
2052
2443
  */
2053
- updateWriteKeys(): boolean {
2444
+ private updateWriteKeys(): boolean {
2054
2445
  const keys: QuicKeys | null = this.application.writeKeys
2055
2446
  if (keys === null) {
2056
2447
  return false
@@ -2079,7 +2470,7 @@ export class QuicConnection {
2079
2470
  * before it ends, so the call keeps nothing in the arena. Answers the
2080
2471
  * slot's keys, or `null` for a secret of the wrong length.
2081
2472
  */
2082
- keysFrom(slot: QuicKeysSlot, aead: i32, held: Secret<u8[]>): QuicKeys | null {
2473
+ private keysFrom(slot: QuicKeysSlot, aead: i32, held: Secret<u8[]>): QuicKeys | null {
2083
2474
  let made: boolean = false
2084
2475
  {
2085
2476
  using _scope = arena()
@@ -2099,7 +2490,12 @@ export class QuicConnection {
2099
2490
  * block, which are zeroed before it ends. Answers the slot's keys, or
2100
2491
  * `null`, leaving `next` as it was, for keys `quicKeys` did not make.
2101
2492
  */
2102
- nextKeys(slot: QuicKeysSlot, keys: QuicKeys, current: Secret<u8[]>, next: Secret<u8[]>): QuicKeys | null {
2493
+ private nextKeys(
2494
+ slot: QuicKeysSlot,
2495
+ keys: QuicKeys,
2496
+ current: Secret<u8[]>,
2497
+ next: Secret<u8[]>
2498
+ ): QuicKeys | null {
2103
2499
  let made: boolean = false
2104
2500
  {
2105
2501
  using _scope = arena()
@@ -2124,7 +2520,7 @@ export class QuicConnection {
2124
2520
  * installed and a probe timeout after each update, never while a packet is
2125
2521
  * being opened, so what a packet's Key Phase bit says shows in no timing.
2126
2522
  */
2127
- prepareNextReadKeys(): void {
2523
+ private prepareNextReadKeys(): void {
2128
2524
  const keys: QuicKeys | null = this.application.readKeys
2129
2525
  quicConnWipePacketKey(this.otherReadKeys)
2130
2526
  this.otherReadKeys = null
@@ -2147,7 +2543,7 @@ export class QuicConnection {
2147
2543
  * the original DCID), a short header to an active local ID. Read in place
2148
2544
  * from `buf`.
2149
2545
  */
2150
- addressedHere(buf: u8[], header: QuicHeader): boolean {
2546
+ private addressedHere(buf: u8[], header: QuicHeader): boolean {
2151
2547
  if (header.type === QUIC_PACKET_SHORT) {
2152
2548
  return this.cids.ownsLocalAt(buf, header.dcidStart, header.dcidLength)
2153
2549
  }
@@ -2176,7 +2572,7 @@ export class QuicConnection {
2176
2572
  * does not parse and a frame the packet type may not carry close the
2177
2573
  * connection (RFC 9000 §12.4).
2178
2574
  */
2179
- receiveFrames(
2575
+ private receiveFrames(
2180
2576
  space: QuicConnSpace,
2181
2577
  packetType: i32,
2182
2578
  payload: u8[],
@@ -2202,6 +2598,7 @@ export class QuicConnection {
2202
2598
  return eliciting
2203
2599
  }
2204
2600
  eliciting = eliciting || quicFrameAckEliciting(frame.type)
2601
+ this.nonProbing = this.nonProbing || !quicConnProbing(frame.type)
2205
2602
  this.receiveFrame(space, frame, payload, at, buf, header)
2206
2603
  if (this.closed() || frame.end <= at) {
2207
2604
  return eliciting
@@ -2212,7 +2609,7 @@ export class QuicConnection {
2212
2609
  }
2213
2610
 
2214
2611
  /** Closes the connection with `error` from a stream frame of `type`, unless it is 0. */
2215
- failOn(error: i64, type: i64): void {
2612
+ private failOn(error: i64, type: i64): void {
2216
2613
  if (error !== QUIC_ERROR_NO_ERROR) {
2217
2614
  this.fail(error, type)
2218
2615
  }
@@ -2222,7 +2619,7 @@ export class QuicConnection {
2222
2619
  * One frame, which the packet type is allowed to carry: it starts at
2223
2620
  * `payload[frameStart]`, and the packet's header is `header` in `buf`.
2224
2621
  */
2225
- receiveFrame(
2622
+ private receiveFrame(
2226
2623
  space: QuicConnSpace,
2227
2624
  frame: QuicFrame,
2228
2625
  payload: u8[],
@@ -2302,12 +2699,17 @@ export class QuicConnection {
2302
2699
  break
2303
2700
  }
2304
2701
  case QUIC_FRAME_PATH_CHALLENGE:
2305
- this.receivePathChallenge(frame, payload)
2702
+ if (this.arrivalOther) {
2703
+ this.stageProbe(frame, payload)
2704
+ } else {
2705
+ this.receivePathChallenge(frame, payload)
2706
+ }
2306
2707
  break
2307
- // A PATH_RESPONSE answers no PATH_CHALLENGE, since the server sends none
2308
- // (§19.18); NEW_TOKEN and HANDSHAKE_DONE go only to a client (§19.7,
2309
- // §19.20). Each is a PROTOCOL_VIOLATION here.
2310
2708
  case QUIC_FRAME_PATH_RESPONSE:
2709
+ this.receivePathResponse(frame, payload)
2710
+ break
2711
+ // NEW_TOKEN and HANDSHAKE_DONE go only to a client (§19.7, §19.20): a
2712
+ // PROTOCOL_VIOLATION here.
2311
2713
  case QUIC_FRAME_NEW_TOKEN:
2312
2714
  case QUIC_FRAME_HANDSHAKE_DONE:
2313
2715
  this.fail(QUIC_ERROR_PROTOCOL_VIOLATION, type)
@@ -2327,7 +2729,7 @@ export class QuicConnection {
2327
2729
  }
2328
2730
 
2329
2731
  /** The client closed the connection: enter the draining state, sending nothing more (RFC 9000 §10.2.2). */
2330
- drain(code: i64, application: boolean): void {
2732
+ private drain(code: i64, application: boolean): void {
2331
2733
  this.state = QUIC_STATE_DRAINING
2332
2734
  this.error = code
2333
2735
  this.errorIsApplication = application
@@ -2341,7 +2743,7 @@ export class QuicConnection {
2341
2743
  * §5, §6.1, §7): each packet it newly acknowledges releases what it
2342
2744
  * carried, and each it shows lost has its frames queued again.
2343
2745
  */
2344
- receiveAck(space: QuicConnSpace, frame: QuicFrame): void {
2746
+ private receiveAck(space: QuicConnSpace, frame: QuicFrame): void {
2345
2747
  if (frame.largest >= space.nextPn || (space.level === TLS_LEVEL_APPLICATION && this.acksSkipped(frame))) {
2346
2748
  this.fail(QUIC_ERROR_PROTOCOL_VIOLATION, toI64(frame.type))
2347
2749
  return
@@ -2385,7 +2787,7 @@ export class QuicConnection {
2385
2787
  * `QUIC_FRAME_MAX_ACK_RANGES` is not, and loss recovery does not act on
2386
2788
  * it either.
2387
2789
  */
2388
- acksSkipped(frame: QuicFrame): boolean {
2790
+ private acksSkipped(frame: QuicFrame): boolean {
2389
2791
  const ranges: i64[] = frame.ackRanges
2390
2792
  for (let k: i32 = 0; k < toI32(this.skipped.length); k += 1) {
2391
2793
  const pn: i64 = this.skipped[k]
@@ -2404,7 +2806,7 @@ export class QuicConnection {
2404
2806
  * to scale is held at 2^40 microseconds first, which is still far past any
2405
2807
  * `max_ack_delay` it is then bounded by (RFC 9002 §5.3).
2406
2808
  */
2407
- ackDelayOf(field: i64): i64 {
2809
+ private ackDelayOf(field: i64): i64 {
2408
2810
  let exponent: i64 = this.peerParameters.ackDelayExponent
2409
2811
  if (exponent < 0 || exponent > 20) {
2410
2812
  exponent = 3
@@ -2415,7 +2817,7 @@ export class QuicConnection {
2415
2817
  }
2416
2818
 
2417
2819
  /** Every packet of `space` that loss recovery's last call declared lost: what each carried is queued again. */
2418
- packetsLost(space: QuicConnSpace, sent: QuicSentPackets): void {
2820
+ private packetsLost(space: QuicConnSpace, sent: QuicSentPackets): void {
2419
2821
  for (let k: i32 = 0; k < sent.lostCount; k += 1) {
2420
2822
  this.requeue(space, sent.lostSlot(k))
2421
2823
  }
@@ -2428,7 +2830,7 @@ export class QuicConnection {
2428
2830
  * one not queued already, and each stream control frame that still says
2429
2831
  * something. A DATAGRAM is never in a record, so it never goes again.
2430
2832
  */
2431
- requeue(space: QuicConnSpace, row: i32): void {
2833
+ private requeue(space: QuicConnSpace, row: i32): void {
2432
2834
  space.resendCrypto(space.cryptoOffset(row), space.cryptoLength(row))
2433
2835
  if ((space.flags(row) & QUIC_CONN_SENT_HANDSHAKE_DONE) !== 0) {
2434
2836
  this.handshakeDonePending = true
@@ -2461,7 +2863,7 @@ export class QuicConnection {
2461
2863
  }
2462
2864
 
2463
2865
  /** A lost control frame of kind `kind` (a sequence number or a stream in `value`), queued again unless it no longer matters. */
2464
- requeueControl(kind: i32, value: i64): void {
2866
+ private requeueControl(kind: i32, value: i64): void {
2465
2867
  if (kind === QUIC_CONN_CONTROL_NEW_CID) {
2466
2868
  for (const entry of this.cids.local) {
2467
2869
  if (entry.used && entry.sequence === value) {
@@ -2486,7 +2888,7 @@ export class QuicConnection {
2486
2888
  * it twice (`QUIC_CONN_HANDSHAKE_PROBES`), so that one more lost datagram
2487
2889
  * does not cost another, doubled, probe timeout.
2488
2890
  */
2489
- probe(): void {
2891
+ private probe(): void {
2490
2892
  for (let level: i32 = 0; level < 3; level += 1) {
2491
2893
  const space: QuicConnSpace = this.spaceAt(level)
2492
2894
  const sent: QuicSentPackets | null = this.recovery.space(level)
@@ -2518,7 +2920,7 @@ export class QuicConnection {
2518
2920
  * one datagram at most. The anti-amplification limit holds it like any
2519
2921
  * datagram (`takeDatagramInto`).
2520
2922
  */
2521
- resendEarly(level: i32): void {
2923
+ private resendEarly(level: i32): void {
2522
2924
  if (
2523
2925
  this.earlyResends >= QUIC_CONN_EARLY_RESENDS ||
2524
2926
  this.initial.probes > 0 ||
@@ -2560,7 +2962,7 @@ export class QuicConnection {
2560
2962
  * its alert unexpected_message (RFC 9001 §4.8). A frame too far ahead is
2561
2963
  * CRYPTO_BUFFER_EXCEEDED.
2562
2964
  */
2563
- receiveCrypto(space: QuicConnSpace, frame: QuicFrame, payload: u8[]): void {
2965
+ private receiveCrypto(space: QuicConnSpace, frame: QuicFrame, payload: u8[]): void {
2564
2966
  const reassembly: QuicConnReassembly = this.cryptoIn
2565
2967
  if (space.level < reassembly.level) {
2566
2968
  if (frame.offset + toI64(frame.dataLength) > space.cryptoInDelivered) {
@@ -2585,7 +2987,7 @@ export class QuicConnection {
2585
2987
  }
2586
2988
 
2587
2989
  /** Hands TLS what now continues the CRYPTO stream, from the buffer itself; an alert closes with CRYPTO_ERROR. */
2588
- feedTls(): void {
2990
+ private feedTls(): void {
2589
2991
  const tls: TlsServer | null = this.tls
2590
2992
  const reassembly: QuicConnReassembly = this.cryptoIn
2591
2993
  if (tls === null) {
@@ -2617,7 +3019,7 @@ export class QuicConnection {
2617
3019
  * PROTOCOL_VIOLATION (§3); otherwise its payload waits for
2618
3020
  * `readDatagram`, or is dropped when the ring is full.
2619
3021
  */
2620
- receiveDatagram(frame: QuicFrame, payload: u8[], frameStart: i32): void {
3022
+ private receiveDatagram(frame: QuicFrame, payload: u8[], frameStart: i32): void {
2621
3023
  const size: i64 = toI64(frame.end - frameStart)
2622
3024
  if (this.config.maxDatagramFrameSize === 0 || size > this.config.maxDatagramFrameSize) {
2623
3025
  // `fin` is how the frame says it was 0x31, the type with a Length.
@@ -2631,29 +3033,77 @@ export class QuicConnection {
2631
3033
  }
2632
3034
 
2633
3035
  /**
2634
- * A PATH_CHALLENGE (§8.2.2): answered with the same eight bytes. Only the
2635
- * latest four are kept, so a burst of challenges cannot grow anything.
3036
+ * A PATH_CHALLENGE (§8.2.2) on the current path: answered with the same
3037
+ * eight bytes. Only the latest four are kept, so a burst of challenges
3038
+ * cannot grow anything.
2636
3039
  */
2637
- receivePathChallenge(frame: QuicFrame, payload: u8[]): void {
3040
+ private receivePathChallenge(frame: QuicFrame, payload: u8[]): void {
3041
+ this.queuePathResponse(payload, frame.dataStart)
3042
+ }
3043
+
3044
+ /** Queues a PATH_RESPONSE of the eight bytes at `data[from]` on the current path. */
3045
+ private queuePathResponse(data: u8[], from: i32): void {
2638
3046
  if (this.pathCount >= 4) {
2639
3047
  this.pathHead = 0
2640
3048
  this.pathCount = 0
2641
3049
  }
2642
3050
  const base: i32 = ((this.pathHead + this.pathCount) % 4) * QUIC_PATH_DATA_SIZE
2643
3051
  for (let k: i32 = 0; k < QUIC_PATH_DATA_SIZE; k += 1) {
2644
- const from: i32 = frame.dataStart + k
2645
- if (
2646
- base + k >= 0 &&
2647
- base + k < toI32(this.pathData.length) &&
2648
- from >= 0 &&
2649
- from < toI32(payload.length)
2650
- ) {
2651
- this.pathData[base + k] = payload[from]
3052
+ const at: i32 = from + k
3053
+ if (base + k >= 0 && base + k < toI32(this.pathData.length) && at >= 0 && at < toI32(data.length)) {
3054
+ this.pathData[base + k] = data[at]
2652
3055
  }
2653
3056
  }
2654
3057
  this.pathCount = this.pathCount + 1
2655
3058
  }
2656
3059
 
3060
+ /**
3061
+ * A PATH_CHALLENGE from another address: kept for `afterPath`, which
3062
+ * answers it on the current path when the datagram moved the connection
3063
+ * there, and on its own path (`takeProbeInto`) otherwise (§8.2.2, §9.1).
3064
+ * Only the latest such challenge is kept, so a response still owed on
3065
+ * `probeAddress` is dropped, as a response may be: its data is about to
3066
+ * be overwritten.
3067
+ */
3068
+ private stageProbe(frame: QuicFrame, payload: u8[]): void {
3069
+ quicConnCopyAt(this.probeData, 0, payload, frame.dataStart, QUIC_PATH_DATA_SIZE)
3070
+ this.probeOwed = false
3071
+ this.probeStaged = true
3072
+ }
3073
+
3074
+ /**
3075
+ * A PATH_RESPONSE (§8.2.3): one matching a PATH_CHALLENGE still out
3076
+ * validates the path, whichever path it came on. Once the server has sent
3077
+ * a challenge, one matching none — late, or for a path given up — is
3078
+ * ignored; before that, none can be expected, and it is a
3079
+ * PROTOCOL_VIOLATION (§19.18).
3080
+ */
3081
+ private receivePathResponse(frame: QuicFrame, payload: u8[]): void {
3082
+ if (this.challengesDrawn === 0) {
3083
+ this.fail(QUIC_ERROR_PROTOCOL_VIOLATION, toI64(QUIC_FRAME_PATH_RESPONSE))
3084
+ return
3085
+ }
3086
+ if (!this.pathValidating) {
3087
+ return
3088
+ }
3089
+ let matched: boolean = false
3090
+ for (let m: i32 = 0; m < this.challengeCount; m += 1) {
3091
+ const slot: i32 = toI32((this.challengesDrawn - 1 - toI64(m)) % toI64(QUIC_CONN_CHALLENGES))
3092
+ // Not secret once sent, but compared without branching on the bytes all the same.
3093
+ matched =
3094
+ timingSafeEqualAt(
3095
+ payload,
3096
+ frame.dataStart,
3097
+ this.challengeData,
3098
+ slot * QUIC_PATH_DATA_SIZE,
3099
+ QUIC_PATH_DATA_SIZE
3100
+ ) || matched
3101
+ }
3102
+ if (matched) {
3103
+ this.pathConfirmed()
3104
+ }
3105
+ }
3106
+
2657
3107
  /**
2658
3108
  * Whatever TLS's last step made due: its output moved into each level's
2659
3109
  * CRYPTO stream, the keys of each level it now has secrets for, the
@@ -2763,7 +3213,7 @@ export class QuicConnection {
2763
3213
  * when they do not. The streams take the client's limits from them, and
2764
3214
  * the datagrams its `max_datagram_frame_size`.
2765
3215
  */
2766
- checkPeerParameters(tls: TlsServer): boolean {
3216
+ private checkPeerParameters(tls: TlsServer): boolean {
2767
3217
  const p: QuicTransportParameters = quicParseTransportParametersInto(
2768
3218
  this.parsedParameters,
2769
3219
  tls.clientTransportParameters,
@@ -2795,7 +3245,7 @@ export class QuicConnection {
2795
3245
  }
2796
3246
 
2797
3247
  /** Discards a space's keys and CRYPTO state (RFC 9001 §4.9), wiping the keys. */
2798
- discard(space: QuicConnSpace): void {
3248
+ private discard(space: QuicConnSpace): void {
2799
3249
  if (space.discarded) {
2800
3250
  return
2801
3251
  }
@@ -2821,7 +3271,7 @@ export class QuicConnection {
2821
3271
  * the seed and need no more entropy. It runs in the connection's HMAC
2822
3272
  * scratch inside an arena block, and wipes the MAC and the scratch.
2823
3273
  */
2824
- deriveConnectionId(sequence: i64): void {
3274
+ private deriveConnectionId(sequence: i64): void {
2825
3275
  const mac: HmacSha256Scratch = this.kdf.sha256
2826
3276
  using _scope = arena()
2827
3277
  const counter: u8[] = new Array<u8>(8)
@@ -2852,7 +3302,7 @@ export class QuicConnection {
2852
3302
  * in the slot's scratch and copied into the table, so issuing keeps
2853
3303
  * nothing (QUIC-3).
2854
3304
  */
2855
- topUpConnectionIds(): void {
3305
+ private topUpConnectionIds(): void {
2856
3306
  if (!this.handshakeComplete) {
2857
3307
  return
2858
3308
  }
@@ -2879,7 +3329,13 @@ export class QuicConnection {
2879
3329
  }
2880
3330
  }
2881
3331
 
2882
- /** What CertificateVerify must sign while the handshake waits for it, else `null` (see `TlsServer.signatureInput`). */
3332
+ /**
3333
+ * What CertificateVerify must sign while the handshake waits for it, else `null` (see
3334
+ * `TlsServer.signatureInput`).
3335
+ *
3336
+ * @returns The bytes to sign with the certificate's key, or `null` when no signature is owed or the
3337
+ * connection has closed.
3338
+ */
2883
3339
  signatureInput(): u8[] | null {
2884
3340
  const tls: TlsServer | null = this.tls
2885
3341
  if (tls === null || this.closed()) {
@@ -2893,6 +3349,12 @@ export class QuicConnection {
2893
3349
  * rest of the server's flight. Answers 0, or the CRYPTO_ERROR the
2894
3350
  * connection closed with when TLS refused it (a call at the wrong time, or
2895
3351
  * an empty signature: `internal_error`).
3352
+ *
3353
+ * @param signature The certificate key's signature over `signatureInput()`, in the encoding the
3354
+ * negotiated TLS signature scheme uses.
3355
+ * @returns 0 when TLS took the signature, or the error the connection has closed with (also when it
3356
+ * was already closed). It is also 0, with nothing signed, when the connection has no TLS session
3357
+ * and has not failed.
2896
3358
  */
2897
3359
  sign(signature: u8[]): i64 {
2898
3360
  const tls: TlsServer | null = this.tls
@@ -2915,7 +3377,7 @@ export class QuicConnection {
2915
3377
  * for none. Until the client's transport parameters are read, the server's
2916
3378
  * own alone.
2917
3379
  */
2918
- idleTimeout(): i64 {
3380
+ private idleTimeout(): i64 {
2919
3381
  const local: i64 = this.config.maxIdleTimeout
2920
3382
  const peer: i64 = this.peerParameters.maxIdleTimeout
2921
3383
  let timeout: i64 = local
@@ -2932,7 +3394,11 @@ export class QuicConnection {
2932
3394
  return timeout < floor ? floor : timeout
2933
3395
  }
2934
3396
 
2935
- /** When the idle timeout passes, or -1 when there is none or the timer has not started. */
3397
+ /**
3398
+ * When the idle timeout passes, or -1 when there is none or the timer has not started.
3399
+ *
3400
+ * @returns The time in the caller's milliseconds, or -1.
3401
+ */
2936
3402
  idleDeadline(): i64 {
2937
3403
  const timeout: i64 = this.idleTimeout()
2938
3404
  return timeout >= 0 && this.idleSince >= 0 ? this.idleSince + timeout : -1
@@ -2941,12 +3407,16 @@ export class QuicConnection {
2941
3407
  /**
2942
3408
  * When `handleTimer` is next due, in the caller's milliseconds: the idle
2943
3409
  * timeout, loss recovery's timer (a time-threshold loss or the probe
2944
- * timeout), or the end of a key update's probe timeout, whichever comes
2945
- * first; once the connection has closed, the end of its closing or
3410
+ * timeout), the end of a key update's probe timeout, or, while a path is
3411
+ * validated, its PATH_CHALLENGE's resend or the end of its validation,
3412
+ * whichever comes first; once the connection has closed, the end of its closing or
2946
3413
  * draining period, when its keys are wiped. -1 when nothing is timed:
2947
3414
  * before the first packet, while a closed connection's own close has not
2948
3415
  * gone out (`takeDatagram` sends it), once a closed connection's keys are
2949
- * wiped, and with no idle timeout, nothing in flight and no update pending.
3416
+ * wiped, and with no idle timeout, nothing in flight, no update pending
3417
+ * and no path being validated.
3418
+ *
3419
+ * @returns The time in the caller's milliseconds at which to call `handleTimer`, or -1.
2950
3420
  */
2951
3421
  deadline(): i64 {
2952
3422
  if (this.closed()) {
@@ -2963,6 +3433,13 @@ export class QuicConnection {
2963
3433
  if (recovery >= 0 && (due < 0 || recovery < due)) {
2964
3434
  due = recovery
2965
3435
  }
3436
+ if (this.pathValidating) {
3437
+ const path: i64 =
3438
+ this.challengeResendAt < this.challengeUntil ? this.challengeResendAt : this.challengeUntil
3439
+ if (due < 0 || path < due) {
3440
+ due = path
3441
+ }
3442
+ }
2966
3443
  return due
2967
3444
  }
2968
3445
 
@@ -2970,9 +3447,23 @@ export class QuicConnection {
2970
3447
  * Whether the anti-amplification limit stops the server sending (RFC 9000
2971
3448
  * §8.1): the client's address is not validated and three times what it
2972
3449
  * sent leaves no room for a whole datagram.
3450
+ *
3451
+ * @returns True while the address (or a new path being validated) has no budget left for a datagram.
2973
3452
  */
2974
3453
  amplificationBlocked(): boolean {
2975
- return !this.addressValidated && this.bytesReceived * 3 - this.bytesSent < toI64(QUIC_CONN_DATAGRAM_SIZE)
3454
+ return (
3455
+ (!this.addressValidated && this.bytesReceived * 3 - this.bytesSent < toI64(QUIC_CONN_DATAGRAM_SIZE)) ||
3456
+ this.pathBudget() < QUIC_CONN_PATH_MIN
3457
+ )
3458
+ }
3459
+
3460
+ /**
3461
+ * What the path being validated still lets the server send: three times
3462
+ * what came from it since the connection moved there, less what went
3463
+ * (RFC 9000 §9.3.1, §8.1). Unlimited, as `QUIC_MAX_VARINT`, on a validated path.
3464
+ */
3465
+ private pathBudget(): i64 {
3466
+ return this.pathValidating ? this.pathReceived * 3 - this.pathSent : QUIC_MAX_VARINT
2976
3467
  }
2977
3468
 
2978
3469
  /**
@@ -2988,6 +3479,8 @@ export class QuicConnection {
2988
3479
  * §6.2.4): `takeDatagram` then sends it. `receive` and `takeDatagram` run
2989
3480
  * it themselves. Time never runs backwards here: an earlier `now` than one
2990
3481
  * already given counts as that one.
3482
+ *
3483
+ * @param now The caller's monotonic time in milliseconds.
2991
3484
  */
2992
3485
  handleTimer(now: i64): void {
2993
3486
  this.runClocks(now)
@@ -2998,7 +3491,7 @@ export class QuicConnection {
2998
3491
  * `handleTimer`'s idle timeout, key retention and the end of the closing
2999
3492
  * or draining period, which `receive` runs before it reads a datagram.
3000
3493
  */
3001
- runClocks(now: i64): void {
3494
+ private runClocks(now: i64): void {
3002
3495
  if (now > this.now) {
3003
3496
  this.now = now
3004
3497
  }
@@ -3022,13 +3515,321 @@ export class QuicConnection {
3022
3515
  this.wipeAll()
3023
3516
  return
3024
3517
  }
3518
+ this.runPathClock()
3025
3519
  if (this.keyRetainUntil >= 0 && this.now >= this.keyRetainUntil) {
3026
3520
  this.prepareNextReadKeys()
3027
3521
  }
3028
3522
  }
3029
3523
 
3524
+ /**
3525
+ * The path being validated's timers (RFC 9000 §8.2.4, §9.3.2): past
3526
+ * `challengeUntil`, max(3 PTO, 6 kInitialRtt) after the move, validation
3527
+ * has failed and the connection goes back to the last validated address;
3528
+ * past `challengeResendAt`, a probe timeout after the last challenge, a
3529
+ * fresh one is drawn and sent. A server's handshake validates the
3530
+ * client's address and the handshake confirms the connection before any
3531
+ * move, so there is always an address to go back to: the case where
3532
+ * there is none, which RFC 9000 §9.3.2 closes silently, cannot arise.
3533
+ */
3534
+ private runPathClock(): void {
3535
+ if (!this.pathValidating) {
3536
+ return
3537
+ }
3538
+ if (this.now >= this.challengeUntil) {
3539
+ this.sendResponsesBack()
3540
+ quicConnCopyAt(this.pathCurrent, 0, this.pathValidated, 0, QUIC_CONN_ADDRESS_SIZE)
3541
+ this.endValidation()
3542
+ return
3543
+ }
3544
+ if (this.now >= this.challengeResendAt) {
3545
+ this.drawChallenge()
3546
+ }
3547
+ }
3548
+
3549
+ /**
3550
+ * Notes where the datagram about to be read came from, before any of it
3551
+ * is: answers false for one to drop unread. The first Initial's address
3552
+ * is the connection's, and validated by the handshake. Until the handshake
3553
+ * is confirmed the client may not move (RFC 9000 §9), and a datagram from
3554
+ * another address is dropped — so a forged Initial or Handshake packet
3555
+ * from elsewhere cannot move the connection, nor take the server's
3556
+ * flight. A carrier that passes no address leaves every path rule off.
3557
+ */
3558
+ private notePath(address: u8[]): boolean {
3559
+ this.arrivalOther = false
3560
+ this.migrateOwed = false
3561
+ this.probeStaged = false
3562
+ if (toI32(address.length) !== QUIC_CONN_ADDRESS_SIZE) {
3563
+ return true
3564
+ }
3565
+ if (this.state === QUIC_STATE_WAIT_INITIAL) {
3566
+ quicConnCopyAt(this.pathCurrent, 0, address, 0, QUIC_CONN_ADDRESS_SIZE)
3567
+ quicConnCopyAt(this.pathValidated, 0, address, 0, QUIC_CONN_ADDRESS_SIZE)
3568
+ this.pathKnown = true
3569
+ return true
3570
+ }
3571
+ if (!this.pathKnown || quicConnSameAddress(address, this.pathCurrent, false)) {
3572
+ return true
3573
+ }
3574
+ if (!this.handshakeComplete) {
3575
+ return false
3576
+ }
3577
+ quicConnCopyAt(this.pathArrival, 0, address, 0, QUIC_CONN_ADDRESS_SIZE)
3578
+ this.arrivalOther = true
3579
+ return true
3580
+ }
3581
+
3582
+ /**
3583
+ * What a datagram of `len` bytes, now read, does to the paths: one from
3584
+ * another address whose newest non-probing packet moved the connection
3585
+ * moves it (§9.3), and a challenge it carried is answered on the new
3586
+ * path; one that moved nothing has its challenge answered on its own path
3587
+ * (`takeProbeInto`). A datagram that authenticated nothing does neither.
3588
+ * What came from the path being validated adds to its limit.
3589
+ */
3590
+ private afterPath(counted: boolean, len: i32): void {
3591
+ if (!counted) {
3592
+ return
3593
+ }
3594
+ if (this.arrivalOther) {
3595
+ if (!this.migrateOwed) {
3596
+ if (this.probeStaged) {
3597
+ quicConnCopyAt(this.probeAddress, 0, this.pathArrival, 0, QUIC_CONN_ADDRESS_SIZE)
3598
+ this.probeBudget = toI64(len) * 3
3599
+ this.probeOwed = true
3600
+ }
3601
+ return
3602
+ }
3603
+ const swapped: boolean = this.migrate(this.pathArrival)
3604
+ if (this.probeStaged && !swapped) {
3605
+ this.queuePathResponse(this.probeData, toI32(0))
3606
+ }
3607
+ }
3608
+ if (this.pathValidating) {
3609
+ this.pathReceived = this.pathReceived + toI64(len)
3610
+ }
3611
+ }
3612
+
3613
+ /**
3614
+ * Moves the connection to `address` (RFC 9000 §9.3): its datagrams go
3615
+ * there from now. Back to the last validated address, nothing more is
3616
+ * needed, and a validation under way stops — which is how a forged
3617
+ * source, a copy of the client's packet sent on from elsewhere, loses the
3618
+ * connection to the client's next packet (§9.3.3). Anywhere else, the
3619
+ * path is validated with a PATH_CHALLENGE, and until it is the server
3620
+ * sends there only three times what it received from it (§9.3.1). The
3621
+ * peer's connection ID is kept: the client chose not to change it, and a
3622
+ * NAT rebinding never does (§9.5). Answers whether the challenge staged
3623
+ * in `probeData` is already queued on the new path (`sendResponsesBack`).
3624
+ */
3625
+ private migrate(address: u8[]): boolean {
3626
+ const swapped: boolean = this.sendResponsesBack()
3627
+ quicConnCopyAt(this.pathCurrent, 0, address, 0, QUIC_CONN_ADDRESS_SIZE)
3628
+ if (quicConnSameAddress(address, this.pathValidated, false)) {
3629
+ this.endValidation()
3630
+ return swapped
3631
+ }
3632
+ this.endValidation()
3633
+ this.pathValidating = true
3634
+ const span: i64 = this.recovery.probeTimeout() * 3
3635
+ this.challengeUntil = this.now + (span > QUIC_CONN_VALIDATION_FLOOR ? span : QUIC_CONN_VALIDATION_FLOOR)
3636
+ this.drawChallenge()
3637
+ return swapped
3638
+ }
3639
+
3640
+ /**
3641
+ * Before `pathCurrent` changes: a PATH_RESPONSE still owed there answers
3642
+ * a challenge that came from there, so it goes there, not to the new
3643
+ * address (RFC 9000 §8.2.2) — the latest one, on the probe route
3644
+ * (`takeProbeInto`), within what that path may still be sent: no limit
3645
+ * once validated, else its own 3x (§8.1). The others are dropped, as a
3646
+ * response may be. A challenge staged in `probeData` by the datagram
3647
+ * being read swaps into the ring in its place, owed on the new address,
3648
+ * and the answer is true; otherwise false. A response still owed on the
3649
+ * probe route is never overwritten: the ring's are dropped instead.
3650
+ */
3651
+ private sendResponsesBack(): boolean {
3652
+ if (this.pathCount <= 0) {
3653
+ return false
3654
+ }
3655
+ if (this.probeOwed) {
3656
+ this.pathCount = 0
3657
+ return false
3658
+ }
3659
+ const base: i32 = ((this.pathHead + this.pathCount - 1) % 4) * QUIC_PATH_DATA_SIZE
3660
+ const swapped: boolean = this.probeStaged
3661
+ for (let k: i32 = 0; k < QUIC_PATH_DATA_SIZE; k += 1) {
3662
+ const kept: u8 = this.probeData[k]
3663
+ this.probeData[k] = this.pathData[base + k]
3664
+ this.pathData[base + k] = kept
3665
+ }
3666
+ this.pathHead = base / QUIC_PATH_DATA_SIZE
3667
+ this.pathCount = swapped ? 1 : 0
3668
+ quicConnCopyAt(this.probeAddress, 0, this.pathCurrent, 0, QUIC_CONN_ADDRESS_SIZE)
3669
+ if (!this.pathValidating) {
3670
+ this.probeBudget = toI64(QUIC_CONN_DATAGRAM_SIZE)
3671
+ } else {
3672
+ const left: i64 = this.pathReceived * 3 - this.pathSent
3673
+ this.probeBudget = left > 0 ? left : 0
3674
+ }
3675
+ this.probeOwed = true
3676
+ return swapped
3677
+ }
3678
+
3679
+ /**
3680
+ * Draws the next PATH_CHALLENGE's eight bytes from the ID seed's HMAC
3681
+ * under `QUIC_CONN_CHALLENGE_SEQUENCE` (§8.2.1: unpredictable), keeps
3682
+ * them with the two before, and owes the challenge; its resend is due a
3683
+ * probe timeout later.
3684
+ */
3685
+ private drawChallenge(): void {
3686
+ this.deriveConnectionId(QUIC_CONN_CHALLENGE_SEQUENCE + this.challengesDrawn)
3687
+ const slot: i32 = toI32(this.challengesDrawn % toI64(QUIC_CONN_CHALLENGES))
3688
+ quicConnCopyAt(this.challengeData, slot * QUIC_PATH_DATA_SIZE, this.cidScratch, 0, QUIC_PATH_DATA_SIZE)
3689
+ secureZero(this.cidScratch)
3690
+ this.challengesDrawn = this.challengesDrawn + 1
3691
+ if (this.challengeCount < QUIC_CONN_CHALLENGES) {
3692
+ this.challengeCount = this.challengeCount + 1
3693
+ }
3694
+ this.challengeOwed = true
3695
+ this.challengeResendAt = this.now + this.recovery.probeTimeout()
3696
+ }
3697
+
3698
+ /**
3699
+ * The path being validated answered (§8.2.3): it is the validated
3700
+ * address now. Congestion control and the RTT estimate start again on a
3701
+ * new address, but not when only the port changed, which is the same
3702
+ * network path behind a rebinding NAT (§9.4); ECN is tested again either
3703
+ * way (§13.4.2).
3704
+ */
3705
+ private pathConfirmed(): void {
3706
+ const portOnly: boolean = quicConnSameAddress(this.pathCurrent, this.pathValidated, true)
3707
+ quicConnCopyAt(this.pathValidated, 0, this.pathCurrent, 0, QUIC_CONN_ADDRESS_SIZE)
3708
+ this.endValidation()
3709
+ if (!portOnly) {
3710
+ this.recovery.resetPath()
3711
+ }
3712
+ this.recovery.restartEcn()
3713
+ }
3714
+
3715
+ /** Stops validating a path: no challenge is owed, kept or timed. */
3716
+ private endValidation(): void {
3717
+ this.pathValidating = false
3718
+ this.challengeOwed = false
3719
+ this.challengeCount = 0
3720
+ this.challengeResendAt = -1
3721
+ this.challengeUntil = -1
3722
+ this.pathReceived = 0
3723
+ this.pathSent = 0
3724
+ }
3725
+
3726
+ /** Adds `n` bytes sent to the path being validated's count. */
3727
+ private notePathSent(n: i32): void {
3728
+ if (this.pathValidating) {
3729
+ this.pathSent = this.pathSent + toI64(n)
3730
+ }
3731
+ }
3732
+
3733
+ /** Clears every path field for a new connection, in the arrays the slot keeps. */
3734
+ private forgetPath(): void {
3735
+ quicConnZeroAt(this.pathCurrent)
3736
+ quicConnZeroAt(this.pathValidated)
3737
+ quicConnZeroAt(this.pathArrival)
3738
+ quicConnZeroAt(this.probeAddress)
3739
+ quicConnZeroAt(this.probeData)
3740
+ quicConnZeroAt(this.challengeData)
3741
+ this.endValidation()
3742
+ this.probeBudget = 0
3743
+ this.challengesDrawn = 0
3744
+ this.pathKnown = false
3745
+ this.arrivalOther = false
3746
+ this.pathFrameStaged = false
3747
+ this.probeOwed = false
3748
+ this.probeStaged = false
3749
+ this.nonProbing = false
3750
+ this.migrateOwed = false
3751
+ }
3752
+
3753
+ /**
3754
+ * Where this connection's datagrams go now: the 18-byte `nish:net`
3755
+ * address `receiveWindowFrom` last moved it to, or the first Initial's.
3756
+ * A carrier sends every datagram of `takeDatagramInto` here; it is empty
3757
+ * (all zero) for a connection fed by `receiveWindow` alone.
3758
+ *
3759
+ * @returns The connection's own address array, borrowed: it changes in place when the connection
3760
+ * moves, so copy it to keep it.
3761
+ */
3762
+ sendAddress(): u8[] {
3763
+ return this.pathCurrent
3764
+ }
3765
+
3766
+ /**
3767
+ * Writes the PATH_RESPONSE owed on another path (§8.2.2, §9.1) into `out`
3768
+ * at `at`, which needs `QUIC_CONN_DATAGRAM_SIZE` bytes of room, and
3769
+ * answers its length, or 0 when none is owed: a 1-RTT packet with that
3770
+ * frame alone, padded to 1200 bytes or to three times what came from the
3771
+ * path (§8.1), whichever is less. The carrier sends it to
3772
+ * `probeAddress`, before `takeDatagramInto`'s datagrams. It is answered
3773
+ * once and never sent again (§13.3).
3774
+ *
3775
+ * @param out Where the datagram is written.
3776
+ * @param at Where in `out` it starts; `out` needs `QUIC_CONN_DATAGRAM_SIZE` bytes from here.
3777
+ * @param now The caller's monotonic time in milliseconds; timers due by then run first.
3778
+ * @returns The datagram's length in bytes, or 0 when no PATH_RESPONSE is owed, the connection is closed,
3779
+ * the handshake is not complete, the room is short, or the packet cannot be built within the path's budget (the
3780
+ * owed PATH_RESPONSE is then dropped).
3781
+ */
3782
+ takeProbeInto(out: u8[], at: i32, now: i64): i32 {
3783
+ this.handleTimer(now)
3784
+ if (
3785
+ !this.probeOwed ||
3786
+ this.closed() ||
3787
+ !this.handshakeComplete ||
3788
+ at < 0 ||
3789
+ at > toI32(out.length) - QUIC_CONN_DATAGRAM_SIZE
3790
+ ) {
3791
+ return 0
3792
+ }
3793
+ this.probeOwed = false
3794
+ const size: i32 =
3795
+ this.probeBudget < toI64(QUIC_CONN_DATAGRAM_SIZE) ? toI32(this.probeBudget) : QUIC_CONN_DATAGRAM_SIZE
3796
+ this.beforeDatagram()
3797
+ this.datagramEcn = 0
3798
+ let n: i32 = 0
3799
+ {
3800
+ using _scope = arena()
3801
+ n = this.buildProbe(out, at, size)
3802
+ }
3803
+ this.probeBudget = this.probeBudget - toI64(n)
3804
+ return n
3805
+ }
3806
+
3807
+ /** `takeProbeInto`'s packet, of `size` bytes at `out[at]`, built and sealed; 0 when it does not fit. */
3808
+ private buildProbe(out: u8[], at: i32, size: i32): i32 {
3809
+ const space: QuicConnSpace = this.application
3810
+ const overhead: i32 = this.overhead(space)
3811
+ if (overhead === 0 || size < overhead + 1 + QUIC_PATH_DATA_SIZE) {
3812
+ return 0
3813
+ }
3814
+ space.clearStaged()
3815
+ const payloadStart: i32 = at + overhead - QUIC_AEAD_TAG_SIZE
3816
+ const payloadEnd: i32 = at + size - QUIC_AEAD_TAG_SIZE
3817
+ const next: i32 = quicPutPathData(
3818
+ out,
3819
+ payloadStart,
3820
+ payloadEnd,
3821
+ QUIC_FRAME_PATH_RESPONSE,
3822
+ this.probeData,
3823
+ 0
3824
+ )
3825
+ if (next < 0) {
3826
+ return 0
3827
+ }
3828
+ return this.sealAt(space, out, at, quicPutPadding(out, next, payloadEnd - next))
3829
+ }
3830
+
3030
3831
  /** Loss recovery's timer, if it is due (RFC 9002 §6.2, A.9). */
3031
- runRecoveryTimer(): void {
3832
+ private runRecoveryTimer(): void {
3032
3833
  if (this.closed() || this.state === QUIC_STATE_WAIT_INITIAL) {
3033
3834
  return
3034
3835
  }
@@ -3053,6 +3854,8 @@ export class QuicConnection {
3053
3854
  * or answered it less than a probe timeout ago, so the next read keys are
3054
3855
  * not ready), and until the client has acknowledged a packet sent with the
3055
3856
  * current keys.
3857
+ *
3858
+ * @returns True when the update started, false when it may not yet.
3056
3859
  */
3057
3860
  updateKeys(): boolean {
3058
3861
  if (
@@ -3073,7 +3876,7 @@ export class QuicConnection {
3073
3876
  * `QUIC_CONN_SKIP_SEQUENCE`, so a client that saw where the last gaps fell
3074
3877
  * cannot tell where the next will.
3075
3878
  */
3076
- scheduleSkip(from: i64): void {
3879
+ private scheduleSkip(from: i64): void {
3077
3880
  this.deriveConnectionId(QUIC_CONN_SKIP_SEQUENCE + this.skipsDrawn)
3078
3881
  this.skipsDrawn = this.skipsDrawn + 1
3079
3882
  let draw: i64 = 0
@@ -3092,6 +3895,8 @@ export class QuicConnection {
3092
3895
  * stopped, or it has room to write again after a short write — or -1
3093
3896
  * when there is none. Each stream comes up once however much happened;
3094
3897
  * read and write it until it has nothing more to say.
3898
+ *
3899
+ * @returns A stream ID, or -1.
3095
3900
  */
3096
3901
  nextStreamEvent(): i64 {
3097
3902
  return this.streams.nextEvent()
@@ -3103,6 +3908,9 @@ export class QuicConnection {
3103
3908
  * `QUIC_STREAM_ERR_STATE` when not connected, or `QUIC_STREAM_ERR_LIMIT`
3104
3909
  * when the client's MAX_STREAMS is reached (STREAMS_BLOCKED then goes out)
3105
3910
  * or `localStreams` of the server's are open.
3911
+ *
3912
+ * @param bidirectional True for a stream both sides send on, false for one only the server sends on.
3913
+ * @returns The new stream's ID, or a negative `QUIC_STREAM_ERR_*`.
3106
3914
  */
3107
3915
  openStream(bidirectional: boolean): i64 {
3108
3916
  if (this.state !== QUIC_STATE_CONNECTED) {
@@ -3120,6 +3928,13 @@ export class QuicConnection {
3120
3928
  * only the client sends on, one already finished or reset, or one the
3121
3929
  * client asked to stop (STOP_SENDING, which this side answered with
3122
3930
  * RESET_STREAM).
3931
+ *
3932
+ * @param id The stream's ID.
3933
+ * @param buf The bytes to send; copied into the stream's buffer, so the caller may reuse it.
3934
+ * @param from Where the bytes start in `buf`.
3935
+ * @param length How many bytes to offer.
3936
+ * @param fin True to finish the sending side once all `length` bytes are taken.
3937
+ * @returns The number of bytes taken, 0 to `length`, or a negative `QUIC_STREAM_ERR_*`.
3123
3938
  */
3124
3939
  streamWrite(id: i64, buf: u8[], from: i32, length: i32, fin: boolean): i32 {
3125
3940
  if (this.state !== QUIC_STATE_CONNECTED) {
@@ -3134,12 +3949,26 @@ export class QuicConnection {
3134
3949
  * once every byte up to the FIN was read, `QUIC_STREAM_ERR_RESET` once the
3135
3950
  * client reset the stream (its code is the stream's `resetCode`), or
3136
3951
  * another `QUIC_STREAM_ERR_*`. Reading is what gives the client more credit.
3952
+ *
3953
+ * @param id The stream's ID.
3954
+ * @param buf Where the bytes go.
3955
+ * @param at Where in `buf` they start.
3956
+ * @param length The most bytes to read.
3957
+ * @returns The number of bytes read, 0, `QUIC_STREAM_END`, or a negative `QUIC_STREAM_ERR_*`.
3137
3958
  */
3138
3959
  streamRead(id: i64, buf: u8[], at: i32, length: i32): i32 {
3139
3960
  return this.streams.read(id, buf, at, length)
3140
3961
  }
3141
3962
 
3142
- /** Abandons stream `id`'s sending side with application error `code` (RESET_STREAM). Answers `QUIC_STREAM_OK` or a `QUIC_STREAM_ERR_*`. */
3963
+ /**
3964
+ * Abandons stream `id`'s sending side with application error `code` (RESET_STREAM). Answers
3965
+ * `QUIC_STREAM_OK` or a `QUIC_STREAM_ERR_*`.
3966
+ *
3967
+ * @param id The stream's ID; it must be one the server sends on.
3968
+ * @param code The application's error code, sent to the client in RESET_STREAM.
3969
+ * @returns `QUIC_STREAM_OK`, or a negative `QUIC_STREAM_ERR_*` (`QUIC_STREAM_ERR_STATE` when not
3970
+ * connected).
3971
+ */
3143
3972
  streamReset(id: i64, code: i64): i32 {
3144
3973
  if (this.state !== QUIC_STATE_CONNECTED) {
3145
3974
  return QUIC_STREAM_ERR_STATE
@@ -3147,7 +3976,15 @@ export class QuicConnection {
3147
3976
  return this.streams.resetStream(id, code)
3148
3977
  }
3149
3978
 
3150
- /** Asks the client to stop sending on stream `id`, with application error `code` (STOP_SENDING). Answers `QUIC_STREAM_OK` or a `QUIC_STREAM_ERR_*`. */
3979
+ /**
3980
+ * Asks the client to stop sending on stream `id`, with application error `code` (STOP_SENDING).
3981
+ * Answers `QUIC_STREAM_OK` or a `QUIC_STREAM_ERR_*`.
3982
+ *
3983
+ * @param id The stream's ID; it must be one the client sends on.
3984
+ * @param code The application's error code, sent to the client in STOP_SENDING.
3985
+ * @returns `QUIC_STREAM_OK`, or a negative `QUIC_STREAM_ERR_*` (`QUIC_STREAM_ERR_STATE` when not
3986
+ * connected).
3987
+ */
3151
3988
  streamStopSending(id: i64, code: i64): i32 {
3152
3989
  if (this.state !== QUIC_STATE_CONNECTED) {
3153
3990
  return QUIC_STREAM_ERR_STATE
@@ -3160,6 +3997,8 @@ export class QuicConnection {
3160
3997
  * none: the all-at-once form of `nextStreamEvent` and `streamRead`, which
3161
3998
  * allocates the run it answers. `fin` marks the last of its stream; a
3162
3999
  * stream the client reset is passed over.
4000
+ *
4001
+ * @returns A new run the caller owns, or `null` when no stream has data or a FIN waiting.
3163
4002
  */
3164
4003
  readStream(): QuicStreamData | null {
3165
4004
  let id: i64 = this.streams.nextEvent()
@@ -3189,6 +4028,12 @@ export class QuicConnection {
3189
4028
  * connected, the stream is unknown, its side is already finished (or the
3190
4029
  * client stopped it), or the data would pass the credit the client gave
3191
4030
  * for the stream or the connection, or the room in the stream's buffer.
4031
+ *
4032
+ * @param id The stream's ID.
4033
+ * @param data The bytes to send; copied, so the caller may reuse it.
4034
+ * @param fin True to finish the sending side after `data`.
4035
+ * @returns `QUIC_STREAM_OK` when every byte was queued, or a negative `QUIC_STREAM_ERR_*` with nothing
4036
+ * queued.
3192
4037
  */
3193
4038
  writeStream(id: i64, data: u8[], fin: boolean): i32 {
3194
4039
  if (this.state !== QUIC_STATE_CONNECTED) {
@@ -3220,6 +4065,8 @@ export class QuicConnection {
3220
4065
  * client's `max_datagram_frame_size` with the frame's type and Length, and
3221
4066
  * a 1-RTT packet of `QUIC_CONN_DATAGRAM_SIZE` with the longest packet
3222
4067
  * number; 0 when the client takes none, or the server sends none.
4068
+ *
4069
+ * @returns The payload size in bytes, 0 up to a little under `QUIC_CONN_DATAGRAM_SIZE`.
3223
4070
  */
3224
4071
  maxDatagramPayload(): i32 {
3225
4072
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
@@ -3251,6 +4098,11 @@ export class QuicConnection {
3251
4098
  * none, `QUIC_DATAGRAM_ERR_TOO_BIG` for a frame past the client's limit or
3252
4099
  * a payload past `maxDatagramPayload()`, or `QUIC_DATAGRAM_ERR_FULL` while
3253
4100
  * the ring holds `QUIC_CONN_DATAGRAM_QUEUE` waiting.
4101
+ *
4102
+ * @param buf The array holding the payload; copied into the ring, so the caller may reuse it.
4103
+ * @param from Where the payload starts in `buf`.
4104
+ * @param length The payload's length in bytes.
4105
+ * @returns `QUIC_DATAGRAM_OK`, or one of the `QUIC_DATAGRAM_ERR_*` codes above with nothing queued.
3254
4106
  */
3255
4107
  sendDatagram(buf: u8[], from: i32, length: i32): i32 {
3256
4108
  if (
@@ -3278,6 +4130,11 @@ export class QuicConnection {
3278
4130
  * at most `cap` bytes, and forgets it. Answers its length,
3279
4131
  * `QUIC_DATAGRAM_NONE` when none is waiting, or `QUIC_DATAGRAM_ERR_ROOM`,
3280
4132
  * keeping it, when it does not fit.
4133
+ *
4134
+ * @param buf Where the payload goes.
4135
+ * @param at Where in `buf` it starts.
4136
+ * @param cap The most bytes `buf` has room for from `at`.
4137
+ * @returns The payload's length in bytes, `QUIC_DATAGRAM_NONE`, or `QUIC_DATAGRAM_ERR_ROOM`.
3281
4138
  */
3282
4139
  readDatagram(buf: u8[], at: i32, cap: i32): i32 {
3283
4140
  return this.datagramsIn.pop(buf, at, cap)
@@ -3288,6 +4145,9 @@ export class QuicConnection {
3288
4145
  /**
3289
4146
  * The next datagram to send, or `null` when nothing is due: the
3290
4147
  * allocating form of `takeDatagramInto`, which a test or a recording uses.
4148
+ *
4149
+ * @param now The caller's monotonic time in milliseconds.
4150
+ * @returns A new array the caller owns, at most `QUIC_CONN_DATAGRAM_SIZE` bytes, or `null`.
3291
4151
  */
3292
4152
  takeDatagram(now: i64): u8[] | null {
3293
4153
  const out: u8[] = new Array<u8>(QUIC_CONN_DATAGRAM_SIZE)
@@ -3316,6 +4176,11 @@ export class QuicConnection {
3316
4176
  * inside an arena block: nothing it does allocates past the call. This is
3317
4177
  * not paced: a carrier that paces calls `nish/net/quic-listener`'s
3318
4178
  * `quicListenerTakeFlight` instead.
4179
+ *
4180
+ * @param out Where the datagram is written.
4181
+ * @param at Where in `out` it starts; `out` needs `QUIC_CONN_DATAGRAM_SIZE` bytes from here.
4182
+ * @param now The caller's monotonic time in milliseconds; timers due by then run first.
4183
+ * @returns The datagram's length in bytes, at most `QUIC_CONN_DATAGRAM_SIZE`, or 0.
3319
4184
  */
3320
4185
  takeDatagramInto(out: u8[], at: i32, now: i64): i32 {
3321
4186
  this.handleTimer(now)
@@ -3361,7 +4226,7 @@ export class QuicConnection {
3361
4226
  * the packet number due to be skipped is (RFC 9000 §21.4): remembered,
3362
4227
  * never sealed nor recorded, and the next skip drawn.
3363
4228
  */
3364
- beforeDatagram(): void {
4229
+ private beforeDatagram(): void {
3365
4230
  const limit: i64 = this.confidentialityLimit
3366
4231
  if (this.sealedUnderKey >= limit - limit / 4) {
3367
4232
  this.updateKeys()
@@ -3384,8 +4249,15 @@ export class QuicConnection {
3384
4249
  * last padded when an Initial elicits, then each sealed where it lies.
3385
4250
  * Answers the datagram's length, or 0 when no space had anything.
3386
4251
  */
3387
- buildDatagram(out: u8[], at: i32): i32 {
4252
+ private buildDatagram(out: u8[], at: i32): i32 {
3388
4253
  let remaining: i32 = QUIC_CONN_DATAGRAM_SIZE
4254
+ // A path being validated has its own 3x limit (§9.3.1), which the
4255
+ // datagram may not pass; `amplificationBlocked` kept it above the floor.
4256
+ const budget: i64 = this.pathBudget()
4257
+ if (budget < toI64(remaining)) {
4258
+ remaining = toI32(budget)
4259
+ }
4260
+ this.pathFrameStaged = false
3389
4261
  let position: i32 = at
3390
4262
  let paddedInitial: boolean = false
3391
4263
  let eliciting: boolean = false
@@ -3415,7 +4287,8 @@ export class QuicConnection {
3415
4287
  out,
3416
4288
  payloadStart,
3417
4289
  payloadStart + remaining - overhead,
3418
- elicit
4290
+ elicit,
4291
+ !sent.full()
3419
4292
  )
3420
4293
  if (payloadEnd <= payloadStart) {
3421
4294
  continue
@@ -3440,7 +4313,10 @@ export class QuicConnection {
3440
4313
  if (last < 0) {
3441
4314
  return 0
3442
4315
  }
3443
- if (paddedInitial && remaining > 0) {
4316
+ // RFC 9000 §14.1: a datagram with an ack-eliciting Initial is padded;
4317
+ // §8.2.1, §8.2.2: so is one with a PATH_CHALLENGE or PATH_RESPONSE, as
4318
+ // far as the path's limit lets it, which shows the path carries 1200.
4319
+ if ((paddedInitial || this.pathFrameStaged) && remaining > 0) {
3444
4320
  const padded: QuicConnSpace = this.spaceAt(last)
3445
4321
  padded.builtEnd = quicPutPadding(out, padded.builtEnd, remaining)
3446
4322
  }
@@ -3464,6 +4340,7 @@ export class QuicConnection {
3464
4340
  return 0
3465
4341
  }
3466
4342
  this.bytesSent = this.bytesSent + toI64(total)
4343
+ this.notePathSent(total)
3467
4344
  return total
3468
4345
  }
3469
4346
 
@@ -3472,7 +4349,7 @@ export class QuicConnection {
3472
4349
  * its packet number, and the AEAD tag. 0 when the space cannot send: no
3473
4350
  * keys, discarded, or no packet number length for its next number.
3474
4351
  */
3475
- overhead(space: QuicConnSpace): i32 {
4352
+ private overhead(space: QuicConnSpace): i32 {
3476
4353
  if (space.writeKeys === null || space.discarded) {
3477
4354
  return 0
3478
4355
  }
@@ -3495,14 +4372,22 @@ export class QuicConnection {
3495
4372
  * The frames of one packet of `space`, written into `out[start .. end)`:
3496
4373
  * an ACK when one is due, and, when `elicit` allows frames that elicit an
3497
4374
  * acknowledgement, CRYPTO data (lost bytes first), at the application
3498
- * level HANDSHAKE_DONE, RETIRE_CONNECTION_ID, NEW_CONNECTION_ID,
3499
- * PATH_RESPONSE, the streams' control frames, DATAGRAMs and stream data,
3500
- * and for a probe with nothing else to carry a PING. Answers the offset
4375
+ * level HANDSHAKE_DONE, RETIRE_CONNECTION_ID, NEW_CONNECTION_ID, the path
4376
+ * frames, the streams' control frames, DATAGRAMs and stream data, and for
4377
+ * a probe with nothing else to carry a PING. Without `elicit`, the path
4378
+ * frames still go when `pathFrames` says the packet can be recorded. Answers the offset
3501
4379
  * past the last frame, `start` when nothing is due. What it carries is
3502
4380
  * written to the space's staging row, and `stagedEliciting` says whether
3503
4381
  * anything elicits an acknowledgement.
3504
4382
  */
3505
- buildPayloadInto(space: QuicConnSpace, out: u8[], start: i32, end: i32, elicit: boolean): i32 {
4383
+ private buildPayloadInto(
4384
+ space: QuicConnSpace,
4385
+ out: u8[],
4386
+ start: i32,
4387
+ end: i32,
4388
+ elicit: boolean,
4389
+ pathFrames: boolean
4390
+ ): i32 {
3506
4391
  let at: i32 = start
3507
4392
  space.clearStaged()
3508
4393
  if (space.received.ackPending) {
@@ -3513,6 +4398,9 @@ export class QuicConnection {
3513
4398
  }
3514
4399
  }
3515
4400
  if (!elicit) {
4401
+ if (pathFrames && space.level === TLS_LEVEL_APPLICATION) {
4402
+ at = this.buildPathFrames(space, out, at, end)
4403
+ }
3516
4404
  return at
3517
4405
  }
3518
4406
  at = this.buildCrypto(space, out, at, end)
@@ -3531,7 +4419,7 @@ export class QuicConnection {
3531
4419
  * level's kept stream, then those not sent yet. The level's CRYPTO stream
3532
4420
  * is kept whole, so a byte's index in `cryptoOut` is its offset.
3533
4421
  */
3534
- buildCrypto(space: QuicConnSpace, out: u8[], at: i32, end: i32): i32 {
4422
+ private buildCrypto(space: QuicConnSpace, out: u8[], at: i32, end: i32): i32 {
3535
4423
  if (space.cryptoResendLow >= 0) {
3536
4424
  const low: i64 = space.cryptoResendLow
3537
4425
  const want: i32 = toI32(space.cryptoResendHigh - low)
@@ -3579,12 +4467,63 @@ export class QuicConnection {
3579
4467
  return next
3580
4468
  }
3581
4469
 
4470
+ /**
4471
+ * The path frames of a 1-RTT packet into `out[at .. end)`: every
4472
+ * PATH_RESPONSE owed and the PATH_CHALLENGE on a path being validated.
4473
+ * They go even when the congestion window holds everything else back
4474
+ * (`buildPayloadInto`), so the first packet on a new path validates it
4475
+ * (RFC 9000 §9.3); the path's own 3x limit still bounds them, and a
4476
+ * challenge is drawn at most once a probe timeout.
4477
+ */
4478
+ private buildPathFrames(space: QuicConnSpace, out: u8[], start: i32, end: i32): i32 {
4479
+ let at: i32 = start
4480
+ while (this.pathCount > 0 && end - at >= 9) {
4481
+ const next: i32 = quicPutPathData(
4482
+ out,
4483
+ at,
4484
+ end,
4485
+ QUIC_FRAME_PATH_RESPONSE,
4486
+ this.pathData,
4487
+ (this.pathHead % 4) * QUIC_PATH_DATA_SIZE
4488
+ )
4489
+ if (next < 0) {
4490
+ break
4491
+ }
4492
+ at = next
4493
+ this.pathHead = (this.pathHead + 1) % 4
4494
+ this.pathCount = this.pathCount - 1
4495
+ // Ack-eliciting, but never sent again (RFC 9000 §13.3).
4496
+ space.stagedEliciting = true
4497
+ this.pathFrameStaged = true
4498
+ }
4499
+ // The PATH_CHALLENGE on a path being validated; one lost is not sent
4500
+ // again, but `runPathClock` draws fresh data a probe timeout later.
4501
+ if (this.challengeOwed && this.challengesDrawn > 0 && end - at >= 9) {
4502
+ const slot: i32 = toI32((this.challengesDrawn - 1) % toI64(QUIC_CONN_CHALLENGES))
4503
+ const next: i32 = quicPutPathData(
4504
+ out,
4505
+ at,
4506
+ end,
4507
+ QUIC_FRAME_PATH_CHALLENGE,
4508
+ this.challengeData,
4509
+ slot * QUIC_PATH_DATA_SIZE
4510
+ )
4511
+ if (next >= 0) {
4512
+ at = next
4513
+ this.challengeOwed = false
4514
+ space.stagedEliciting = true
4515
+ this.pathFrameStaged = true
4516
+ }
4517
+ }
4518
+ return at
4519
+ }
4520
+
3582
4521
  /**
3583
4522
  * The 1-RTT frames beyond ACK, as many as fit in `out[at .. end)` and in
3584
4523
  * the packet's record: `QUIC_CONN_PACKET_CONTROL` control frames and
3585
4524
  * `QUIC_CONN_PACKET_STREAMS` STREAM frames, and every DATAGRAM that fits.
3586
4525
  */
3587
- buildApplication(space: QuicConnSpace, out: u8[], start: i32, end: i32): i32 {
4526
+ private buildApplication(space: QuicConnSpace, out: u8[], start: i32, end: i32): i32 {
3588
4527
  let at: i32 = start
3589
4528
  if (this.handshakeDonePending && at < end) {
3590
4529
  at = quicPutTypeOnly(out, at, end, QUIC_FRAME_HANDSHAKE_DONE)
@@ -3593,7 +4532,7 @@ export class QuicConnection {
3593
4532
  space.stagedEliciting = true
3594
4533
  }
3595
4534
  // RETIRE_CONNECTION_ID is at most 9 bytes, NEW_CONNECTION_ID with an
3596
- // 8-byte ID at most 42, PATH_RESPONSE 9.
4535
+ // 8-byte ID at most 42.
3597
4536
  while (
3598
4537
  this.cids.retireCount > 0 &&
3599
4538
  end - at >= 9 &&
@@ -3623,24 +4562,7 @@ export class QuicConnection {
3623
4562
  space.stageControl(QUIC_CONN_CONTROL_NEW_CID, entry.sequence)
3624
4563
  entry = this.cids.nextUnannounced()
3625
4564
  }
3626
- while (this.pathCount > 0 && end - at >= 9) {
3627
- const next: i32 = quicPutPathData(
3628
- out,
3629
- at,
3630
- end,
3631
- QUIC_FRAME_PATH_RESPONSE,
3632
- this.pathData,
3633
- (this.pathHead % 4) * QUIC_PATH_DATA_SIZE
3634
- )
3635
- if (next < 0) {
3636
- break
3637
- }
3638
- at = next
3639
- this.pathHead = (this.pathHead + 1) % 4
3640
- this.pathCount = this.pathCount - 1
3641
- // Ack-eliciting, but never sent again (RFC 9000 §13.3).
3642
- space.stagedEliciting = true
3643
- }
4565
+ at = this.buildPathFrames(space, out, at, end)
3644
4566
  const streams: QuicStreams = this.streams
3645
4567
  while (space.controlCount(space.staging) < QUIC_CONN_PACKET_CONTROL) {
3646
4568
  const next: i32 = streams.putNextControl(out, at, end)
@@ -3677,7 +4599,7 @@ export class QuicConnection {
3677
4599
  * the packet's length, or 0 when it could not be sealed, which only keys
3678
4600
  * `quicKeys` did not make cause.
3679
4601
  */
3680
- sealAt(space: QuicConnSpace, out: u8[], start: i32, payloadEnd: i32): i32 {
4602
+ private sealAt(space: QuicConnSpace, out: u8[], start: i32, payloadEnd: i32): i32 {
3681
4603
  // RFC 9001 §6.6: at the confidentiality limit, with no key update made
3682
4604
  // (`beforeDatagram`), the connection closes, and no packet, its
3683
4605
  // CONNECTION_CLOSE included, is sealed under the key again.
@@ -3743,7 +4665,7 @@ export class QuicConnection {
3743
4665
  * what the packet carried is queued again at once, as though lost.
3744
4666
  * Answers the slot recovery recorded it in, or -1.
3745
4667
  */
3746
- recordSent(space: QuicConnSpace, pn: i64, size: i32): i32 {
4668
+ private recordSent(space: QuicConnSpace, pn: i64, size: i32): i32 {
3747
4669
  if (!space.stagedEliciting) {
3748
4670
  return -1
3749
4671
  }
@@ -3767,7 +4689,7 @@ export class QuicConnection {
3767
4689
  }
3768
4690
 
3769
4691
  /** An acknowledged packet in row `row`: each stream chunk and stream control frame it carried is settled. */
3770
- untrack(space: QuicConnSpace, row: i32): void {
4692
+ private untrack(space: QuicConnSpace, row: i32): void {
3771
4693
  const streams: i32 = space.streamCount(row)
3772
4694
  for (let j: i32 = 0; j < streams; j += 1) {
3773
4695
  const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
@@ -3804,7 +4726,7 @@ export class QuicConnection {
3804
4726
  * 0x1d (§12.4). Before the handshake is complete no 1-RTT packet carries
3805
4727
  * it, because the client cannot yet read one.
3806
4728
  */
3807
- takeCloseInto(out: u8[], at: i32): i32 {
4729
+ private takeCloseInto(out: u8[], at: i32): i32 {
3808
4730
  if (this.closeSent) {
3809
4731
  return 0
3810
4732
  }
@@ -3851,6 +4773,7 @@ export class QuicConnection {
3851
4773
  position = position + this.sealAt(space, out, position, payloadEnd)
3852
4774
  }
3853
4775
  this.bytesSent = this.bytesSent + toI64(position - at)
4776
+ this.notePathSent(position - at)
3854
4777
  return position - at
3855
4778
  }
3856
4779
 
@@ -3881,7 +4804,7 @@ export class QuicConnection {
3881
4804
  * reset tokens and `TlsServer`'s expected client Finished and resumption
3882
4805
  * secret.
3883
4806
  */
3884
- wipeAll(): void {
4807
+ private wipeAll(): void {
3885
4808
  this.discard(this.initial)
3886
4809
  this.discard(this.handshake)
3887
4810
  this.discard(this.application)
@@ -3918,7 +4841,7 @@ export class QuicConnection {
3918
4841
  * and so `release()`, `reset`, the idle timeout and the end of the
3919
4842
  * closing or draining period.
3920
4843
  */
3921
- wipe(): void {
4844
+ private wipe(): void {
3922
4845
  wipe(this.ephemeral)
3923
4846
  wipe(this.readSecret256)
3924
4847
  wipe(this.nextReadSecret256)