nish 0.42.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +11 -5
  2. package/docs/AI.md +287 -129
  3. package/package.json +9 -9
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +24 -0
  7. package/runtime/core.mjs +21 -0
  8. package/runtime/nish.d.ts +167 -24
  9. package/runtime/nish.mjs +7 -1
  10. package/runtime/runtime-cross.c +9 -0
  11. package/runtime/runtime-net.c +51 -13
  12. package/runtime/runtime-region.c +13 -0
  13. package/runtime/runtime-text.c +11 -0
  14. package/runtime/runtime-uring.c +83 -25
  15. package/runtime/runtime-wasm.c +3 -0
  16. package/runtime/runtime.c +329 -6
  17. package/runtime/sqlite/README.md +16 -3
  18. package/runtime/sqlite/nish-sqlite.c +940 -29
  19. package/scripts/build.sh +111 -29
  20. package/skills/writing-nish/SKILL.md +12 -4
  21. package/std/README.md +6 -6
  22. package/std/array.ts +10 -2
  23. package/std/bytes.ts +239 -26
  24. package/std/cli-args.ts +1072 -606
  25. package/std/cli-flags.ts +180 -98
  26. package/std/cli.ts +21 -13
  27. package/std/collections.ts +245 -127
  28. package/std/compress/checksum.ts +32 -37
  29. package/std/compress/deflate.ts +1102 -542
  30. package/std/compress/gzip.ts +290 -145
  31. package/std/compress/zlib.ts +57 -21
  32. package/std/crypto/aes.ts +153 -75
  33. package/std/crypto/base64url.ts +163 -39
  34. package/std/crypto/bcrypt-batch.ts +164 -90
  35. package/std/crypto/bcrypt.ts +185 -107
  36. package/std/crypto/chacha20poly1305.ts +84 -68
  37. package/std/crypto/ct.ts +9 -7
  38. package/std/crypto/ed25519.ts +64 -27
  39. package/std/crypto/hkdf.ts +105 -63
  40. package/std/crypto/hmac.ts +95 -89
  41. package/std/crypto/jwt.ts +248 -126
  42. package/std/crypto/p256.ts +758 -444
  43. package/std/crypto/p384.ts +20 -13
  44. package/std/crypto/pki-roots.ts +95 -38
  45. package/std/crypto/pki.ts +164 -60
  46. package/std/crypto/rsa.ts +266 -223
  47. package/std/crypto/scram.ts +141 -0
  48. package/std/crypto/sha1.ts +157 -57
  49. package/std/crypto/sha256.ts +502 -422
  50. package/std/crypto/sha512.ts +204 -135
  51. package/std/crypto/x509-random.ts +9 -3
  52. package/std/crypto/x509.ts +331 -171
  53. package/std/host/ring.ts +1 -1
  54. package/std/host/text.ts +1 -1
  55. package/std/json-equal.ts +35 -19
  56. package/std/json-format.ts +215 -108
  57. package/std/json-number.ts +126 -72
  58. package/std/json-pointer.ts +42 -13
  59. package/std/json-tokenizer.ts +498 -307
  60. package/std/json-typed.ts +115 -36
  61. package/std/json-value.ts +341 -152
  62. package/std/json.ts +300 -158
  63. package/std/net/buffer-pool.ts +17 -7
  64. package/std/net/dns-config.ts +427 -236
  65. package/std/net/dns-message.ts +114 -47
  66. package/std/net/dns-resolver.ts +736 -237
  67. package/std/net/dns.ts +205 -52
  68. package/std/net/fetch.ts +320 -184
  69. package/std/net/grpc.ts +948 -0
  70. package/std/net/handler.ts +1276 -218
  71. package/std/net/hpack.ts +395 -180
  72. package/std/net/http-compress.ts +502 -65
  73. package/std/net/http-fields.ts +85 -49
  74. package/std/net/http-server.ts +1764 -603
  75. package/std/net/http1-client-codec.ts +372 -161
  76. package/std/net/http1-codec.ts +665 -331
  77. package/std/net/http1-server.ts +881 -269
  78. package/std/net/http2-cleartext.ts +165 -95
  79. package/std/net/http2-frame.ts +232 -89
  80. package/std/net/http2-tls.ts +42 -12
  81. package/std/net/http2.ts +327 -101
  82. package/std/net/http3-frame.ts +68 -33
  83. package/std/net/http3-server.ts +672 -206
  84. package/std/net/http3.ts +669 -191
  85. package/std/net/oidc.ts +63 -24
  86. package/std/net/outbound.ts +207 -142
  87. package/std/net/postgres-async.ts +1223 -470
  88. package/std/net/postgres-carrier.ts +575 -372
  89. package/std/net/postgres.ts +1521 -632
  90. package/std/net/prefork.ts +254 -98
  91. package/std/net/protobuf.ts +1017 -0
  92. package/std/net/qpack.ts +143 -92
  93. package/std/net/quic-conn-ack.ts +104 -22
  94. package/std/net/quic-conn-cid.ts +66 -26
  95. package/std/net/quic-conn-params.ts +13 -7
  96. package/std/net/quic-datagram.ts +90 -27
  97. package/std/net/quic-frame.ts +324 -121
  98. package/std/net/quic-listener.ts +206 -91
  99. package/std/net/quic-packet.ts +289 -163
  100. package/std/net/quic-recovery.ts +279 -128
  101. package/std/net/quic-stream.ts +466 -167
  102. package/std/net/quic.ts +584 -258
  103. package/std/net/router.ts +450 -99
  104. package/std/net/serve.ts +661 -240
  105. package/std/net/static.ts +1458 -0
  106. package/std/net/tls/client.ts +140 -45
  107. package/std/net/tls/codec.ts +510 -260
  108. package/std/net/tls/record-client.ts +268 -76
  109. package/std/net/tls/record-server.ts +236 -79
  110. package/std/net/tls/record.ts +173 -47
  111. package/std/net/tls/schedule.ts +58 -39
  112. package/std/net/tls/ticket.ts +295 -103
  113. package/std/net/tls/verify.ts +1 -1
  114. package/std/net/tls-tcp.ts +218 -75
  115. package/std/net/tls.ts +260 -152
  116. package/std/net/upstream.ts +283 -86
  117. package/std/net/url.ts +277 -102
  118. package/std/net/websocket.ts +532 -209
  119. package/std/net/webtransport.ts +755 -436
  120. package/std/regex.ts +1659 -829
  121. package/std/sqlite.ts +325 -0
  122. package/std/sync/ring.ts +320 -156
  123. package/std/sync/shm.ts +53 -6
  124. package/std/text.ts +285 -135
  125. package/std/threads.ts +22 -2
package/std/net/quic.ts CHANGED
@@ -760,9 +760,12 @@ class QuicConnReassembly {
760
760
  */
761
761
  delivered: i64 = 0
762
762
 
763
- constructor(capacity: i32) {
763
+ /**
764
+ * @param capacity The ring's size in bytes, a `u16` so its arrays' lengths cannot be negative.
765
+ */
766
+ constructor(capacity: u16) {
764
767
  this.ring = new Array<u8>(capacity)
765
- this.have = new Array<u8>((capacity + 7) >> 3)
768
+ this.have = new Array<u8>(toU16((toI32(capacity) + 7) >> 3))
766
769
  }
767
770
 
768
771
  /**
@@ -780,8 +783,8 @@ class QuicConnReassembly {
780
783
  * @internal Read in quic.ts outside the class.
781
784
  */
782
785
  slot(offset: i64): i32 {
783
- const capacity: i32 = toI32(this.ring.length)
784
- return capacity > 0 ? toI32(offset % toI64(capacity)) : 0
786
+ const capacity: i64 = toI64(this.ring.length)
787
+ return capacity > 0 ? toI32(offset % capacity) : 0
785
788
  }
786
789
 
787
790
  /** Whether the byte in ring slot `s` arrived and is not yet handed out. */
@@ -801,20 +804,40 @@ class QuicConnReassembly {
801
804
  * @internal Read in quic.ts outside the class.
802
805
  */
803
806
  insert(offset: i64, data: u8[], from: i32, length: i32): boolean {
804
- const capacity: i32 = toI32(this.ring.length)
805
- if (offset + toI64(length) > this.delivered + toI64(capacity)) {
807
+ const ring: u8[] = this.ring
808
+ const capacity: i32 = toI32(ring.length)
809
+ const delivered: i64 = this.delivered
810
+ // A CRYPTO frame's offset is a varint and `delivered` counts bytes that arrived, so neither is
811
+ // negative and `offset - delivered` is exact; a negative length or range start is no frame's.
812
+ if (offset < 0 || delivered < 0 || length < 0 || from < 0) {
806
813
  return false
807
814
  }
808
- for (let k: i32 = 0; k < length; k += 1) {
809
- const position: i64 = offset + toI64(k)
810
- const at: i32 = from + k
811
- if (position >= this.delivered && at >= 0 && at < toI32(data.length)) {
812
- const s: i32 = this.slot(position)
813
- if (s >= 0 && s < capacity) {
814
- this.ring[s] = data[at]
815
- this.mark(s, true)
816
- }
815
+ // offset + length > delivered + capacity, rearranged so no sum can overflow.
816
+ const ahead: i64 = offset - delivered
817
+ if (ahead > toI64(capacity) - toI64(length)) {
818
+ return false
819
+ }
820
+ // The bytes before `delivered` were handed out already: start at the first one that was not.
821
+ let k: i32 = 0
822
+ let s: i32 = this.slot(offset)
823
+ if (ahead < 0) {
824
+ const behind: i64 = delivered - offset
825
+ if (behind >= toI64(length)) {
826
+ return true
827
+ }
828
+ k = toI32(behind)
829
+ s = this.slot(delivered)
830
+ }
831
+ const dataLength: i32 = toI32(data.length)
832
+ while (k < length && s >= 0 && s < capacity) {
833
+ const wide: i64 = toI64(from) + toI64(k)
834
+ const at: i32 = wide < toI64(dataLength) ? toI32(wide) : -1
835
+ if (at >= 0 && at < toI32(data.length)) {
836
+ ring[s] = data[at]
837
+ this.mark(s, true)
817
838
  }
839
+ k += 1
840
+ s = s + 1 < capacity ? s + 1 : 0
818
841
  }
819
842
  return true
820
843
  }
@@ -826,11 +849,15 @@ class QuicConnReassembly {
826
849
  run(): i32 {
827
850
  const capacity: i32 = toI32(this.ring.length)
828
851
  const start: i32 = this.slot(this.delivered)
829
- let n: i32 = 0
830
- while (start + n < capacity && this.arrived(start + n)) {
831
- n += 1
852
+ if (start < 0) {
853
+ // Never taken: `delivered` is not negative, so neither is its slot.
854
+ return 0
832
855
  }
833
- return n
856
+ let s: i32 = start
857
+ while (s < capacity && this.arrived(s)) {
858
+ s += 1
859
+ }
860
+ return s - start
834
861
  }
835
862
 
836
863
  /**
@@ -838,11 +865,19 @@ class QuicConnReassembly {
838
865
  * @internal Read in quic.ts outside the class.
839
866
  */
840
867
  consume(n: i32): void {
868
+ const capacity: i32 = toI32(this.ring.length)
841
869
  const start: i32 = this.slot(this.delivered)
842
- for (let k: i32 = 0; k < n; k += 1) {
843
- this.mark(start + k, false)
870
+ if (start < 0 || n < 0) {
871
+ // Never taken: `delivered` is not negative, and `n` is a count `run` gave.
872
+ return
873
+ }
874
+ // `run` counts no further than the ring's end, so `s` reaches `start + n` before `capacity`.
875
+ for (let s: i32 = start; s < capacity && s - start < n; s += 1) {
876
+ this.mark(s, false)
844
877
  }
845
- this.delivered = this.delivered + toI64(n)
878
+ // Exact: `delivered` only moves past bytes that arrived, below 2^62 + the ring, and `n` is at
879
+ // most the ring's size, so the sum is far below 2^63 and the u64 add cannot wrap.
880
+ this.delivered = toI64(toU64(this.delivered) + toU64(n))
846
881
  }
847
882
  }
848
883
 
@@ -931,6 +966,8 @@ class QuicConnSpace {
931
966
  * second of each, which a key update derives the next generation into.
932
967
  */
933
968
  keySlots: QuicKeysSlot[]
969
+ /** `keySlots[0]`, held apart so `keySlot` can answer it without an index into the array. */
970
+ private firstKeySlot: QuicKeysSlot
934
971
  /**
935
972
  * `TLS_LEVEL_INITIAL`, `_HANDSHAKE` or `_APPLICATION`, which is also the space's index.
936
973
  * @internal Read in quic.ts outside the class.
@@ -962,28 +999,36 @@ class QuicConnSpace {
962
999
  this.level = level
963
1000
  this.received = new QuicAckRanges()
964
1001
  this.cryptoOut = []
965
- this.keySlots = []
1002
+ this.firstKeySlot = new QuicKeysSlot()
1003
+ this.keySlots = [this.firstKeySlot]
966
1004
  const slots: i32 = level === TLS_LEVEL_APPLICATION ? 4 : 2
967
- for (let k: i32 = 0; k < slots; k += 1) {
1005
+ for (let k: i32 = 1; k < slots; k += 1) {
968
1006
  this.keySlots.push(new QuicKeysSlot())
969
1007
  }
970
- const capacity: i32 =
971
- level === TLS_LEVEL_APPLICATION ? QUIC_RECOVERY_APPLICATION_CAPACITY : QUIC_RECOVERY_HANDSHAKE_CAPACITY
972
- const rows: i32 = capacity + 1
1008
+ const application: boolean = level === TLS_LEVEL_APPLICATION
1009
+ // The row counts are constants folded into `u16`s, so no length below can be negative.
1010
+ const rows: u16 = application
1011
+ ? toU16(QUIC_RECOVERY_APPLICATION_CAPACITY + 1)
1012
+ : toU16(QUIC_RECOVERY_HANDSHAKE_CAPACITY + 1)
973
1013
  // Only 1-RTT packets carry STREAM and control frames (RFC 9000 §12.4).
974
- const chunkRows: i32 = level === TLS_LEVEL_APPLICATION ? rows : 0
975
- this.staging = capacity
1014
+ const streamSlots: u16 = application
1015
+ ? toU16((QUIC_RECOVERY_APPLICATION_CAPACITY + 1) * QUIC_CONN_PACKET_STREAMS)
1016
+ : toU16(0)
1017
+ const controlSlots: u16 = application
1018
+ ? toU16((QUIC_RECOVERY_APPLICATION_CAPACITY + 1) * QUIC_CONN_PACKET_CONTROL)
1019
+ : toU16(0)
1020
+ this.staging = application ? QUIC_RECOVERY_APPLICATION_CAPACITY : QUIC_RECOVERY_HANDSHAKE_CAPACITY
976
1021
  this.sentCryptoOffset = new Array<i64>(rows)
977
1022
  this.sentCryptoLength = new Array<i32>(rows)
978
1023
  this.sentFlags = new Array<u8>(rows)
979
1024
  this.sentStreamCount = new Array<i32>(rows)
980
- this.sentStreamId = new Array<i64>(chunkRows * QUIC_CONN_PACKET_STREAMS)
981
- this.sentStreamOffset = new Array<i64>(chunkRows * QUIC_CONN_PACKET_STREAMS)
982
- this.sentStreamLength = new Array<i32>(chunkRows * QUIC_CONN_PACKET_STREAMS)
983
- this.sentStreamFin = new Array<u8>(chunkRows * QUIC_CONN_PACKET_STREAMS)
1025
+ this.sentStreamId = new Array<i64>(streamSlots)
1026
+ this.sentStreamOffset = new Array<i64>(streamSlots)
1027
+ this.sentStreamLength = new Array<i32>(streamSlots)
1028
+ this.sentStreamFin = new Array<u8>(streamSlots)
984
1029
  this.sentControlCount = new Array<i32>(rows)
985
- this.sentControlKind = new Array<u8>(chunkRows * QUIC_CONN_PACKET_CONTROL)
986
- this.sentControlValue = new Array<i64>(chunkRows * QUIC_CONN_PACKET_CONTROL)
1030
+ this.sentControlKind = new Array<u8>(controlSlots)
1031
+ this.sentControlValue = new Array<i64>(controlSlots)
987
1032
  }
988
1033
 
989
1034
  /**
@@ -1018,10 +1063,12 @@ class QuicConnSpace {
1018
1063
  const at: i32 = this.cryptoOutLength
1019
1064
  if (at >= 0 && at < toI32(this.cryptoOut.length)) {
1020
1065
  this.cryptoOut[at] = bytes[k]
1066
+ this.cryptoOutLength = at + 1
1021
1067
  } else {
1068
+ // `cryptoOutLength` never passes the array's length, so here it equals it and the push is byte `at`.
1022
1069
  this.cryptoOut.push(bytes[k])
1070
+ this.cryptoOutLength = toI32(this.cryptoOut.length)
1023
1071
  }
1024
- this.cryptoOutLength = at + 1
1025
1072
  }
1026
1073
  }
1027
1074
 
@@ -1034,8 +1081,11 @@ class QuicConnSpace {
1034
1081
  * @returns The slot itself, borrowed from the space and reused across keys; slot 0 for a `k` out of range.
1035
1082
  */
1036
1083
  keySlot(k: i32): QuicKeysSlot {
1037
- const at: i32 = k >= 0 && k < toI32(this.keySlots.length) ? k : 0
1038
- return this.keySlots[at]
1084
+ const slots: QuicKeysSlot[] = this.keySlots
1085
+ if (k >= 0 && k < toI32(slots.length)) {
1086
+ return slots[k]
1087
+ }
1088
+ return this.firstKeySlot
1039
1089
  }
1040
1090
 
1041
1091
  /**
@@ -1127,7 +1177,7 @@ class QuicConnSpace {
1127
1177
 
1128
1178
  /** Sets STREAM chunk `j` of row `row`. */
1129
1179
  private setChunk(row: i32, j: i32, id: i64, offset: i64, length: i32, fin: boolean): void {
1130
- const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
1180
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_STREAMS, toI32(this.sentStreamId.length))
1131
1181
  if (
1132
1182
  at >= 0 &&
1133
1183
  at < toI32(this.sentStreamId.length) &&
@@ -1144,7 +1194,7 @@ class QuicConnSpace {
1144
1194
 
1145
1195
  /** Sets control frame `j` of row `row`. */
1146
1196
  private setControl(row: i32, j: i32, kind: i32, value: i64): void {
1147
- const at: i32 = row * QUIC_CONN_PACKET_CONTROL + j
1197
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_CONTROL, toI32(this.sentControlKind.length))
1148
1198
  if (at >= 0 && at < toI32(this.sentControlKind.length) && at < toI32(this.sentControlValue.length)) {
1149
1199
  this.sentControlKind[at] = toU8(kind)
1150
1200
  this.sentControlValue[at] = value
@@ -1166,6 +1216,10 @@ class QuicConnSpace {
1166
1216
  */
1167
1217
  stageChunk(id: i64, offset: i64, length: i32, fin: boolean): void {
1168
1218
  const streams: i32 = this.streamCount(this.staging)
1219
+ if (streams < 0 || streams >= QUIC_CONN_PACKET_STREAMS) {
1220
+ // Never taken: the caller keeps under `QUIC_CONN_PACKET_STREAMS`, and a count is never negative.
1221
+ return
1222
+ }
1169
1223
  this.setChunk(this.staging, streams, id, offset, length, fin)
1170
1224
  this.setCounts(this.staging, streams + 1, this.controlCount(this.staging))
1171
1225
  this.stagedEliciting = true
@@ -1177,6 +1231,10 @@ class QuicConnSpace {
1177
1231
  */
1178
1232
  stageControl(kind: i32, value: i64): void {
1179
1233
  const control: i32 = this.controlCount(this.staging)
1234
+ if (control < 0 || control >= QUIC_CONN_PACKET_CONTROL) {
1235
+ // Never taken: the caller keeps under `QUIC_CONN_PACKET_CONTROL`, and a count is never negative.
1236
+ return
1237
+ }
1180
1238
  this.setControl(this.staging, control, kind, value)
1181
1239
  this.setCounts(this.staging, this.streamCount(this.staging), control + 1)
1182
1240
  this.stagedEliciting = true
@@ -1194,7 +1252,7 @@ class QuicConnSpace {
1194
1252
  const control: i32 = this.controlCount(from)
1195
1253
  this.setCounts(row, streams, control)
1196
1254
  for (let j: i32 = 0; j < streams; j += 1) {
1197
- const at: i32 = from * QUIC_CONN_PACKET_STREAMS + j
1255
+ const at: i32 = quicConnCell(from, j, QUIC_CONN_PACKET_STREAMS, toI32(this.sentStreamId.length))
1198
1256
  if (
1199
1257
  at >= 0 &&
1200
1258
  at < toI32(this.sentStreamId.length) &&
@@ -1213,7 +1271,7 @@ class QuicConnSpace {
1213
1271
  }
1214
1272
  }
1215
1273
  for (let j: i32 = 0; j < control; j += 1) {
1216
- const at: i32 = from * QUIC_CONN_PACKET_CONTROL + j
1274
+ const at: i32 = quicConnCell(from, j, QUIC_CONN_PACKET_CONTROL, toI32(this.sentControlKind.length))
1217
1275
  if (at >= 0 && at < toI32(this.sentControlKind.length) && at < toI32(this.sentControlValue.length)) {
1218
1276
  this.setControl(row, j, toI32(this.sentControlKind[at]), this.sentControlValue[at])
1219
1277
  }
@@ -1228,7 +1286,12 @@ class QuicConnSpace {
1228
1286
  if (length <= 0 || this.discarded) {
1229
1287
  return
1230
1288
  }
1231
- const end: i64 = offset + toI64(length)
1289
+ if (offset < 0) {
1290
+ // Never taken: a CRYPTO offset is a varint.
1291
+ return
1292
+ }
1293
+ // Exact: `offset` is a varint, below 2^62, and `length` an `i32`, so the u64 sum cannot wrap.
1294
+ const end: i64 = toI64(toU64(offset) + toU64(length))
1232
1295
  if (this.cryptoResendLow < 0) {
1233
1296
  this.cryptoResendLow = offset
1234
1297
  this.cryptoResendHigh = end
@@ -1247,17 +1310,37 @@ class QuicConnSpace {
1247
1310
  * @internal Read in quic.ts outside the class.
1248
1311
  */
1249
1312
  cryptoUnsent(): i32 {
1250
- return this.cryptoOutLength - this.cryptoOutHead
1313
+ const length: i32 = this.cryptoOutLength
1314
+ const head: i32 = this.cryptoOutHead
1315
+ if (length < 0 || head < 0) {
1316
+ // Never taken: both count bytes from the stream's start.
1317
+ return 0
1318
+ }
1319
+ return toI32(toI64(length) - toI64(head))
1320
+ }
1321
+ }
1322
+
1323
+ /**
1324
+ * Index of entry `j` of row `row` in a table of `per` entries a row and `length` entries in all,
1325
+ * or -1 when the entry is not in the table.
1326
+ */
1327
+ const quicConnCell = (row: i32, j: i32, per: i32, length: i32): i32 => {
1328
+ if (row < 0 || j < 0 || j >= per || length <= 0) {
1329
+ return -1
1251
1330
  }
1331
+ const at: i64 = toI64(row) * toI64(per) + toI64(j)
1332
+ return at < toI64(length) ? toI32(at) : -1
1252
1333
  }
1253
1334
 
1254
1335
  /** The bytes `bytes[from .. from + length)`, copied into an array of exactly that size. */
1255
- const quicConnSlice = (bytes: u8[], from: i32, length: i32): u8[] => {
1336
+ const quicConnSlice = (bytes: u8[], from: i32, length: u16): u8[] => {
1256
1337
  const out: u8[] = new Array<u8>(length)
1257
1338
  const n: i32 = toI32(out.length)
1258
1339
  for (let k: i32 = 0; k < n; k += 1) {
1259
- if (from + k >= 0 && from + k < toI32(bytes.length)) {
1260
- out[k] = bytes[from + k]
1340
+ const wide: i64 = toI64(from) + toI64(k)
1341
+ const at: i32 = wide >= 0 && wide < toI64(bytes.length) ? toI32(wide) : -1
1342
+ if (at >= 0 && at < toI32(bytes.length)) {
1343
+ out[k] = bytes[at]
1261
1344
  }
1262
1345
  }
1263
1346
  return out
@@ -1321,7 +1404,7 @@ const quicConnWipePacketKey = (keys: QuicKeys | null): void => {
1321
1404
  */
1322
1405
  export const quicStatelessResetToken = (key: u8[], cid: u8[]): u8[] => {
1323
1406
  const mac: u8[] = hmacSha256(key, cid)
1324
- const token: u8[] = quicConnSlice(mac, 0, QUIC_RESET_TOKEN_SIZE)
1407
+ const token: u8[] = quicConnSlice(mac, 0, toU16(QUIC_RESET_TOKEN_SIZE))
1325
1408
  secureZero(mac)
1326
1409
  return token
1327
1410
  }
@@ -1354,32 +1437,105 @@ export const quicConnResetTokenInto = (
1354
1437
  mac.begin(key, QUIC_CONN_FROM, toI32(key.length))
1355
1438
  mac.update(cid, at, length)
1356
1439
  mac.finishInto(tag, QUIC_CONN_FROM)
1357
- for (
1358
- let k: i32 = 0;
1359
- k < QUIC_RESET_TOKEN_SIZE && k < toI32(tag.length) && outAt + k < toI32(out.length);
1360
- k += 1
1361
- ) {
1362
- out[outAt + k] = tag[k]
1440
+ for (let k: i32 = 0; k < QUIC_RESET_TOKEN_SIZE && k < toI32(tag.length); k += 1) {
1441
+ const i: i32 = quicConnAt(outAt, k, toI32(out.length))
1442
+ if (i < 0 || i >= toI32(out.length)) {
1443
+ break
1444
+ }
1445
+ out[i] = tag[k]
1363
1446
  }
1364
1447
  secureZero(tag)
1365
1448
  mac.wipe()
1366
1449
  }
1367
1450
 
1451
+ /** `base + k` when it indexes an array of `length` elements, else -1; the sum is taken in `i64`, so it cannot overflow. */
1452
+ const quicConnAt = (base: i32, k: i32, length: i32): i32 => {
1453
+ const at: i64 = toI64(base) + toI64(k)
1454
+ return at >= 0 && at < toI64(length) ? toI32(at) : -1
1455
+ }
1456
+
1457
+ /**
1458
+ * A new array of `count` zero bytes: none for a count of 0 or less. A count
1459
+ * that fits a `u16` is sized at once; a larger one is pushed byte by byte,
1460
+ * so no `i32` length is computed for `new Array`.
1461
+ */
1462
+ const quicConnBytes = (count: i64): u8[] => {
1463
+ if (count <= 0) {
1464
+ return []
1465
+ }
1466
+ if (count <= 65535) {
1467
+ return new Array<u8>(toU16(count))
1468
+ }
1469
+ const out: u8[] = []
1470
+ while (toI64(out.length) < count) {
1471
+ out.push(toU8(0))
1472
+ }
1473
+ return out
1474
+ }
1475
+
1476
+ /**
1477
+ * `a + b`, stopping at the largest or smallest `i64` instead of wrapping. Its
1478
+ * callers add a span to a time in milliseconds or a datagram's size to a byte
1479
+ * count, which are never near either end, so the sum is exact on every path a
1480
+ * connection takes. The add is done in `u64`, where it wraps to the same bits
1481
+ * as an exact two's-complement sum, and a wrap shows as a sign the operands
1482
+ * did not have.
1483
+ */
1484
+ const quicConnSum = (a: i64, b: i64): i64 => {
1485
+ const sum: i64 = toI64(toU64(a) + toU64(b))
1486
+ if (a >= 0 && b >= 0 && sum < 0) {
1487
+ return toI64((toU64(1) << toU64(63)) - toU64(1))
1488
+ }
1489
+ if (a < 0 && b < 0 && sum >= 0) {
1490
+ return toI64(toU64(1) << toU64(63))
1491
+ }
1492
+ return sum
1493
+ }
1494
+
1495
+ /**
1496
+ * Where entry `index` of a ring of `entries` entries, each
1497
+ * `QUIC_PATH_DATA_SIZE` bytes, starts: `(index % entries) *
1498
+ * QUIC_PATH_DATA_SIZE`. A negative index or an empty ring, which no caller
1499
+ * passes, answers -1.
1500
+ */
1501
+ const quicConnRingAt = (index: i64, entries: i32): i32 => {
1502
+ if (index < 0) {
1503
+ return -1
1504
+ }
1505
+ const n: i64 = toI64(entries)
1506
+ if (n <= 0) {
1507
+ return -1
1508
+ }
1509
+ return toI32(toI64(toI32(index % n)) * toI64(QUIC_PATH_DATA_SIZE))
1510
+ }
1511
+
1512
+ /**
1513
+ * `received * 3 - sent`, what the anti-amplification limit (RFC 9000 §8.1)
1514
+ * leaves a path. Byte counts are never near the ends of `i64`, so the
1515
+ * arithmetic, done in `u64` where it wraps to the bits of the exact result,
1516
+ * is exact.
1517
+ */
1518
+ const quicConnThrice = (received: i64, sent: i64): i64 => toI64(toU64(received) * toU64(3) - toU64(sent))
1519
+
1368
1520
  /** Puts `from[at .. at + length)` in `to`, emptied first, in the room `to` already has. */
1369
1521
  const quicConnRefill = (to: u8[], from: u8[], at: i32, length: i32): void => {
1370
1522
  while (to.length > 0) {
1371
1523
  to.pop()
1372
1524
  }
1373
- for (let k: i32 = 0; k < length && at + k >= 0 && at + k < toI32(from.length); k += 1) {
1374
- to.push(from[at + k])
1525
+ for (let k: i32 = 0; k < length; k += 1) {
1526
+ const i: i32 = quicConnAt(at, k, toI32(from.length))
1527
+ if (i < 0 || i >= toI32(from.length)) {
1528
+ break
1529
+ }
1530
+ to.push(from[i])
1375
1531
  }
1376
1532
  }
1377
1533
 
1378
1534
  /** Copies `length` bytes from `from[fromAt]` to `to[toAt]`, as far as both arrays reach. */
1379
1535
  const quicConnCopyAt = (to: u8[], toAt: i32, from: u8[], fromAt: i32, length: i32): void => {
1380
1536
  for (let k: i32 = 0; k < length; k += 1) {
1381
- const i: i32 = toAt + k
1382
- const j: i32 = fromAt + k
1537
+ const i: i32 = quicConnAt(toAt, k, toI32(to.length))
1538
+ const j: i32 = quicConnAt(fromAt, k, toI32(from.length))
1383
1539
  if (i >= 0 && i < toI32(to.length) && j >= 0 && j < toI32(from.length)) {
1384
1540
  to[i] = from[j]
1385
1541
  }
@@ -1434,27 +1590,42 @@ const quicWorkerMark = (config: QuicServerConfig, cid: u8[]): void => {
1434
1590
  }
1435
1591
 
1436
1592
  /** Whether the configuration's limits are ones this module can honour. */
1437
- const quicConnConfigFits = (config: QuicServerConfig): boolean =>
1438
- config.maxStreamData >= 1 &&
1439
- config.maxStreamData <= QUIC_CONN_MAX_STREAM_DATA &&
1440
- config.maxStreamsBidi >= 0 &&
1441
- config.maxStreamsBidi <= QUIC_CONN_MAX_STREAMS &&
1442
- config.maxStreamsUni >= 0 &&
1443
- config.maxStreamsUni <= QUIC_CONN_MAX_STREAMS &&
1444
- config.localStreams >= 0 &&
1445
- config.localStreams <= QUIC_CONN_MAX_STREAMS &&
1446
- (config.maxStreamsBidi + config.maxStreamsUni + config.localStreams) * config.maxStreamData * 2 <=
1447
- QUIC_CONN_MAX_STREAM_BUFFERS &&
1448
- config.maxDatagramFrameSize >= 0 &&
1449
- config.maxDatagramFrameSize <= QUIC_CONN_MAX_DATAGRAM_FRAME &&
1450
- config.maxData >= 0 &&
1451
- config.maxData <= QUIC_MAX_VARINT &&
1452
- config.maxIdleTimeout >= 0 &&
1453
- config.maxIdleTimeout <= QUIC_MAX_VARINT &&
1454
- config.activeConnectionIdLimit >= 2 &&
1455
- config.activeConnectionIdLimit <= 8 &&
1456
- (config.congestion === QUIC_RECOVERY_NEWRENO || config.congestion === QUIC_RECOVERY_CUBIC) &&
1457
- toI32(config.statelessResetKey.length) === QUIC_CONN_STATIC_KEY_SIZE
1593
+ const quicConnConfigFits = (config: QuicServerConfig): boolean => {
1594
+ const data: i64 = config.maxStreamData
1595
+ const bidi: i64 = config.maxStreamsBidi
1596
+ const uni: i64 = config.maxStreamsUni
1597
+ const local: i64 = config.localStreams
1598
+ if (
1599
+ data < 1 ||
1600
+ data > QUIC_CONN_MAX_STREAM_DATA ||
1601
+ bidi < 0 ||
1602
+ bidi > QUIC_CONN_MAX_STREAMS ||
1603
+ uni < 0 ||
1604
+ uni > QUIC_CONN_MAX_STREAMS ||
1605
+ local < 0 ||
1606
+ local > QUIC_CONN_MAX_STREAMS
1607
+ ) {
1608
+ return false
1609
+ }
1610
+ // At most 3 * 1024 streams of 2^20 bytes each, twice over: below 2^33, so nothing here overflows.
1611
+ // Taken in `u64` as the prover does not carry the bounds above into the product.
1612
+ const buffers: u64 = (toU64(bidi) + toU64(uni) + toU64(local)) * toU64(data) * 2
1613
+ if (buffers > toU64(QUIC_CONN_MAX_STREAM_BUFFERS)) {
1614
+ return false
1615
+ }
1616
+ return (
1617
+ config.maxDatagramFrameSize >= 0 &&
1618
+ config.maxDatagramFrameSize <= QUIC_CONN_MAX_DATAGRAM_FRAME &&
1619
+ config.maxData >= 0 &&
1620
+ config.maxData <= QUIC_MAX_VARINT &&
1621
+ config.maxIdleTimeout >= 0 &&
1622
+ config.maxIdleTimeout <= QUIC_MAX_VARINT &&
1623
+ config.activeConnectionIdLimit >= 2 &&
1624
+ config.activeConnectionIdLimit <= 8 &&
1625
+ (config.congestion === QUIC_RECOVERY_NEWRENO || config.congestion === QUIC_RECOVERY_CUBIC) &&
1626
+ toI32(config.statelessResetKey.length) === QUIC_CONN_STATIC_KEY_SIZE
1627
+ )
1628
+ }
1458
1629
 
1459
1630
  /**
1460
1631
  * One server connection, which is also a reusable slot. Make one, hand it
@@ -1712,6 +1883,17 @@ export class QuicConnection {
1712
1883
  datagramEcn: i32 = 0
1713
1884
  /** Whether the carrier sends with the ECN bits of `datagramEcn`; the carrier sets it, and `reset` keeps it. */
1714
1885
  ecnMarking: boolean = false
1886
+ /**
1887
+ * The ECN bits the next datagram handed to `receive`, `receiveWindow` or
1888
+ * `receiveWindowFrom` arrived with (the IP header's two low traffic-class
1889
+ * bits: 0 Not-ECT, 1 ECT(1), 2 ECT(0), 3 CE), which the carrier sets before
1890
+ * the call and keeps for every coalesced packet of that datagram. Each
1891
+ * packet that opens and is not a duplicate adds them to its packet number
1892
+ * space's counts (RFC 9000 §13.4.1), which the space's ACKs then carry as
1893
+ * an ACK_ECN. A carrier that cannot read the bits leaves it 0, and its
1894
+ * ACKs stay plain. `reset` clears it.
1895
+ */
1896
+ arrivalEcn: i32 = 0
1715
1897
  /** Whether `error` is an application code (CONNECTION_CLOSE 0x1d) rather than a transport error. */
1716
1898
  errorIsApplication: boolean = false
1717
1899
  /** Whether the one CONNECTION_CLOSE this side owes has gone out. */
@@ -1849,14 +2031,14 @@ export class QuicConnection {
1849
2031
  datagrams,
1850
2032
  fits ? toI32(config.maxDatagramFrameSize) : QUIC_CONN_FROM
1851
2033
  )
1852
- this.cryptoIn = new QuicConnReassembly(QUIC_CONN_CRYPTO_WINDOW)
1853
- this.pathData = new Array<u8>(QUIC_PATH_DATA_SIZE * 4)
2034
+ this.cryptoIn = new QuicConnReassembly(toU16(QUIC_CONN_CRYPTO_WINDOW))
2035
+ this.pathData = new Array<u8>(toU16(QUIC_PATH_DATA_SIZE * 4))
1854
2036
  this.pathCurrent = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1855
2037
  this.pathValidated = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1856
2038
  this.pathArrival = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1857
2039
  this.probeAddress = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1858
2040
  this.probeData = new Array<u8>(QUIC_PATH_DATA_SIZE)
1859
- this.challengeData = new Array<u8>(QUIC_PATH_DATA_SIZE * QUIC_CONN_CHALLENGES)
2041
+ this.challengeData = new Array<u8>(toU16(QUIC_PATH_DATA_SIZE * QUIC_CONN_CHALLENGES))
1860
2042
  this.frame = new QuicFrame()
1861
2043
  this.header = new QuicHeader()
1862
2044
  this.packet = new QuicPacket()
@@ -1953,6 +2135,7 @@ export class QuicConnection {
1953
2135
  this.sealedUnderKey = 0
1954
2136
  this.authFailures = 0
1955
2137
  this.datagramEcn = 0
2138
+ this.arrivalEcn = 0
1956
2139
  this.nextSkip = -1
1957
2140
  quicConnForgetSkips(this.skipped)
1958
2141
  this.skipsDrawn = 0
@@ -1996,8 +2179,9 @@ export class QuicConnection {
1996
2179
 
1997
2180
  /** Counts a dropped packet; the count stops at the largest `i32` rather than overflow. */
1998
2181
  private drop(): void {
1999
- if (this.dropped < 2147483647) {
2000
- this.dropped += 1
2182
+ const n: i32 = this.dropped
2183
+ if (n < 2147483647) {
2184
+ this.dropped = n + 1
2001
2185
  }
2002
2186
  }
2003
2187
 
@@ -2085,7 +2269,8 @@ export class QuicConnection {
2085
2269
  * keep them.
2086
2270
  */
2087
2271
  private startClosingPeriod(): void {
2088
- this.closingUntil = this.now + this.recovery.probeTimeout() * 3
2272
+ const probe: i64 = this.recovery.probeTimeout()
2273
+ this.closingUntil = quicConnSum(this.now, quicConnSum(quicConnSum(probe, probe), probe))
2089
2274
  }
2090
2275
 
2091
2276
  /** The space of packets of `type`, or `null` for a 0-RTT or Retry packet. */
@@ -2206,7 +2391,9 @@ export class QuicConnection {
2206
2391
  this.drop()
2207
2392
  return 0
2208
2393
  }
2209
- const end: i32 = off + len
2394
+ // The check above leaves `off + len` at most the array's length, so the
2395
+ // sum taken in `i64` is exact.
2396
+ const end: i32 = toI32(toI64(off) + toI64(len))
2210
2397
  let at: i32 = off
2211
2398
  let counted: boolean = false
2212
2399
  while (at < end) {
@@ -2225,7 +2412,7 @@ export class QuicConnection {
2225
2412
  // A datagram counts toward the amplification limit once one of its packets
2226
2413
  // proves it is this connection's (RFC 9000 §8.1).
2227
2414
  if (counted) {
2228
- this.bytesReceived = this.bytesReceived + toI64(len)
2415
+ this.bytesReceived = quicConnSum(this.bytesReceived, toI64(len))
2229
2416
  }
2230
2417
  if (!this.closed()) {
2231
2418
  this.afterPath(counted, len)
@@ -2442,7 +2629,8 @@ export class QuicConnection {
2442
2629
  // connection's private pools, so the handshake, not the first 1-RTT
2443
2630
  // packet, pays for them.
2444
2631
  if (type === QUIC_PACKET_SHORT || type === QUIC_PACKET_ZERO_RTT) {
2445
- this.streams.prime(header.end - header.pnOffset)
2632
+ // The parser leaves both in the datagram, the end past the packet number.
2633
+ this.streams.prime(toI32(toI64(header.end) - toI64(header.pnOffset)))
2446
2634
  } else {
2447
2635
  this.streams.ownPools()
2448
2636
  }
@@ -2513,7 +2701,7 @@ export class QuicConnection {
2513
2701
  // reads nothing more. A first Initial that fails is not counted: the
2514
2702
  // connection is not started, and the next one starts afresh.
2515
2703
  if (!first) {
2516
- this.authFailures = this.authFailures + 1
2704
+ this.authFailures = quicConnSum(this.authFailures, 1)
2517
2705
  if (this.authFailures > this.integrityLimit) {
2518
2706
  this.fail(QUIC_ERROR_AEAD_LIMIT_REACHED, QUIC_CONN_NONE)
2519
2707
  }
@@ -2549,7 +2737,10 @@ export class QuicConnection {
2549
2737
  if (eliciting && type === QUIC_PACKET_HANDSHAKE) {
2550
2738
  this.resendLevel = TLS_LEVEL_HANDSHAKE
2551
2739
  }
2552
- space.received.record(pn, eliciting)
2740
+ // §13.4.1: a packet processed, not a duplicate, counts its datagram's ECN bits in its space.
2741
+ if (space.received.record(pn, eliciting)) {
2742
+ space.received.countEcn(this.arrivalEcn)
2743
+ }
2553
2744
  // §10.1: a packet received and processed restarts the idle timer.
2554
2745
  this.idleSince = this.now
2555
2746
  this.elicitingSent = false
@@ -2603,7 +2794,13 @@ export class QuicConnection {
2603
2794
  */
2604
2795
  private applyPhase(pn: i64): void {
2605
2796
  if (this.writePhase === this.readPhase) {
2606
- this.keyUpdates = this.keyUpdates + 1
2797
+ // `notePhase` refused the packet at the limit, so this is never taken.
2798
+ const updates: i32 = this.keyUpdates
2799
+ if (updates >= QUIC_CONN_MAX_KEY_UPDATES) {
2800
+ this.fail(QUIC_ERROR_KEY_UPDATE, QUIC_CONN_NONE)
2801
+ return
2802
+ }
2803
+ this.keyUpdates = updates + 1
2607
2804
  if (!this.updateWriteKeys()) {
2608
2805
  this.fail(QUIC_ERROR_INTERNAL, QUIC_CONN_NONE)
2609
2806
  return
@@ -2613,7 +2810,7 @@ export class QuicConnection {
2613
2810
  this.application.readKeys = this.otherReadKeys
2614
2811
  this.otherReadKeys = previous
2615
2812
  this.otherIsNext = false
2616
- this.appReadSlot = 1 - this.appReadSlot
2813
+ this.appReadSlot = this.appReadSlot === 0 ? 1 : 0
2617
2814
  // The next read secret becomes the current one, over the secret it
2618
2815
  // replaces, and is zeroed where it was. Both widths move: the one the
2619
2816
  // suite does not use holds zeros.
@@ -2624,7 +2821,7 @@ export class QuicConnection {
2624
2821
  this.readPhase = !this.readPhase
2625
2822
  this.readPhaseLowest = pn
2626
2823
  this.readPhaseHighest = pn
2627
- this.keyRetainUntil = this.now + this.recovery.probeTimeout()
2824
+ this.keyRetainUntil = quicConnSum(this.now, this.recovery.probeTimeout())
2628
2825
  }
2629
2826
 
2630
2827
  /**
@@ -2638,7 +2835,9 @@ export class QuicConnection {
2638
2835
  if (keys === null) {
2639
2836
  return false
2640
2837
  }
2641
- const slot: QuicKeysSlot = this.application.keySlot(QUIC_CONN_APP_WRITE_SLOTS + 1 - this.appWriteSlot)
2838
+ const slot: QuicKeysSlot = this.application.keySlot(
2839
+ this.appWriteSlot === 0 ? QUIC_CONN_APP_WRITE_SLOTS + 1 : QUIC_CONN_APP_WRITE_SLOTS
2840
+ )
2642
2841
  const next: QuicKeys | null =
2643
2842
  keys.aead === QUIC_AEAD_AES_256_GCM
2644
2843
  ? this.nextKeys(slot, keys, this.writeSecret384, this.writeSecret384)
@@ -2648,7 +2847,7 @@ export class QuicConnection {
2648
2847
  }
2649
2848
  quicConnWipePacketKey(keys)
2650
2849
  this.application.writeKeys = next
2651
- this.appWriteSlot = 1 - this.appWriteSlot
2850
+ this.appWriteSlot = this.appWriteSlot === 0 ? 1 : 0
2652
2851
  this.writePhase = !this.writePhase
2653
2852
  this.writePhaseFirst = this.application.nextPn
2654
2853
  this.sealedUnderKey = 0
@@ -2692,15 +2891,20 @@ export class QuicConnection {
2692
2891
  {
2693
2892
  using _scope = arena()
2694
2893
  const plain: u8[] = expose(current, tlsHeldClone)
2695
- const out: u8[] = new Array<u8>(plain.length)
2696
- made =
2697
- quicKeyUpdateSecretInto(this.kdf, keys.aead, plain, out) &&
2698
- quicKeysUpdateInto(this.kdf, slot, keys, out) !== null
2699
- if (made) {
2700
- exposeWith(next, out, tlsHeldCopyIn)
2894
+ // A traffic secret is its hash's length, 32 or 48 bytes, so the size
2895
+ // check never fails; one that did would make no keys.
2896
+ const size: i32 = toI32(plain.length)
2897
+ if (size > 0 && size <= 255) {
2898
+ const out: u8[] = new Array<u8>(toU8(size))
2899
+ made =
2900
+ quicKeyUpdateSecretInto(this.kdf, keys.aead, plain, out) &&
2901
+ quicKeysUpdateInto(this.kdf, slot, keys, out) !== null
2902
+ if (made) {
2903
+ exposeWith(next, out, tlsHeldCopyIn)
2904
+ }
2905
+ secureZero(out)
2701
2906
  }
2702
2907
  secureZero(plain)
2703
- secureZero(out)
2704
2908
  }
2705
2909
  return made ? slot.keys : null
2706
2910
  }
@@ -2721,7 +2925,8 @@ export class QuicConnection {
2721
2925
  if (keys === null) {
2722
2926
  return
2723
2927
  }
2724
- const slot: QuicKeysSlot = this.application.keySlot(1 - this.appReadSlot)
2928
+ const otherSlot: i32 = this.appReadSlot === 0 ? 1 : 0
2929
+ const slot: QuicKeysSlot = this.application.keySlot(otherSlot)
2725
2930
  this.otherReadKeys =
2726
2931
  keys.aead === QUIC_AEAD_AES_256_GCM
2727
2932
  ? this.nextKeys(slot, keys, this.readSecret384, this.nextReadSecret384)
@@ -2987,8 +3192,13 @@ export class QuicConnection {
2987
3192
  const ranges: i64[] = frame.ackRanges
2988
3193
  for (let k: i32 = 0; k < toI32(this.skipped.length); k += 1) {
2989
3194
  const pn: i64 = this.skipped[k]
2990
- for (let r: i32 = 0; pn >= 0 && r < frame.ackRangeCount && r * 2 + 1 < toI32(ranges.length); r += 1) {
2991
- if (pn >= ranges[r * 2] && pn <= ranges[r * 2 + 1]) {
3195
+ for (let r: i32 = 0; pn >= 0 && r < frame.ackRangeCount; r += 1) {
3196
+ const lo: i32 = quicConnCell(r, 0, 2, toI32(ranges.length))
3197
+ const hi: i32 = quicConnCell(r, 1, 2, toI32(ranges.length))
3198
+ if (lo < 0 || hi < 0 || lo >= toI32(ranges.length) || hi >= toI32(ranges.length)) {
3199
+ break
3200
+ }
3201
+ if (pn >= ranges[lo] && pn <= ranges[hi]) {
2992
3202
  return true
2993
3203
  }
2994
3204
  }
@@ -3117,7 +3327,7 @@ export class QuicConnection {
3117
3327
  this.application.probes === 0 &&
3118
3328
  sent !== null &&
3119
3329
  !sent.full() &&
3120
- this.recovery.bytesInFlight() + toI64(size) <= this.recovery.congestionWindow
3330
+ quicConnSum(this.recovery.bytesInFlight(), toI64(size)) <= this.recovery.congestionWindow
3121
3331
  )
3122
3332
  }
3123
3333
 
@@ -3129,12 +3339,22 @@ export class QuicConnection {
3129
3339
  private buildPmtuProbe(out: u8[], at: i32, size: i32): i32 {
3130
3340
  const space: QuicConnSpace = this.application
3131
3341
  const overhead: i32 = this.overhead(space)
3132
- if (overhead === 0 || overhead + 1 > size) {
3342
+ if (overhead === 0 || overhead >= size) {
3343
+ return 0
3344
+ }
3345
+ // `pmtuDue` checked the probe fits the room after `at`, so this is never
3346
+ // taken; were it, the probe would go unsealed.
3347
+ const start: i64 = toI64(at) + toI64(overhead) - toI64(QUIC_AEAD_TAG_SIZE)
3348
+ const end: i64 = toI64(at) + toI64(size) - toI64(QUIC_AEAD_TAG_SIZE)
3349
+ if (start < 0 || end < start || end > toI64(out.length)) {
3350
+ return 0
3351
+ }
3352
+ if (end < 0) {
3133
3353
  return 0
3134
3354
  }
3135
3355
  space.clearStaged()
3136
- const payloadStart: i32 = at + overhead - QUIC_AEAD_TAG_SIZE
3137
- const payloadEnd: i32 = at + size - QUIC_AEAD_TAG_SIZE
3356
+ const payloadStart: i32 = toI32(start)
3357
+ const payloadEnd: i32 = toI32(end)
3138
3358
  const ping: i32 = quicPutTypeOnly(out, payloadStart, payloadEnd, QUIC_FRAME_PING)
3139
3359
  if (ping < 0) {
3140
3360
  return 0
@@ -3142,21 +3362,22 @@ export class QuicConnection {
3142
3362
  space.stagedEliciting = true
3143
3363
  const pn: i64 = space.nextPn
3144
3364
  this.pmtuSealing = true
3145
- const n: i32 = this.sealAt(space, out, at, quicPutPadding(out, ping, payloadEnd - ping))
3365
+ const n: i32 = this.sealAt(space, out, at, quicPutPadding(out, ping, toI32(end - toI64(ping))))
3146
3366
  this.pmtuSealing = false
3147
3367
  if (n <= 0) {
3148
3368
  return 0
3149
3369
  }
3150
3370
  this.pmtuProbeSize = n
3151
3371
  this.pmtuProbePn = pn
3152
- if (this.pmtuProbes < 2147483647) {
3153
- this.pmtuProbes = this.pmtuProbes + 1
3372
+ const pmtuProbes: i32 = this.pmtuProbes
3373
+ if (pmtuProbes < 2147483647) {
3374
+ this.pmtuProbes = pmtuProbes + 1
3154
3375
  }
3155
3376
  if (!this.elicitingSent) {
3156
3377
  this.idleSince = this.now
3157
3378
  this.elicitingSent = true
3158
3379
  }
3159
- this.bytesSent = this.bytesSent + toI64(n)
3380
+ this.bytesSent = quicConnSum(this.bytesSent, toI64(n))
3160
3381
  this.notePathSent(n)
3161
3382
  return n
3162
3383
  }
@@ -3188,15 +3409,18 @@ export class QuicConnection {
3188
3409
 
3189
3410
  /** The probe numbered `pn` was lost: after three of one size, the search goes on below it. */
3190
3411
  private pmtuProbeLost(pn: i64): void {
3191
- if (this.pmtuProbesLost < 2147483647) {
3192
- this.pmtuProbesLost = this.pmtuProbesLost + 1
3412
+ const pmtuProbesLost: i32 = this.pmtuProbesLost
3413
+ if (pmtuProbesLost < 2147483647) {
3414
+ this.pmtuProbesLost = pmtuProbesLost + 1
3193
3415
  }
3194
- if (this.pmtuProbeSize === 0 || pn !== this.pmtuProbePn) {
3416
+ const size: i32 = this.pmtuProbeSize
3417
+ if (size <= 0 || pn !== this.pmtuProbePn) {
3195
3418
  return
3196
3419
  }
3197
- const size: i32 = this.pmtuProbeSize
3198
3420
  this.pmtuProbeSize = 0
3199
- this.pmtuTries = this.pmtuTries + 1
3421
+ // `pmtuStep` sets the count back to 0 when it reaches 3.
3422
+ const tries: i32 = this.pmtuTries
3423
+ this.pmtuTries = tries < 3 ? tries + 1 : 3
3200
3424
  if (this.pmtuTries >= 3) {
3201
3425
  this.pmtuHigh = size - 1
3202
3426
  this.pmtuStep()
@@ -3209,19 +3433,26 @@ export class QuicConnection {
3209
3433
  * (RFC 8899 §4.3), and `pathMtu` falls back to 1200.
3210
3434
  */
3211
3435
  private pmtuLargeLost(): void {
3212
- this.pmtuSuspect = this.pmtuSuspect + 1
3213
- if (this.pmtuSuspect < 3 || this.pathMtu <= QUIC_CONN_DATAGRAM_SIZE) {
3214
- return
3436
+ const suspect: i32 = this.pmtuSuspect
3437
+ if (suspect < 2147483647) {
3438
+ this.pmtuSuspect = suspect + 1
3215
3439
  }
3216
3440
  const failed: i32 = this.pathMtu
3441
+ if (this.pmtuSuspect < 3) {
3442
+ return
3443
+ }
3444
+ if (failed <= QUIC_CONN_DATAGRAM_SIZE) {
3445
+ return
3446
+ }
3217
3447
  this.pathMtu = QUIC_CONN_DATAGRAM_SIZE
3218
3448
  this.recovery.setDatagramSize(toI64(QUIC_CONN_DATAGRAM_SIZE))
3219
3449
  this.pmtuSuspect = 0
3220
3450
  this.pmtuProbeSize = 0
3221
3451
  this.pmtuLow = QUIC_CONN_DATAGRAM_SIZE
3222
- this.pmtuHigh = failed - 1
3223
- if (this.pmtuBlackHoles < 2147483647) {
3224
- this.pmtuBlackHoles = this.pmtuBlackHoles + 1
3452
+ this.pmtuHigh = toI32(toI64(failed) - 1)
3453
+ const pmtuBlackHoles: i32 = this.pmtuBlackHoles
3454
+ if (pmtuBlackHoles < 2147483647) {
3455
+ this.pmtuBlackHoles = pmtuBlackHoles + 1
3225
3456
  }
3226
3457
  this.pmtuStep()
3227
3458
  }
@@ -3229,7 +3460,15 @@ export class QuicConnection {
3229
3460
  /** The next size to try, halfway between the bounds, or 0 when they are within 16 bytes. */
3230
3461
  private pmtuStep(): void {
3231
3462
  this.pmtuTries = 0
3232
- this.pmtuNext = this.pmtuHigh - this.pmtuLow < 16 ? 0 : (this.pmtuLow + this.pmtuHigh + 1) / 2
3463
+ const low: i32 = this.pmtuLow
3464
+ const high: i32 = this.pmtuHigh
3465
+ // Both bounds are sizes, at least 1200 bytes, so the guard is never
3466
+ // taken; were it, the search would stop.
3467
+ if (low < 0 || high < 0) {
3468
+ this.pmtuNext = 0
3469
+ return
3470
+ }
3471
+ this.pmtuNext = toI64(high) - toI64(low) < 16 ? 0 : toI32((toI64(low) + toI64(high) + 1) / 2)
3233
3472
  }
3234
3473
 
3235
3474
  /**
@@ -3246,7 +3485,7 @@ export class QuicConnection {
3246
3485
  }
3247
3486
  const streams: i32 = space.streamCount(row)
3248
3487
  for (let j: i32 = 0; j < streams; j += 1) {
3249
- const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
3488
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_STREAMS, toI32(space.sentStreamId.length))
3250
3489
  if (
3251
3490
  at >= 0 &&
3252
3491
  at < toI32(space.sentStreamId.length) &&
@@ -3264,7 +3503,7 @@ export class QuicConnection {
3264
3503
  }
3265
3504
  const control: i32 = space.controlCount(row)
3266
3505
  for (let j: i32 = 0; j < control; j += 1) {
3267
- const at: i32 = row * QUIC_CONN_PACKET_CONTROL + j
3506
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_CONTROL, toI32(space.sentControlKind.length))
3268
3507
  if (at >= 0 && at < toI32(space.sentControlKind.length) && at < toI32(space.sentControlValue.length)) {
3269
3508
  this.requeueControl(toI32(space.sentControlKind[at]), space.sentControlValue[at])
3270
3509
  }
@@ -3330,11 +3569,11 @@ export class QuicConnection {
3330
3569
  * datagram (`takeDatagramInto`).
3331
3570
  */
3332
3571
  private resendEarly(level: i32): void {
3333
- if (
3334
- this.earlyResends >= QUIC_CONN_EARLY_RESENDS ||
3335
- this.initial.probes > 0 ||
3336
- this.handshake.probes > 0
3337
- ) {
3572
+ const resends: i32 = this.earlyResends
3573
+ if (resends >= QUIC_CONN_EARLY_RESENDS) {
3574
+ return
3575
+ }
3576
+ if (this.initial.probes > 0 || this.handshake.probes > 0) {
3338
3577
  return
3339
3578
  }
3340
3579
  const asked: QuicSentPackets | null = this.recovery.space(level)
@@ -3342,7 +3581,7 @@ export class QuicConnection {
3342
3581
  return
3343
3582
  }
3344
3583
  let queued: boolean = false
3345
- for (let at: i32 = level; at <= TLS_LEVEL_HANDSHAKE; at += 1) {
3584
+ for (let at: i32 = level; at < TLS_LEVEL_HANDSHAKE + 1; at += 1) {
3346
3585
  const space: QuicConnSpace = this.spaceAt(at)
3347
3586
  const sent: QuicSentPackets | null = this.recovery.space(at)
3348
3587
  if (sent === null || space.discarded || sent.inFlight === 0) {
@@ -3359,7 +3598,7 @@ export class QuicConnection {
3359
3598
  }
3360
3599
  }
3361
3600
  if (queued) {
3362
- this.earlyResends += 1
3601
+ this.earlyResends = resends + 1
3363
3602
  }
3364
3603
  }
3365
3604
 
@@ -3374,7 +3613,7 @@ export class QuicConnection {
3374
3613
  private receiveCrypto(space: QuicConnSpace, frame: QuicFrame, payload: u8[]): void {
3375
3614
  const reassembly: QuicConnReassembly = this.cryptoIn
3376
3615
  if (space.level < reassembly.level) {
3377
- if (frame.offset + toI64(frame.dataLength) > space.cryptoInDelivered) {
3616
+ if (quicConnSum(frame.offset, toI64(frame.dataLength)) > space.cryptoInDelivered) {
3378
3617
  this.fail(QUIC_ERROR_CRYPTO + QUIC_CONN_ALERT_UNEXPECTED, toI64(QUIC_FRAME_CRYPTO))
3379
3618
  }
3380
3619
  return
@@ -3429,7 +3668,7 @@ export class QuicConnection {
3429
3668
  * `readDatagram`, or is dropped when the ring is full.
3430
3669
  */
3431
3670
  private receiveDatagram(frame: QuicFrame, payload: u8[], frameStart: i32): void {
3432
- const size: i64 = toI64(frame.end - frameStart)
3671
+ const size: i64 = toI64(frame.end) - toI64(frameStart)
3433
3672
  if (this.config.maxDatagramFrameSize === 0 || size > this.config.maxDatagramFrameSize) {
3434
3673
  // `fin` is how the frame says it was 0x31, the type with a Length.
3435
3674
  this.fail(
@@ -3456,14 +3695,21 @@ export class QuicConnection {
3456
3695
  this.pathHead = 0
3457
3696
  this.pathCount = 0
3458
3697
  }
3459
- const base: i32 = ((this.pathHead + this.pathCount) % 4) * QUIC_PATH_DATA_SIZE
3460
- for (let k: i32 = 0; k < QUIC_PATH_DATA_SIZE; k += 1) {
3461
- const at: i32 = from + k
3462
- if (base + k >= 0 && base + k < toI32(this.pathData.length) && at >= 0 && at < toI32(data.length)) {
3463
- this.pathData[base + k] = data[at]
3698
+ const count: i32 = this.pathCount
3699
+ // The ring holds 0 to 3 entries here, so this is never taken.
3700
+ if (count < 0 || count >= 4) {
3701
+ return
3702
+ }
3703
+ const base: i32 = quicConnRingAt(toI64(this.pathHead) + toI64(count), 4)
3704
+ const ring: u8[] = this.pathData
3705
+ for (let k: i32 = 0; base >= 0 && k < QUIC_PATH_DATA_SIZE; k += 1) {
3706
+ const to: i32 = quicConnAt(base, k, toI32(ring.length))
3707
+ const at: i32 = quicConnAt(from, k, toI32(data.length))
3708
+ if (to >= 0 && to < toI32(ring.length) && at >= 0 && at < toI32(data.length)) {
3709
+ ring[to] = data[at]
3464
3710
  }
3465
3711
  }
3466
- this.pathCount = this.pathCount + 1
3712
+ this.pathCount = count + 1
3467
3713
  }
3468
3714
 
3469
3715
  /**
@@ -3497,16 +3743,18 @@ export class QuicConnection {
3497
3743
  }
3498
3744
  let matched: boolean = false
3499
3745
  for (let m: i32 = 0; m < this.challengeCount; m += 1) {
3500
- const slot: i32 = toI32((this.challengesDrawn - 1 - toI64(m)) % toI64(QUIC_CONN_CHALLENGES))
3746
+ // At most `challengesDrawn` challenges are kept, so the index, taken
3747
+ // in `u64` where it is exact, is never negative.
3748
+ const base: i32 = quicConnRingAt(
3749
+ toI64(toU64(this.challengesDrawn) - toU64(1) - toU64(m)),
3750
+ QUIC_CONN_CHALLENGES
3751
+ )
3752
+ if (base < 0) {
3753
+ continue
3754
+ }
3501
3755
  // Not secret once sent, but compared without branching on the bytes all the same.
3502
3756
  matched =
3503
- timingSafeEqualAt(
3504
- payload,
3505
- frame.dataStart,
3506
- this.challengeData,
3507
- slot * QUIC_PATH_DATA_SIZE,
3508
- QUIC_PATH_DATA_SIZE
3509
- ) || matched
3757
+ timingSafeEqualAt(payload, frame.dataStart, this.challengeData, base, QUIC_PATH_DATA_SIZE) || matched
3510
3758
  }
3511
3759
  if (matched) {
3512
3760
  this.pathConfirmed()
@@ -3571,7 +3819,7 @@ export class QuicConnection {
3571
3819
  // suite's width and wiped in `TlsServer`, leaving one copy of each.
3572
3820
  const pool: TlsSecretPool = tls.secrets()
3573
3821
  const writeSlot: QuicKeysSlot = this.application.keySlot(
3574
- QUIC_CONN_APP_WRITE_SLOTS + this.appWriteSlot
3822
+ this.appWriteSlot === 0 ? QUIC_CONN_APP_WRITE_SLOTS : QUIC_CONN_APP_WRITE_SLOTS + 1
3575
3823
  )
3576
3824
  const readSlot: QuicKeysSlot = this.application.keySlot(this.appReadSlot)
3577
3825
  if (aead === QUIC_AEAD_AES_256_GCM) {
@@ -3797,7 +4045,8 @@ export class QuicConnection {
3797
4045
  if (timeout === 0) {
3798
4046
  return -1
3799
4047
  }
3800
- let floor: i64 = this.recovery.probeTimeout() * 3
4048
+ const probe: i64 = this.recovery.probeTimeout()
4049
+ let floor: i64 = quicConnSum(quicConnSum(probe, probe), probe)
3801
4050
  if (floor < QUIC_CONN_IDLE_FLOOR) {
3802
4051
  floor = QUIC_CONN_IDLE_FLOOR
3803
4052
  }
@@ -3811,7 +4060,8 @@ export class QuicConnection {
3811
4060
  */
3812
4061
  idleDeadline(): i64 {
3813
4062
  const timeout: i64 = this.idleTimeout()
3814
- return timeout >= 0 && this.idleSince >= 0 ? this.idleSince + timeout : -1
4063
+ const since: i64 = this.idleSince
4064
+ return timeout >= 0 && since >= 0 ? quicConnSum(since, timeout) : -1
3815
4065
  }
3816
4066
 
3817
4067
  /**
@@ -3867,7 +4117,8 @@ export class QuicConnection {
3867
4117
  */
3868
4118
  amplificationBlocked(): boolean {
3869
4119
  return (
3870
- (!this.addressValidated && this.bytesReceived * 3 - this.bytesSent < toI64(QUIC_CONN_DATAGRAM_SIZE)) ||
4120
+ (!this.addressValidated &&
4121
+ quicConnThrice(this.bytesReceived, this.bytesSent) < toI64(QUIC_CONN_DATAGRAM_SIZE)) ||
3871
4122
  this.pathBudget() < QUIC_CONN_PATH_MIN
3872
4123
  )
3873
4124
  }
@@ -3878,7 +4129,7 @@ export class QuicConnection {
3878
4129
  * (RFC 9000 §9.3.1, §8.1). Unlimited, as `QUIC_MAX_VARINT`, on a validated path.
3879
4130
  */
3880
4131
  private pathBudget(): i64 {
3881
- return this.pathValidating ? this.pathReceived * 3 - this.pathSent : QUIC_MAX_VARINT
4132
+ return this.pathValidating ? quicConnThrice(this.pathReceived, this.pathSent) : QUIC_MAX_VARINT
3882
4133
  }
3883
4134
 
3884
4135
  /**
@@ -4015,7 +4266,7 @@ export class QuicConnection {
4015
4266
  if (!this.migrateOwed) {
4016
4267
  if (this.probeStaged) {
4017
4268
  quicConnCopyAt(this.probeAddress, 0, this.pathArrival, 0, QUIC_CONN_ADDRESS_SIZE)
4018
- this.probeBudget = toI64(len) * 3
4269
+ this.probeBudget = quicConnThrice(toI64(len), 0)
4019
4270
  this.probeOwed = true
4020
4271
  }
4021
4272
  return
@@ -4026,7 +4277,7 @@ export class QuicConnection {
4026
4277
  }
4027
4278
  }
4028
4279
  if (this.pathValidating) {
4029
- this.pathReceived = this.pathReceived + toI64(len)
4280
+ this.pathReceived = quicConnSum(this.pathReceived, toI64(len))
4030
4281
  }
4031
4282
  }
4032
4283
 
@@ -4051,8 +4302,12 @@ export class QuicConnection {
4051
4302
  }
4052
4303
  this.endValidation()
4053
4304
  this.pathValidating = true
4054
- const span: i64 = this.recovery.probeTimeout() * 3
4055
- this.challengeUntil = this.now + (span > QUIC_CONN_VALIDATION_FLOOR ? span : QUIC_CONN_VALIDATION_FLOOR)
4305
+ const probe: i64 = this.recovery.probeTimeout()
4306
+ const span: i64 = quicConnSum(quicConnSum(probe, probe), probe)
4307
+ this.challengeUntil = quicConnSum(
4308
+ this.now,
4309
+ span > QUIC_CONN_VALIDATION_FLOOR ? span : QUIC_CONN_VALIDATION_FLOOR
4310
+ )
4056
4311
  this.drawChallenge()
4057
4312
  return swapped
4058
4313
  }
@@ -4076,12 +4331,22 @@ export class QuicConnection {
4076
4331
  this.pathCount = 0
4077
4332
  return false
4078
4333
  }
4079
- const base: i32 = ((this.pathHead + this.pathCount - 1) % 4) * QUIC_PATH_DATA_SIZE
4334
+ const base: i32 = quicConnRingAt(toI64(this.pathHead) + toI64(this.pathCount) - 1, 4)
4335
+ // The ring holds an entry here, so its base is never negative.
4336
+ if (base < 0) {
4337
+ this.pathCount = 0
4338
+ return false
4339
+ }
4080
4340
  const swapped: boolean = this.probeStaged
4341
+ const probe: u8[] = this.probeData
4342
+ const ring: u8[] = this.pathData
4081
4343
  for (let k: i32 = 0; k < QUIC_PATH_DATA_SIZE; k += 1) {
4082
- const kept: u8 = this.probeData[k]
4083
- this.probeData[k] = this.pathData[base + k]
4084
- this.pathData[base + k] = kept
4344
+ const to: i32 = quicConnAt(base, k, toI32(ring.length))
4345
+ if (k < toI32(probe.length) && to >= 0 && to < toI32(ring.length)) {
4346
+ const kept: u8 = probe[k]
4347
+ probe[k] = ring[to]
4348
+ ring[to] = kept
4349
+ }
4085
4350
  }
4086
4351
  this.pathHead = base / QUIC_PATH_DATA_SIZE
4087
4352
  this.pathCount = swapped ? 1 : 0
@@ -4089,7 +4354,7 @@ export class QuicConnection {
4089
4354
  if (!this.pathValidating) {
4090
4355
  this.probeBudget = toI64(QUIC_CONN_DATAGRAM_SIZE)
4091
4356
  } else {
4092
- const left: i64 = this.pathReceived * 3 - this.pathSent
4357
+ const left: i64 = quicConnThrice(this.pathReceived, this.pathSent)
4093
4358
  this.probeBudget = left > 0 ? left : 0
4094
4359
  }
4095
4360
  this.probeOwed = true
@@ -4103,16 +4368,20 @@ export class QuicConnection {
4103
4368
  * probe timeout later.
4104
4369
  */
4105
4370
  private drawChallenge(): void {
4106
- this.deriveConnectionId(QUIC_CONN_CHALLENGE_SEQUENCE + this.challengesDrawn)
4107
- const slot: i32 = toI32(this.challengesDrawn % toI64(QUIC_CONN_CHALLENGES))
4108
- quicConnCopyAt(this.challengeData, slot * QUIC_PATH_DATA_SIZE, this.cidScratch, 0, QUIC_PATH_DATA_SIZE)
4371
+ const drawn: i64 = this.challengesDrawn
4372
+ this.deriveConnectionId(quicConnSum(QUIC_CONN_CHALLENGE_SEQUENCE, drawn))
4373
+ const base: i32 = quicConnRingAt(drawn, QUIC_CONN_CHALLENGES)
4374
+ if (base >= 0) {
4375
+ quicConnCopyAt(this.challengeData, base, this.cidScratch, 0, QUIC_PATH_DATA_SIZE)
4376
+ }
4109
4377
  secureZero(this.cidScratch)
4110
- this.challengesDrawn = this.challengesDrawn + 1
4111
- if (this.challengeCount < QUIC_CONN_CHALLENGES) {
4112
- this.challengeCount = this.challengeCount + 1
4378
+ this.challengesDrawn = quicConnSum(drawn, 1)
4379
+ const count: i32 = this.challengeCount
4380
+ if (count < QUIC_CONN_CHALLENGES) {
4381
+ this.challengeCount = count + 1
4113
4382
  }
4114
4383
  this.challengeOwed = true
4115
- this.challengeResendAt = this.now + this.recovery.probeTimeout()
4384
+ this.challengeResendAt = quicConnSum(this.now, this.recovery.probeTimeout())
4116
4385
  }
4117
4386
 
4118
4387
  /**
@@ -4147,7 +4416,7 @@ export class QuicConnection {
4147
4416
  /** Adds `n` bytes sent to the path being validated's count. */
4148
4417
  private notePathSent(n: i32): void {
4149
4418
  if (this.pathValidating) {
4150
- this.pathSent = this.pathSent + toI64(n)
4419
+ this.pathSent = quicConnSum(this.pathSent, toI64(n))
4151
4420
  }
4152
4421
  }
4153
4422
 
@@ -4221,7 +4490,9 @@ export class QuicConnection {
4221
4490
  using _scope = arena()
4222
4491
  n = this.buildProbe(out, at, size)
4223
4492
  }
4224
- this.probeBudget = this.probeBudget - toI64(n)
4493
+ // Both are byte counts far from the ends of `i64`, so the `u64`
4494
+ // difference is exact.
4495
+ this.probeBudget = toI64(toU64(this.probeBudget) - toU64(n))
4225
4496
  return n
4226
4497
  }
4227
4498
 
@@ -4229,12 +4500,21 @@ export class QuicConnection {
4229
4500
  private buildProbe(out: u8[], at: i32, size: i32): i32 {
4230
4501
  const space: QuicConnSpace = this.application
4231
4502
  const overhead: i32 = this.overhead(space)
4232
- if (overhead === 0 || size < overhead + 1 + QUIC_PATH_DATA_SIZE) {
4503
+ if (overhead === 0 || toI64(size) < toI64(overhead) + toI64(1 + QUIC_PATH_DATA_SIZE)) {
4504
+ return 0
4505
+ }
4506
+ const start: i64 = toI64(at) + toI64(overhead) - toI64(QUIC_AEAD_TAG_SIZE)
4507
+ const end: i64 = toI64(at) + toI64(size) - toI64(QUIC_AEAD_TAG_SIZE)
4508
+ // Both lie inside `out`, which the caller sized, so these are never taken.
4509
+ if (start < 0 || end > toI64(out.length)) {
4510
+ return 0
4511
+ }
4512
+ if (end < start) {
4233
4513
  return 0
4234
4514
  }
4235
4515
  space.clearStaged()
4236
- const payloadStart: i32 = at + overhead - QUIC_AEAD_TAG_SIZE
4237
- const payloadEnd: i32 = at + size - QUIC_AEAD_TAG_SIZE
4516
+ const payloadStart: i32 = toI32(start)
4517
+ const payloadEnd: i32 = toI32(end)
4238
4518
  const next: i32 = quicPutPathData(
4239
4519
  out,
4240
4520
  payloadStart,
@@ -4246,7 +4526,7 @@ export class QuicConnection {
4246
4526
  if (next < 0) {
4247
4527
  return 0
4248
4528
  }
4249
- return this.sealAt(space, out, at, quicPutPadding(out, next, payloadEnd - next))
4529
+ return this.sealAt(space, out, at, quicPutPadding(out, next, toI32(toI64(payloadEnd) - toI64(next))))
4250
4530
  }
4251
4531
 
4252
4532
  /**
@@ -4288,7 +4568,10 @@ export class QuicConnection {
4288
4568
  return -1
4289
4569
  }
4290
4570
  const half: i64 = this.recovery.smoothedRtt / 2
4291
- return sent.lastAckEliciting + (half > QUIC_RECOVERY_GRANULARITY ? half : QUIC_RECOVERY_GRANULARITY)
4571
+ return quicConnSum(
4572
+ sent.lastAckEliciting,
4573
+ half > QUIC_RECOVERY_GRANULARITY ? half : QUIC_RECOVERY_GRANULARITY
4574
+ )
4292
4575
  }
4293
4576
 
4294
4577
  /** The early probe of `earlyProbeAt`, if it is due. */
@@ -4353,14 +4636,15 @@ export class QuicConnection {
4353
4636
  * cannot tell where the next will.
4354
4637
  */
4355
4638
  private scheduleSkip(from: i64): void {
4356
- this.deriveConnectionId(QUIC_CONN_SKIP_SEQUENCE + this.skipsDrawn)
4357
- this.skipsDrawn = this.skipsDrawn + 1
4639
+ const drawn: i64 = this.skipsDrawn
4640
+ this.deriveConnectionId(quicConnSum(QUIC_CONN_SKIP_SEQUENCE, drawn))
4641
+ this.skipsDrawn = quicConnSum(drawn, 1)
4358
4642
  let draw: i64 = 0
4359
4643
  for (let k: i32 = 0; k < 4 && k < toI32(this.cidScratch.length); k += 1) {
4360
4644
  draw = (draw << 8) | toI64(this.cidScratch[k])
4361
4645
  }
4362
4646
  secureZero(this.cidScratch)
4363
- this.nextSkip = from + QUIC_CONN_SKIP_MIN + (draw % QUIC_CONN_SKIP_SPREAD)
4647
+ this.nextSkip = quicConnSum(from, quicConnSum(QUIC_CONN_SKIP_MIN, draw % QUIC_CONN_SKIP_SPREAD))
4364
4648
  }
4365
4649
 
4366
4650
  // ---- Streams ------------------------------------------------------------------
@@ -4481,7 +4765,7 @@ export class QuicConnection {
4481
4765
  while (id >= 0) {
4482
4766
  const stream: QuicStream | null = this.streams.find(id)
4483
4767
  const available: i64 = stream !== null ? stream.readable() : 0
4484
- const data: u8[] = new Array<u8>(toI32(available))
4768
+ const data: u8[] = quicConnBytes(available)
4485
4769
  const n: i32 = this.streams.read(id, data, QUIC_CONN_FROM, toI32(available))
4486
4770
  // Every byte up to the FIN read: one more read sees the end, which lets the side finish.
4487
4771
  const end: boolean =
@@ -4524,8 +4808,8 @@ export class QuicConnection {
4524
4808
  }
4525
4809
  const length: i64 = toI64(toI32(data.length))
4526
4810
  if (
4527
- stream.sendEnd + length > stream.sendLimit ||
4528
- this.streams.writtenTotal + length > this.streams.sendMaxData ||
4811
+ quicConnSum(stream.sendEnd, length) > stream.sendLimit ||
4812
+ quicConnSum(this.streams.writtenTotal, length) > this.streams.sendMaxData ||
4529
4813
  length > stream.room()
4530
4814
  ) {
4531
4815
  return QUIC_STREAM_ERR_FLOW
@@ -4549,10 +4833,15 @@ export class QuicConnection {
4549
4833
  maxDatagramPayload(): i32 {
4550
4834
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
4551
4835
  const cid: i32 = entry !== null ? entry.length : QUIC_CONN_FROM
4552
- let limit: i64 = toI64(this.datagramSize() - 1 - cid - 4 - QUIC_AEAD_TAG_SIZE)
4836
+ let limit: i64 = toI64(this.datagramSize()) - toI64(cid) - toI64(QUIC_AEAD_TAG_SIZE + 1 + 4)
4553
4837
  if (this.peerMaxDatagramFrame < limit) {
4554
4838
  limit = this.peerMaxDatagramFrame
4555
4839
  }
4840
+ // A negative limit leaves no payload either way: below, every payload it
4841
+ // gives is negative, and so is answered as none.
4842
+ if (limit < 0) {
4843
+ limit = 0
4844
+ }
4556
4845
  // The frame is its type, a Length of 1, 2 or 4 bytes, and the payload.
4557
4846
  let payload: i64 = limit - 2
4558
4847
  if (payload > 63) {
@@ -4632,7 +4921,8 @@ export class QuicConnection {
4632
4921
  takeDatagram(now: i64): u8[] | null {
4633
4922
  const out: u8[] = new Array<u8>(QUIC_CONN_DATAGRAM_SIZE)
4634
4923
  const n: i32 = this.takeDatagramInto(out, QUIC_CONN_FROM, now)
4635
- return n > 0 ? quicConnSlice(out, 0, n) : null
4924
+ // `n` is a datagram's length, at most `out`'s `QUIC_CONN_DATAGRAM_SIZE` bytes, so it fits a `u16`.
4925
+ return n > 0 && n <= QUIC_CONN_DATAGRAM_SIZE ? quicConnSlice(out, 0, toU16(n)) : null
4636
4926
  }
4637
4927
 
4638
4928
  /**
@@ -4674,7 +4964,9 @@ export class QuicConnection {
4674
4964
  * @returns The datagram's length in bytes, at most what `out` holds from `at` and `datagramSize()`, or 0.
4675
4965
  */
4676
4966
  takeDatagramInto(out: u8[], at: i32, now: i64): i32 {
4677
- return this.takeDatagramWithin(out, at, toI32(out.length) - at, now)
4967
+ // A negative `at` is refused there whatever the room.
4968
+ const room: i32 = at < 0 ? 0 : toI32(out.length) - at
4969
+ return this.takeDatagramWithin(out, at, room, now)
4678
4970
  }
4679
4971
 
4680
4972
  /**
@@ -4702,7 +4994,7 @@ export class QuicConnection {
4702
4994
  this.state === QUIC_STATE_TIMED_OUT ||
4703
4995
  at < 0 ||
4704
4996
  room < QUIC_CONN_DATAGRAM_SIZE ||
4705
- at > toI32(out.length) - room
4997
+ toI64(at) > toI64(out.length) - toI64(room)
4706
4998
  ) {
4707
4999
  return 0
4708
5000
  }
@@ -4745,19 +5037,26 @@ export class QuicConnection {
4745
5037
  */
4746
5038
  private beforeDatagram(): void {
4747
5039
  const limit: i64 = this.confidentialityLimit
4748
- if (this.sealedUnderKey >= limit - limit / 4) {
5040
+ // The limit is a positive count far from the ends of `i64`, so the
5041
+ // `u64` difference is exact.
5042
+ if (this.sealedUnderKey >= toI64(toU64(limit) - toU64(limit / 4))) {
4749
5043
  this.updateKeys()
4750
5044
  }
4751
5045
  const pn: i64 = this.application.nextPn
4752
5046
  if (pn !== this.nextSkip) {
4753
5047
  return
4754
5048
  }
4755
- if (this.skipHead >= 0 && this.skipHead < toI32(this.skipped.length)) {
4756
- this.skipped[this.skipHead] = pn
5049
+ const head: i32 = this.skipHead
5050
+ const ring: i64[] = this.skipped
5051
+ if (head >= 0 && head < toI32(ring.length)) {
5052
+ ring[head] = pn
4757
5053
  }
4758
- this.skipHead = (this.skipHead + 1) % QUIC_CONN_SKIP_RING
4759
- this.application.nextPn = pn + 1
4760
- this.scheduleSkip(pn + 1)
5054
+ // The head stays in 0 .. QUIC_CONN_SKIP_RING - 1, so this is
5055
+ // `(head + 1) % QUIC_CONN_SKIP_RING`.
5056
+ this.skipHead = head >= 0 && head < QUIC_CONN_SKIP_RING - 1 ? head + 1 : 0
5057
+ const next: i64 = quicConnSum(pn, 1)
5058
+ this.application.nextPn = next
5059
+ this.scheduleSkip(next)
4761
5060
  }
4762
5061
 
4763
5062
  /**
@@ -4785,7 +5084,7 @@ export class QuicConnection {
4785
5084
  space.builtStart = -1
4786
5085
  const overhead: i32 = this.overhead(space)
4787
5086
  const sent: QuicSentPackets | null = this.recovery.space(level)
4788
- if (sent === null || overhead === 0 || remaining <= overhead + 8) {
5087
+ if (sent === null || overhead === 0 || toI64(remaining) <= toI64(overhead) + 8) {
4789
5088
  continue
4790
5089
  }
4791
5090
  if (space.probes > 0 && sent.full()) {
@@ -4797,13 +5096,14 @@ export class QuicConnection {
4797
5096
  }
4798
5097
  }
4799
5098
  const elicit: boolean = space.probes > 0 || (open && !sent.full())
4800
- const headerLength: i32 = overhead - QUIC_AEAD_TAG_SIZE
4801
- const payloadStart: i32 = position + headerLength
5099
+ // Every position here lies inside `out`, so each sum, taken in `i64`,
5100
+ // fits an `i32`.
5101
+ const payloadStart: i32 = toI32(toI64(position) + toI64(overhead) - toI64(QUIC_AEAD_TAG_SIZE))
4802
5102
  let payloadEnd: i32 = this.buildPayloadInto(
4803
5103
  space,
4804
5104
  out,
4805
5105
  payloadStart,
4806
- payloadStart + remaining - overhead,
5106
+ toI32(toI64(payloadStart) + toI64(remaining) - toI64(overhead)),
4807
5107
  elicit,
4808
5108
  !sent.full()
4809
5109
  )
@@ -4813,8 +5113,11 @@ export class QuicConnection {
4813
5113
  // RFC 9001 §5.4.2: the packet number and payload give header
4814
5114
  // protection at least four bytes to sample from.
4815
5115
  const pnLength: i32 = quicPacketNumberLength(space.nextPn, space.largestAcked)
4816
- if (pnLength + payloadEnd - payloadStart < 4) {
4817
- payloadEnd = quicPutPadding(out, payloadEnd, 4 - pnLength - (payloadEnd - payloadStart))
5116
+ const written: i64 = toI64(pnLength) + toI64(payloadEnd) - toI64(payloadStart)
5117
+ // The packet number is 1 to 4 bytes and the payload never shorter
5118
+ // than nothing, so `written` is never negative.
5119
+ if (written >= 0 && written < 4) {
5120
+ payloadEnd = quicPutPadding(out, payloadEnd, toI32(4 - written))
4818
5121
  }
4819
5122
  eliciting = eliciting || space.stagedEliciting
4820
5123
  // RFC 9000 §14.1: a datagram with an ack-eliciting Initial is padded.
@@ -4824,8 +5127,8 @@ export class QuicConnection {
4824
5127
  space.builtStart = position
4825
5128
  space.builtEnd = payloadEnd
4826
5129
  last = level
4827
- remaining = remaining - (payloadEnd + QUIC_AEAD_TAG_SIZE - position)
4828
- position = payloadEnd + QUIC_AEAD_TAG_SIZE
5130
+ remaining = toI32(toI64(remaining) + toI64(position) - toI64(payloadEnd) - toI64(QUIC_AEAD_TAG_SIZE))
5131
+ position = toI32(toI64(payloadEnd) + toI64(QUIC_AEAD_TAG_SIZE))
4829
5132
  }
4830
5133
  if (last < 0) {
4831
5134
  return 0
@@ -4845,18 +5148,19 @@ export class QuicConnection {
4845
5148
  // make cause, leaves the datagram unsendable: none of it goes.
4846
5149
  let total: i32 = 0
4847
5150
  let sealed: boolean = true
4848
- for (let level: i32 = 0; level <= last; level += 1) {
5151
+ for (let level: i32 = 0; level < 3 && level <= last; level += 1) {
4849
5152
  const space: QuicConnSpace = this.spaceAt(level)
4850
5153
  if (space.builtStart >= 0) {
4851
5154
  const n: i32 = this.sealAt(space, out, space.builtStart, space.builtEnd)
4852
5155
  sealed = sealed && n > 0
4853
- total = total + n
5156
+ // A datagram's packets together fit `out`, so this fits an `i32`.
5157
+ total = toI32(toI64(total) + toI64(n))
4854
5158
  }
4855
5159
  }
4856
5160
  if (!sealed) {
4857
5161
  return 0
4858
5162
  }
4859
- this.bytesSent = this.bytesSent + toI64(total)
5163
+ this.bytesSent = quicConnSum(this.bytesSent, toI64(total))
4860
5164
  this.notePathSent(total)
4861
5165
  return total
4862
5166
  }
@@ -4877,12 +5181,15 @@ export class QuicConnection {
4877
5181
  if (space.level === TLS_LEVEL_APPLICATION) {
4878
5182
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
4879
5183
  const cid: i32 = entry !== null ? entry.length : QUIC_CONN_FROM
4880
- return 1 + cid + pnLength + QUIC_AEAD_TAG_SIZE
5184
+ // An ID is at most 20 bytes and a packet number 4, so this fits an `i32`.
5185
+ return toI32(toI64(cid) + toI64(pnLength) + toI64(1 + QUIC_AEAD_TAG_SIZE))
4881
5186
  }
4882
5187
  // First byte, version, both IDs with their lengths, the Length (two
4883
5188
  // bytes, always) and, for an Initial, the empty token's length.
4884
5189
  const token: i32 = space.level === TLS_LEVEL_INITIAL ? 1 : 0
4885
- return 7 + this.peerScidLength + QUIC_CONN_CID_LENGTH + token + 2 + pnLength + QUIC_AEAD_TAG_SIZE
5190
+ // Each part is a few bytes, so the sum fits an `i32`.
5191
+ const fixed: i64 = toI64(7 + QUIC_CONN_CID_LENGTH + 2 + QUIC_AEAD_TAG_SIZE)
5192
+ return toI32(fixed + toI64(this.peerScidLength) + toI64(token) + toI64(pnLength))
4886
5193
  }
4887
5194
 
4888
5195
  /**
@@ -4937,10 +5244,16 @@ export class QuicConnection {
4937
5244
  * is kept whole, so a byte's index in `cryptoOut` is its offset.
4938
5245
  */
4939
5246
  private buildCrypto(space: QuicConnSpace, out: u8[], at: i32, end: i32): i32 {
4940
- if (space.cryptoResendLow >= 0) {
4941
- const low: i64 = space.cryptoResendLow
4942
- const want: i32 = toI32(space.cryptoResendHigh - low)
4943
- const left: i32 = end - at - quicCryptoOverhead(low, want)
5247
+ const low: i64 = space.cryptoResendLow
5248
+ if (low >= 0) {
5249
+ const high: i64 = space.cryptoResendHigh
5250
+ // A resend range is never empty while it is kept, so this is never taken.
5251
+ if (high < low) {
5252
+ return at
5253
+ }
5254
+ // `high` is at least `low`, so the `u64` difference is exact.
5255
+ const want: i32 = toI32(toI64(toU64(high) - toU64(low)))
5256
+ const left: i32 = toI32(toI64(end) - toI64(at) - toI64(quicCryptoOverhead(low, want)))
4944
5257
  const n: i32 = left < want ? left : want
4945
5258
  if (n <= 0) {
4946
5259
  return at
@@ -4950,7 +5263,7 @@ export class QuicConnection {
4950
5263
  return at
4951
5264
  }
4952
5265
  space.stageCrypto(low, n)
4953
- space.cryptoResendLow = low + toI64(n)
5266
+ space.cryptoResendLow = quicConnSum(low, toI64(n))
4954
5267
  if (space.cryptoResendLow >= space.cryptoResendHigh) {
4955
5268
  space.cryptoResendLow = -1
4956
5269
  space.cryptoResendHigh = -1
@@ -4961,7 +5274,7 @@ export class QuicConnection {
4961
5274
  if (unsent <= 0) {
4962
5275
  return at
4963
5276
  }
4964
- const left: i32 = end - at - quicCryptoOverhead(space.cryptoOutOffset, unsent)
5277
+ const left: i32 = toI32(toI64(end) - toI64(at) - toI64(quicCryptoOverhead(space.cryptoOutOffset, unsent)))
4965
5278
  const n: i32 = left < unsent ? left : unsent
4966
5279
  if (n <= 0) {
4967
5280
  return at
@@ -4979,8 +5292,9 @@ export class QuicConnection {
4979
5292
  return at
4980
5293
  }
4981
5294
  space.stageCrypto(space.cryptoOutOffset, n)
4982
- space.cryptoOutHead = space.cryptoOutHead + n
4983
- space.cryptoOutOffset = space.cryptoOutOffset + toI64(n)
5295
+ // The head moves within `cryptoOut`, so the sum fits an `i32`.
5296
+ space.cryptoOutHead = toI32(toI64(space.cryptoOutHead) + toI64(n))
5297
+ space.cryptoOutOffset = quicConnSum(space.cryptoOutOffset, toI64(n))
4984
5298
  return next
4985
5299
  }
4986
5300
 
@@ -4994,37 +5308,34 @@ export class QuicConnection {
4994
5308
  */
4995
5309
  private buildPathFrames(space: QuicConnSpace, out: u8[], start: i32, end: i32): i32 {
4996
5310
  let at: i32 = start
4997
- while (this.pathCount > 0 && end - at >= 9) {
4998
- const next: i32 = quicPutPathData(
4999
- out,
5000
- at,
5001
- end,
5002
- QUIC_FRAME_PATH_RESPONSE,
5003
- this.pathData,
5004
- (this.pathHead % 4) * QUIC_PATH_DATA_SIZE
5005
- )
5311
+ while (this.pathCount > 0 && toI64(end) - toI64(at) >= 9) {
5312
+ const head: i32 = this.pathHead
5313
+ const base: i32 = quicConnRingAt(toI64(head), 4)
5314
+ // The head stays in 0 .. 3, so this is never taken.
5315
+ if (base < 0) {
5316
+ break
5317
+ }
5318
+ const next: i32 = quicPutPathData(out, at, end, QUIC_FRAME_PATH_RESPONSE, this.pathData, base)
5006
5319
  if (next < 0) {
5007
5320
  break
5008
5321
  }
5009
5322
  at = next
5010
- this.pathHead = (this.pathHead + 1) % 4
5011
- this.pathCount = this.pathCount - 1
5323
+ // `(head + 1) % 4`, the head being in 0 .. 3.
5324
+ this.pathHead = head < 3 ? head + 1 : 0
5325
+ const count: i32 = this.pathCount
5326
+ this.pathCount = count > 0 ? count - 1 : 0
5012
5327
  // Ack-eliciting, but never sent again (RFC 9000 §13.3).
5013
5328
  space.stagedEliciting = true
5014
5329
  this.pathFrameStaged = true
5015
5330
  }
5016
5331
  // The PATH_CHALLENGE on a path being validated; one lost is not sent
5017
5332
  // again, but `runPathClock` draws fresh data a probe timeout later.
5018
- if (this.challengeOwed && this.challengesDrawn > 0 && end - at >= 9) {
5019
- const slot: i32 = toI32((this.challengesDrawn - 1) % toI64(QUIC_CONN_CHALLENGES))
5020
- const next: i32 = quicPutPathData(
5021
- out,
5022
- at,
5023
- end,
5024
- QUIC_FRAME_PATH_CHALLENGE,
5025
- this.challengeData,
5026
- slot * QUIC_PATH_DATA_SIZE
5027
- )
5333
+ const drawn: i64 = this.challengesDrawn
5334
+ if (this.challengeOwed && drawn > 0 && toI64(end) - toI64(at) >= 9) {
5335
+ const base: i32 = quicConnRingAt(drawn - 1, QUIC_CONN_CHALLENGES)
5336
+ // `drawn` is positive, so `base` is never negative.
5337
+ const next: i32 =
5338
+ base >= 0 ? quicPutPathData(out, at, end, QUIC_FRAME_PATH_CHALLENGE, this.challengeData, base) : -1
5028
5339
  if (next >= 0) {
5029
5340
  at = next
5030
5341
  this.challengeOwed = false
@@ -5052,7 +5363,7 @@ export class QuicConnection {
5052
5363
  // 8-byte ID at most 42.
5053
5364
  while (
5054
5365
  this.cids.retireCount > 0 &&
5055
- end - at >= 9 &&
5366
+ toI64(end) - toI64(at) >= 9 &&
5056
5367
  space.controlCount(space.staging) < QUIC_CONN_PACKET_CONTROL
5057
5368
  ) {
5058
5369
  const sequence: i64 = this.cids.takeRetire()
@@ -5060,7 +5371,11 @@ export class QuicConnection {
5060
5371
  space.stageControl(QUIC_CONN_CONTROL_RETIRE, sequence)
5061
5372
  }
5062
5373
  let entry: QuicCidEntry | null = this.cids.nextUnannounced()
5063
- while (entry !== null && end - at >= 42 && space.controlCount(space.staging) < QUIC_CONN_PACKET_CONTROL) {
5374
+ while (
5375
+ entry !== null &&
5376
+ toI64(end) - toI64(at) >= 42 &&
5377
+ space.controlCount(space.staging) < QUIC_CONN_PACKET_CONTROL
5378
+ ) {
5064
5379
  const next: i32 = quicPutNewConnectionId(
5065
5380
  out,
5066
5381
  at,
@@ -5153,8 +5468,10 @@ export class QuicConnection {
5153
5468
  const keys: QuicKeys | null = space.writeKeys
5154
5469
  const pn: i64 = space.nextPn
5155
5470
  const pnLength: i32 = quicPacketNumberLength(pn, space.largestAcked)
5156
- const headerLength: i32 = this.overhead(space) - QUIC_AEAD_TAG_SIZE
5157
- const payloadLength: i32 = payloadEnd - start - headerLength
5471
+ // Positions inside `out` and a header of a few bytes: each sum, taken
5472
+ // in `i64`, fits an `i32`.
5473
+ const headerLength: i32 = toI32(toI64(this.overhead(space)) - toI64(QUIC_AEAD_TAG_SIZE))
5474
+ const payloadLength: i32 = toI32(toI64(payloadEnd) - toI64(start) - toI64(headerLength))
5158
5475
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
5159
5476
  const headerEnd: i32 =
5160
5477
  space.level === TLS_LEVEL_APPLICATION
@@ -5181,25 +5498,26 @@ export class QuicConnection {
5181
5498
  pnLength,
5182
5499
  payloadLength
5183
5500
  )
5184
- if (keys === null || headerEnd !== start + headerLength) {
5501
+ if (keys === null || toI64(headerEnd) !== toI64(start) + toI64(headerLength)) {
5185
5502
  return 0
5186
5503
  }
5187
5504
  const end: i32 = quicSealInPlace(keys, out, start, headerLength, payloadLength, pn)
5188
5505
  if (end < 0) {
5189
5506
  return 0
5190
5507
  }
5191
- space.nextPn = pn + 1
5508
+ space.nextPn = quicConnSum(pn, 1)
5192
5509
  if (space.level === TLS_LEVEL_APPLICATION) {
5193
- this.sealedUnderKey = this.sealedUnderKey + 1
5510
+ this.sealedUnderKey = quicConnSum(this.sealedUnderKey, 1)
5194
5511
  }
5195
- const slot: i32 = this.recordSent(space, pn, end - start)
5512
+ const size: i32 = toI32(toI64(end) - toI64(start))
5513
+ const slot: i32 = this.recordSent(space, pn, size)
5196
5514
  if (this.pmtuSealing) {
5197
5515
  this.recovery.onProbeSent(space.level, slot)
5198
5516
  }
5199
5517
  if (this.datagramEcn !== 0) {
5200
5518
  this.recovery.onEctSent(space.level, slot)
5201
5519
  }
5202
- return end - start
5520
+ return size
5203
5521
  }
5204
5522
 
5205
5523
  /**
@@ -5218,8 +5536,9 @@ export class QuicConnection {
5218
5536
  const slot: i32 = this.recovery.onPacketSent(space.level, pn, size, this.now)
5219
5537
  if (slot >= 0) {
5220
5538
  space.commitStaged(slot)
5221
- if (space.probes > 0) {
5222
- space.probes -= 1
5539
+ const probes: i32 = space.probes
5540
+ if (probes > 0) {
5541
+ space.probes = probes - 1
5223
5542
  // §6.2.4: a second probe carries unacknowledged data too. When the
5224
5543
  // first took everything queued, the oldest — what it just carried —
5225
5544
  // goes again.
@@ -5238,7 +5557,7 @@ export class QuicConnection {
5238
5557
  private untrack(space: QuicConnSpace, row: i32): void {
5239
5558
  const streams: i32 = space.streamCount(row)
5240
5559
  for (let j: i32 = 0; j < streams; j += 1) {
5241
- const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
5560
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_STREAMS, toI32(space.sentStreamId.length))
5242
5561
  if (
5243
5562
  at >= 0 &&
5244
5563
  at < toI32(space.sentStreamId.length) &&
@@ -5256,7 +5575,7 @@ export class QuicConnection {
5256
5575
  }
5257
5576
  const control: i32 = space.controlCount(row)
5258
5577
  for (let j: i32 = 0; j < control; j += 1) {
5259
- const at: i32 = row * QUIC_CONN_PACKET_CONTROL + j
5578
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_CONTROL, toI32(space.sentControlKind.length))
5260
5579
  if (at >= 0 && at < toI32(space.sentControlKind.length) && at < toI32(space.sentControlValue.length)) {
5261
5580
  this.streams.controlAcked(toI32(space.sentControlKind[at]), space.sentControlValue[at])
5262
5581
  }
@@ -5279,7 +5598,10 @@ export class QuicConnection {
5279
5598
  this.closeSent = true
5280
5599
  this.startClosingPeriod()
5281
5600
  let position: i32 = at
5282
- const limit: i32 = at + QUIC_CONN_DATAGRAM_SIZE
5601
+ // `takeDatagramWithin` checked `out` holds a whole datagram from `at`,
5602
+ // so every position here lies inside it and each sum, taken in `i64`,
5603
+ // fits an `i32`.
5604
+ const limit: i32 = toI32(toI64(at) + toI64(QUIC_CONN_DATAGRAM_SIZE))
5283
5605
  for (let level: i32 = 0; level < 3; level += 1) {
5284
5606
  const space: QuicConnSpace = this.spaceAt(level)
5285
5607
  const overhead: i32 = this.overhead(space)
@@ -5287,8 +5609,8 @@ export class QuicConnection {
5287
5609
  continue
5288
5610
  }
5289
5611
  space.clearStaged()
5290
- const payloadStart: i32 = position + overhead - QUIC_AEAD_TAG_SIZE
5291
- const room: i32 = limit - QUIC_AEAD_TAG_SIZE
5612
+ const payloadStart: i32 = toI32(toI64(position) + toI64(overhead) - toI64(QUIC_AEAD_TAG_SIZE))
5613
+ const room: i32 = toI32(toI64(limit) - toI64(QUIC_AEAD_TAG_SIZE))
5292
5614
  let payloadEnd: i32 =
5293
5615
  level === TLS_LEVEL_APPLICATION || !this.errorIsApplication
5294
5616
  ? quicPutConnectionClose(
@@ -5313,14 +5635,18 @@ export class QuicConnection {
5313
5635
  continue
5314
5636
  }
5315
5637
  const pnLength: i32 = quicPacketNumberLength(space.nextPn, space.largestAcked)
5316
- if (pnLength + payloadEnd - payloadStart < 4) {
5317
- payloadEnd = quicPutPadding(out, payloadEnd, 4 - pnLength - (payloadEnd - payloadStart))
5638
+ const written: i64 = toI64(pnLength) + toI64(payloadEnd) - toI64(payloadStart)
5639
+ // The packet number is 1 to 4 bytes and the payload never shorter
5640
+ // than nothing, so `written` is never negative.
5641
+ if (written >= 0 && written < 4) {
5642
+ payloadEnd = quicPutPadding(out, payloadEnd, toI32(4 - written))
5318
5643
  }
5319
- position = position + this.sealAt(space, out, position, payloadEnd)
5644
+ position = toI32(toI64(position) + toI64(this.sealAt(space, out, position, payloadEnd)))
5320
5645
  }
5321
- this.bytesSent = this.bytesSent + toI64(position - at)
5322
- this.notePathSent(position - at)
5323
- return position - at
5646
+ const sent: i32 = toI32(toI64(position) - toI64(at))
5647
+ this.bytesSent = quicConnSum(this.bytesSent, toI64(sent))
5648
+ this.notePathSent(sent)
5649
+ return sent
5324
5650
  }
5325
5651
 
5326
5652
  /**