@amritk/nish-x86_64-linux 0.44.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 (111) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +18 -16
  3. package/package.json +1 -1
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +8 -0
  7. package/runtime/core.mjs +16 -0
  8. package/runtime/nish.d.ts +47 -5
  9. package/runtime/nish.mjs +4 -0
  10. package/std/README.md +3 -3
  11. package/std/array.ts +10 -2
  12. package/std/bytes.ts +239 -26
  13. package/std/cli-args.ts +1072 -606
  14. package/std/cli-flags.ts +180 -98
  15. package/std/cli.ts +21 -13
  16. package/std/collections.ts +245 -127
  17. package/std/compress/checksum.ts +32 -37
  18. package/std/compress/deflate.ts +1102 -542
  19. package/std/compress/gzip.ts +290 -145
  20. package/std/compress/zlib.ts +57 -21
  21. package/std/crypto/aes.ts +153 -75
  22. package/std/crypto/base64url.ts +84 -61
  23. package/std/crypto/bcrypt-batch.ts +164 -90
  24. package/std/crypto/bcrypt.ts +185 -107
  25. package/std/crypto/chacha20poly1305.ts +84 -68
  26. package/std/crypto/ct.ts +9 -7
  27. package/std/crypto/ed25519.ts +64 -27
  28. package/std/crypto/hkdf.ts +105 -63
  29. package/std/crypto/hmac.ts +95 -89
  30. package/std/crypto/jwt.ts +248 -126
  31. package/std/crypto/p256.ts +758 -444
  32. package/std/crypto/p384.ts +20 -13
  33. package/std/crypto/pki-roots.ts +95 -38
  34. package/std/crypto/pki.ts +164 -60
  35. package/std/crypto/rsa.ts +266 -223
  36. package/std/crypto/scram.ts +3 -4
  37. package/std/crypto/sha1.ts +107 -65
  38. package/std/crypto/sha256.ts +502 -422
  39. package/std/crypto/sha512.ts +204 -135
  40. package/std/crypto/x509-random.ts +9 -3
  41. package/std/crypto/x509.ts +331 -171
  42. package/std/json-equal.ts +35 -19
  43. package/std/json-format.ts +215 -108
  44. package/std/json-number.ts +126 -72
  45. package/std/json-pointer.ts +42 -13
  46. package/std/json-tokenizer.ts +498 -307
  47. package/std/json-typed.ts +115 -36
  48. package/std/json-value.ts +341 -152
  49. package/std/json.ts +300 -158
  50. package/std/net/buffer-pool.ts +17 -7
  51. package/std/net/dns-config.ts +427 -236
  52. package/std/net/dns-message.ts +114 -47
  53. package/std/net/dns-resolver.ts +736 -237
  54. package/std/net/dns.ts +205 -52
  55. package/std/net/fetch.ts +320 -184
  56. package/std/net/grpc.ts +948 -0
  57. package/std/net/handler.ts +1275 -217
  58. package/std/net/hpack.ts +395 -180
  59. package/std/net/http-compress.ts +502 -65
  60. package/std/net/http-fields.ts +85 -49
  61. package/std/net/http-server.ts +1764 -602
  62. package/std/net/http1-client-codec.ts +372 -161
  63. package/std/net/http1-codec.ts +665 -331
  64. package/std/net/http1-server.ts +660 -278
  65. package/std/net/http2-cleartext.ts +165 -95
  66. package/std/net/http2-frame.ts +232 -89
  67. package/std/net/http2-tls.ts +42 -12
  68. package/std/net/http2.ts +327 -101
  69. package/std/net/http3-frame.ts +68 -33
  70. package/std/net/http3-server.ts +647 -192
  71. package/std/net/http3.ts +667 -189
  72. package/std/net/oidc.ts +63 -24
  73. package/std/net/outbound.ts +207 -142
  74. package/std/net/postgres-async.ts +1165 -443
  75. package/std/net/postgres-carrier.ts +575 -372
  76. package/std/net/postgres.ts +1459 -559
  77. package/std/net/prefork.ts +254 -98
  78. package/std/net/protobuf.ts +1017 -0
  79. package/std/net/qpack.ts +143 -92
  80. package/std/net/quic-conn-ack.ts +50 -18
  81. package/std/net/quic-conn-cid.ts +66 -26
  82. package/std/net/quic-conn-params.ts +13 -7
  83. package/std/net/quic-datagram.ts +90 -27
  84. package/std/net/quic-frame.ts +225 -124
  85. package/std/net/quic-listener.ts +197 -89
  86. package/std/net/quic-packet.ts +289 -163
  87. package/std/net/quic-recovery.ts +279 -128
  88. package/std/net/quic-stream.ts +466 -167
  89. package/std/net/quic.ts +568 -257
  90. package/std/net/router.ts +450 -99
  91. package/std/net/serve.ts +651 -232
  92. package/std/net/static.ts +1458 -0
  93. package/std/net/tls/client.ts +140 -45
  94. package/std/net/tls/codec.ts +510 -260
  95. package/std/net/tls/record-client.ts +268 -76
  96. package/std/net/tls/record-server.ts +236 -79
  97. package/std/net/tls/record.ts +173 -47
  98. package/std/net/tls/schedule.ts +58 -39
  99. package/std/net/tls/ticket.ts +295 -103
  100. package/std/net/tls/verify.ts +1 -1
  101. package/std/net/tls-tcp.ts +218 -75
  102. package/std/net/tls.ts +260 -152
  103. package/std/net/upstream.ts +283 -86
  104. package/std/net/url.ts +277 -102
  105. package/std/net/websocket.ts +370 -186
  106. package/std/net/webtransport.ts +755 -436
  107. package/std/regex.ts +1659 -829
  108. package/std/sync/ring.ts +320 -156
  109. package/std/sync/shm.ts +53 -6
  110. package/std/text.ts +205 -124
  111. 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))
1251
1320
  }
1252
1321
  }
1253
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
1330
+ }
1331
+ const at: i64 = toI64(row) * toI64(per) + toI64(j)
1332
+ return at < toI64(length) ? toI32(at) : -1
1333
+ }
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
@@ -1860,14 +2031,14 @@ export class QuicConnection {
1860
2031
  datagrams,
1861
2032
  fits ? toI32(config.maxDatagramFrameSize) : QUIC_CONN_FROM
1862
2033
  )
1863
- this.cryptoIn = new QuicConnReassembly(QUIC_CONN_CRYPTO_WINDOW)
1864
- 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))
1865
2036
  this.pathCurrent = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1866
2037
  this.pathValidated = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1867
2038
  this.pathArrival = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1868
2039
  this.probeAddress = new Array<u8>(QUIC_CONN_ADDRESS_SIZE)
1869
2040
  this.probeData = new Array<u8>(QUIC_PATH_DATA_SIZE)
1870
- 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))
1871
2042
  this.frame = new QuicFrame()
1872
2043
  this.header = new QuicHeader()
1873
2044
  this.packet = new QuicPacket()
@@ -2008,8 +2179,9 @@ export class QuicConnection {
2008
2179
 
2009
2180
  /** Counts a dropped packet; the count stops at the largest `i32` rather than overflow. */
2010
2181
  private drop(): void {
2011
- if (this.dropped < 2147483647) {
2012
- this.dropped += 1
2182
+ const n: i32 = this.dropped
2183
+ if (n < 2147483647) {
2184
+ this.dropped = n + 1
2013
2185
  }
2014
2186
  }
2015
2187
 
@@ -2097,7 +2269,8 @@ export class QuicConnection {
2097
2269
  * keep them.
2098
2270
  */
2099
2271
  private startClosingPeriod(): void {
2100
- 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))
2101
2274
  }
2102
2275
 
2103
2276
  /** The space of packets of `type`, or `null` for a 0-RTT or Retry packet. */
@@ -2218,7 +2391,9 @@ export class QuicConnection {
2218
2391
  this.drop()
2219
2392
  return 0
2220
2393
  }
2221
- 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))
2222
2397
  let at: i32 = off
2223
2398
  let counted: boolean = false
2224
2399
  while (at < end) {
@@ -2237,7 +2412,7 @@ export class QuicConnection {
2237
2412
  // A datagram counts toward the amplification limit once one of its packets
2238
2413
  // proves it is this connection's (RFC 9000 §8.1).
2239
2414
  if (counted) {
2240
- this.bytesReceived = this.bytesReceived + toI64(len)
2415
+ this.bytesReceived = quicConnSum(this.bytesReceived, toI64(len))
2241
2416
  }
2242
2417
  if (!this.closed()) {
2243
2418
  this.afterPath(counted, len)
@@ -2454,7 +2629,8 @@ export class QuicConnection {
2454
2629
  // connection's private pools, so the handshake, not the first 1-RTT
2455
2630
  // packet, pays for them.
2456
2631
  if (type === QUIC_PACKET_SHORT || type === QUIC_PACKET_ZERO_RTT) {
2457
- 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)))
2458
2634
  } else {
2459
2635
  this.streams.ownPools()
2460
2636
  }
@@ -2525,7 +2701,7 @@ export class QuicConnection {
2525
2701
  // reads nothing more. A first Initial that fails is not counted: the
2526
2702
  // connection is not started, and the next one starts afresh.
2527
2703
  if (!first) {
2528
- this.authFailures = this.authFailures + 1
2704
+ this.authFailures = quicConnSum(this.authFailures, 1)
2529
2705
  if (this.authFailures > this.integrityLimit) {
2530
2706
  this.fail(QUIC_ERROR_AEAD_LIMIT_REACHED, QUIC_CONN_NONE)
2531
2707
  }
@@ -2618,7 +2794,13 @@ export class QuicConnection {
2618
2794
  */
2619
2795
  private applyPhase(pn: i64): void {
2620
2796
  if (this.writePhase === this.readPhase) {
2621
- 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
2622
2804
  if (!this.updateWriteKeys()) {
2623
2805
  this.fail(QUIC_ERROR_INTERNAL, QUIC_CONN_NONE)
2624
2806
  return
@@ -2628,7 +2810,7 @@ export class QuicConnection {
2628
2810
  this.application.readKeys = this.otherReadKeys
2629
2811
  this.otherReadKeys = previous
2630
2812
  this.otherIsNext = false
2631
- this.appReadSlot = 1 - this.appReadSlot
2813
+ this.appReadSlot = this.appReadSlot === 0 ? 1 : 0
2632
2814
  // The next read secret becomes the current one, over the secret it
2633
2815
  // replaces, and is zeroed where it was. Both widths move: the one the
2634
2816
  // suite does not use holds zeros.
@@ -2639,7 +2821,7 @@ export class QuicConnection {
2639
2821
  this.readPhase = !this.readPhase
2640
2822
  this.readPhaseLowest = pn
2641
2823
  this.readPhaseHighest = pn
2642
- this.keyRetainUntil = this.now + this.recovery.probeTimeout()
2824
+ this.keyRetainUntil = quicConnSum(this.now, this.recovery.probeTimeout())
2643
2825
  }
2644
2826
 
2645
2827
  /**
@@ -2653,7 +2835,9 @@ export class QuicConnection {
2653
2835
  if (keys === null) {
2654
2836
  return false
2655
2837
  }
2656
- 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
+ )
2657
2841
  const next: QuicKeys | null =
2658
2842
  keys.aead === QUIC_AEAD_AES_256_GCM
2659
2843
  ? this.nextKeys(slot, keys, this.writeSecret384, this.writeSecret384)
@@ -2663,7 +2847,7 @@ export class QuicConnection {
2663
2847
  }
2664
2848
  quicConnWipePacketKey(keys)
2665
2849
  this.application.writeKeys = next
2666
- this.appWriteSlot = 1 - this.appWriteSlot
2850
+ this.appWriteSlot = this.appWriteSlot === 0 ? 1 : 0
2667
2851
  this.writePhase = !this.writePhase
2668
2852
  this.writePhaseFirst = this.application.nextPn
2669
2853
  this.sealedUnderKey = 0
@@ -2707,15 +2891,20 @@ export class QuicConnection {
2707
2891
  {
2708
2892
  using _scope = arena()
2709
2893
  const plain: u8[] = expose(current, tlsHeldClone)
2710
- const out: u8[] = new Array<u8>(plain.length)
2711
- made =
2712
- quicKeyUpdateSecretInto(this.kdf, keys.aead, plain, out) &&
2713
- quicKeysUpdateInto(this.kdf, slot, keys, out) !== null
2714
- if (made) {
2715
- 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)
2716
2906
  }
2717
2907
  secureZero(plain)
2718
- secureZero(out)
2719
2908
  }
2720
2909
  return made ? slot.keys : null
2721
2910
  }
@@ -2736,7 +2925,8 @@ export class QuicConnection {
2736
2925
  if (keys === null) {
2737
2926
  return
2738
2927
  }
2739
- 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)
2740
2930
  this.otherReadKeys =
2741
2931
  keys.aead === QUIC_AEAD_AES_256_GCM
2742
2932
  ? this.nextKeys(slot, keys, this.readSecret384, this.nextReadSecret384)
@@ -3002,8 +3192,13 @@ export class QuicConnection {
3002
3192
  const ranges: i64[] = frame.ackRanges
3003
3193
  for (let k: i32 = 0; k < toI32(this.skipped.length); k += 1) {
3004
3194
  const pn: i64 = this.skipped[k]
3005
- for (let r: i32 = 0; pn >= 0 && r < frame.ackRangeCount && r * 2 + 1 < toI32(ranges.length); r += 1) {
3006
- 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]) {
3007
3202
  return true
3008
3203
  }
3009
3204
  }
@@ -3132,7 +3327,7 @@ export class QuicConnection {
3132
3327
  this.application.probes === 0 &&
3133
3328
  sent !== null &&
3134
3329
  !sent.full() &&
3135
- this.recovery.bytesInFlight() + toI64(size) <= this.recovery.congestionWindow
3330
+ quicConnSum(this.recovery.bytesInFlight(), toI64(size)) <= this.recovery.congestionWindow
3136
3331
  )
3137
3332
  }
3138
3333
 
@@ -3144,12 +3339,22 @@ export class QuicConnection {
3144
3339
  private buildPmtuProbe(out: u8[], at: i32, size: i32): i32 {
3145
3340
  const space: QuicConnSpace = this.application
3146
3341
  const overhead: i32 = this.overhead(space)
3147
- 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) {
3148
3353
  return 0
3149
3354
  }
3150
3355
  space.clearStaged()
3151
- const payloadStart: i32 = at + overhead - QUIC_AEAD_TAG_SIZE
3152
- const payloadEnd: i32 = at + size - QUIC_AEAD_TAG_SIZE
3356
+ const payloadStart: i32 = toI32(start)
3357
+ const payloadEnd: i32 = toI32(end)
3153
3358
  const ping: i32 = quicPutTypeOnly(out, payloadStart, payloadEnd, QUIC_FRAME_PING)
3154
3359
  if (ping < 0) {
3155
3360
  return 0
@@ -3157,21 +3362,22 @@ export class QuicConnection {
3157
3362
  space.stagedEliciting = true
3158
3363
  const pn: i64 = space.nextPn
3159
3364
  this.pmtuSealing = true
3160
- 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))))
3161
3366
  this.pmtuSealing = false
3162
3367
  if (n <= 0) {
3163
3368
  return 0
3164
3369
  }
3165
3370
  this.pmtuProbeSize = n
3166
3371
  this.pmtuProbePn = pn
3167
- if (this.pmtuProbes < 2147483647) {
3168
- this.pmtuProbes = this.pmtuProbes + 1
3372
+ const pmtuProbes: i32 = this.pmtuProbes
3373
+ if (pmtuProbes < 2147483647) {
3374
+ this.pmtuProbes = pmtuProbes + 1
3169
3375
  }
3170
3376
  if (!this.elicitingSent) {
3171
3377
  this.idleSince = this.now
3172
3378
  this.elicitingSent = true
3173
3379
  }
3174
- this.bytesSent = this.bytesSent + toI64(n)
3380
+ this.bytesSent = quicConnSum(this.bytesSent, toI64(n))
3175
3381
  this.notePathSent(n)
3176
3382
  return n
3177
3383
  }
@@ -3203,15 +3409,18 @@ export class QuicConnection {
3203
3409
 
3204
3410
  /** The probe numbered `pn` was lost: after three of one size, the search goes on below it. */
3205
3411
  private pmtuProbeLost(pn: i64): void {
3206
- if (this.pmtuProbesLost < 2147483647) {
3207
- this.pmtuProbesLost = this.pmtuProbesLost + 1
3412
+ const pmtuProbesLost: i32 = this.pmtuProbesLost
3413
+ if (pmtuProbesLost < 2147483647) {
3414
+ this.pmtuProbesLost = pmtuProbesLost + 1
3208
3415
  }
3209
- if (this.pmtuProbeSize === 0 || pn !== this.pmtuProbePn) {
3416
+ const size: i32 = this.pmtuProbeSize
3417
+ if (size <= 0 || pn !== this.pmtuProbePn) {
3210
3418
  return
3211
3419
  }
3212
- const size: i32 = this.pmtuProbeSize
3213
3420
  this.pmtuProbeSize = 0
3214
- 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
3215
3424
  if (this.pmtuTries >= 3) {
3216
3425
  this.pmtuHigh = size - 1
3217
3426
  this.pmtuStep()
@@ -3224,19 +3433,26 @@ export class QuicConnection {
3224
3433
  * (RFC 8899 §4.3), and `pathMtu` falls back to 1200.
3225
3434
  */
3226
3435
  private pmtuLargeLost(): void {
3227
- this.pmtuSuspect = this.pmtuSuspect + 1
3228
- if (this.pmtuSuspect < 3 || this.pathMtu <= QUIC_CONN_DATAGRAM_SIZE) {
3229
- return
3436
+ const suspect: i32 = this.pmtuSuspect
3437
+ if (suspect < 2147483647) {
3438
+ this.pmtuSuspect = suspect + 1
3230
3439
  }
3231
3440
  const failed: i32 = this.pathMtu
3441
+ if (this.pmtuSuspect < 3) {
3442
+ return
3443
+ }
3444
+ if (failed <= QUIC_CONN_DATAGRAM_SIZE) {
3445
+ return
3446
+ }
3232
3447
  this.pathMtu = QUIC_CONN_DATAGRAM_SIZE
3233
3448
  this.recovery.setDatagramSize(toI64(QUIC_CONN_DATAGRAM_SIZE))
3234
3449
  this.pmtuSuspect = 0
3235
3450
  this.pmtuProbeSize = 0
3236
3451
  this.pmtuLow = QUIC_CONN_DATAGRAM_SIZE
3237
- this.pmtuHigh = failed - 1
3238
- if (this.pmtuBlackHoles < 2147483647) {
3239
- 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
3240
3456
  }
3241
3457
  this.pmtuStep()
3242
3458
  }
@@ -3244,7 +3460,15 @@ export class QuicConnection {
3244
3460
  /** The next size to try, halfway between the bounds, or 0 when they are within 16 bytes. */
3245
3461
  private pmtuStep(): void {
3246
3462
  this.pmtuTries = 0
3247
- 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)
3248
3472
  }
3249
3473
 
3250
3474
  /**
@@ -3261,7 +3485,7 @@ export class QuicConnection {
3261
3485
  }
3262
3486
  const streams: i32 = space.streamCount(row)
3263
3487
  for (let j: i32 = 0; j < streams; j += 1) {
3264
- const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
3488
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_STREAMS, toI32(space.sentStreamId.length))
3265
3489
  if (
3266
3490
  at >= 0 &&
3267
3491
  at < toI32(space.sentStreamId.length) &&
@@ -3279,7 +3503,7 @@ export class QuicConnection {
3279
3503
  }
3280
3504
  const control: i32 = space.controlCount(row)
3281
3505
  for (let j: i32 = 0; j < control; j += 1) {
3282
- const at: i32 = row * QUIC_CONN_PACKET_CONTROL + j
3506
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_CONTROL, toI32(space.sentControlKind.length))
3283
3507
  if (at >= 0 && at < toI32(space.sentControlKind.length) && at < toI32(space.sentControlValue.length)) {
3284
3508
  this.requeueControl(toI32(space.sentControlKind[at]), space.sentControlValue[at])
3285
3509
  }
@@ -3345,11 +3569,11 @@ export class QuicConnection {
3345
3569
  * datagram (`takeDatagramInto`).
3346
3570
  */
3347
3571
  private resendEarly(level: i32): void {
3348
- if (
3349
- this.earlyResends >= QUIC_CONN_EARLY_RESENDS ||
3350
- this.initial.probes > 0 ||
3351
- this.handshake.probes > 0
3352
- ) {
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) {
3353
3577
  return
3354
3578
  }
3355
3579
  const asked: QuicSentPackets | null = this.recovery.space(level)
@@ -3357,7 +3581,7 @@ export class QuicConnection {
3357
3581
  return
3358
3582
  }
3359
3583
  let queued: boolean = false
3360
- for (let at: i32 = level; at <= TLS_LEVEL_HANDSHAKE; at += 1) {
3584
+ for (let at: i32 = level; at < TLS_LEVEL_HANDSHAKE + 1; at += 1) {
3361
3585
  const space: QuicConnSpace = this.spaceAt(at)
3362
3586
  const sent: QuicSentPackets | null = this.recovery.space(at)
3363
3587
  if (sent === null || space.discarded || sent.inFlight === 0) {
@@ -3374,7 +3598,7 @@ export class QuicConnection {
3374
3598
  }
3375
3599
  }
3376
3600
  if (queued) {
3377
- this.earlyResends += 1
3601
+ this.earlyResends = resends + 1
3378
3602
  }
3379
3603
  }
3380
3604
 
@@ -3389,7 +3613,7 @@ export class QuicConnection {
3389
3613
  private receiveCrypto(space: QuicConnSpace, frame: QuicFrame, payload: u8[]): void {
3390
3614
  const reassembly: QuicConnReassembly = this.cryptoIn
3391
3615
  if (space.level < reassembly.level) {
3392
- if (frame.offset + toI64(frame.dataLength) > space.cryptoInDelivered) {
3616
+ if (quicConnSum(frame.offset, toI64(frame.dataLength)) > space.cryptoInDelivered) {
3393
3617
  this.fail(QUIC_ERROR_CRYPTO + QUIC_CONN_ALERT_UNEXPECTED, toI64(QUIC_FRAME_CRYPTO))
3394
3618
  }
3395
3619
  return
@@ -3444,7 +3668,7 @@ export class QuicConnection {
3444
3668
  * `readDatagram`, or is dropped when the ring is full.
3445
3669
  */
3446
3670
  private receiveDatagram(frame: QuicFrame, payload: u8[], frameStart: i32): void {
3447
- const size: i64 = toI64(frame.end - frameStart)
3671
+ const size: i64 = toI64(frame.end) - toI64(frameStart)
3448
3672
  if (this.config.maxDatagramFrameSize === 0 || size > this.config.maxDatagramFrameSize) {
3449
3673
  // `fin` is how the frame says it was 0x31, the type with a Length.
3450
3674
  this.fail(
@@ -3471,14 +3695,21 @@ export class QuicConnection {
3471
3695
  this.pathHead = 0
3472
3696
  this.pathCount = 0
3473
3697
  }
3474
- const base: i32 = ((this.pathHead + this.pathCount) % 4) * QUIC_PATH_DATA_SIZE
3475
- for (let k: i32 = 0; k < QUIC_PATH_DATA_SIZE; k += 1) {
3476
- const at: i32 = from + k
3477
- if (base + k >= 0 && base + k < toI32(this.pathData.length) && at >= 0 && at < toI32(data.length)) {
3478
- 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]
3479
3710
  }
3480
3711
  }
3481
- this.pathCount = this.pathCount + 1
3712
+ this.pathCount = count + 1
3482
3713
  }
3483
3714
 
3484
3715
  /**
@@ -3512,16 +3743,18 @@ export class QuicConnection {
3512
3743
  }
3513
3744
  let matched: boolean = false
3514
3745
  for (let m: i32 = 0; m < this.challengeCount; m += 1) {
3515
- 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
+ }
3516
3755
  // Not secret once sent, but compared without branching on the bytes all the same.
3517
3756
  matched =
3518
- timingSafeEqualAt(
3519
- payload,
3520
- frame.dataStart,
3521
- this.challengeData,
3522
- slot * QUIC_PATH_DATA_SIZE,
3523
- QUIC_PATH_DATA_SIZE
3524
- ) || matched
3757
+ timingSafeEqualAt(payload, frame.dataStart, this.challengeData, base, QUIC_PATH_DATA_SIZE) || matched
3525
3758
  }
3526
3759
  if (matched) {
3527
3760
  this.pathConfirmed()
@@ -3586,7 +3819,7 @@ export class QuicConnection {
3586
3819
  // suite's width and wiped in `TlsServer`, leaving one copy of each.
3587
3820
  const pool: TlsSecretPool = tls.secrets()
3588
3821
  const writeSlot: QuicKeysSlot = this.application.keySlot(
3589
- QUIC_CONN_APP_WRITE_SLOTS + this.appWriteSlot
3822
+ this.appWriteSlot === 0 ? QUIC_CONN_APP_WRITE_SLOTS : QUIC_CONN_APP_WRITE_SLOTS + 1
3590
3823
  )
3591
3824
  const readSlot: QuicKeysSlot = this.application.keySlot(this.appReadSlot)
3592
3825
  if (aead === QUIC_AEAD_AES_256_GCM) {
@@ -3812,7 +4045,8 @@ export class QuicConnection {
3812
4045
  if (timeout === 0) {
3813
4046
  return -1
3814
4047
  }
3815
- let floor: i64 = this.recovery.probeTimeout() * 3
4048
+ const probe: i64 = this.recovery.probeTimeout()
4049
+ let floor: i64 = quicConnSum(quicConnSum(probe, probe), probe)
3816
4050
  if (floor < QUIC_CONN_IDLE_FLOOR) {
3817
4051
  floor = QUIC_CONN_IDLE_FLOOR
3818
4052
  }
@@ -3826,7 +4060,8 @@ export class QuicConnection {
3826
4060
  */
3827
4061
  idleDeadline(): i64 {
3828
4062
  const timeout: i64 = this.idleTimeout()
3829
- 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
3830
4065
  }
3831
4066
 
3832
4067
  /**
@@ -3882,7 +4117,8 @@ export class QuicConnection {
3882
4117
  */
3883
4118
  amplificationBlocked(): boolean {
3884
4119
  return (
3885
- (!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)) ||
3886
4122
  this.pathBudget() < QUIC_CONN_PATH_MIN
3887
4123
  )
3888
4124
  }
@@ -3893,7 +4129,7 @@ export class QuicConnection {
3893
4129
  * (RFC 9000 §9.3.1, §8.1). Unlimited, as `QUIC_MAX_VARINT`, on a validated path.
3894
4130
  */
3895
4131
  private pathBudget(): i64 {
3896
- return this.pathValidating ? this.pathReceived * 3 - this.pathSent : QUIC_MAX_VARINT
4132
+ return this.pathValidating ? quicConnThrice(this.pathReceived, this.pathSent) : QUIC_MAX_VARINT
3897
4133
  }
3898
4134
 
3899
4135
  /**
@@ -4030,7 +4266,7 @@ export class QuicConnection {
4030
4266
  if (!this.migrateOwed) {
4031
4267
  if (this.probeStaged) {
4032
4268
  quicConnCopyAt(this.probeAddress, 0, this.pathArrival, 0, QUIC_CONN_ADDRESS_SIZE)
4033
- this.probeBudget = toI64(len) * 3
4269
+ this.probeBudget = quicConnThrice(toI64(len), 0)
4034
4270
  this.probeOwed = true
4035
4271
  }
4036
4272
  return
@@ -4041,7 +4277,7 @@ export class QuicConnection {
4041
4277
  }
4042
4278
  }
4043
4279
  if (this.pathValidating) {
4044
- this.pathReceived = this.pathReceived + toI64(len)
4280
+ this.pathReceived = quicConnSum(this.pathReceived, toI64(len))
4045
4281
  }
4046
4282
  }
4047
4283
 
@@ -4066,8 +4302,12 @@ export class QuicConnection {
4066
4302
  }
4067
4303
  this.endValidation()
4068
4304
  this.pathValidating = true
4069
- const span: i64 = this.recovery.probeTimeout() * 3
4070
- 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
+ )
4071
4311
  this.drawChallenge()
4072
4312
  return swapped
4073
4313
  }
@@ -4091,12 +4331,22 @@ export class QuicConnection {
4091
4331
  this.pathCount = 0
4092
4332
  return false
4093
4333
  }
4094
- 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
+ }
4095
4340
  const swapped: boolean = this.probeStaged
4341
+ const probe: u8[] = this.probeData
4342
+ const ring: u8[] = this.pathData
4096
4343
  for (let k: i32 = 0; k < QUIC_PATH_DATA_SIZE; k += 1) {
4097
- const kept: u8 = this.probeData[k]
4098
- this.probeData[k] = this.pathData[base + k]
4099
- 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
+ }
4100
4350
  }
4101
4351
  this.pathHead = base / QUIC_PATH_DATA_SIZE
4102
4352
  this.pathCount = swapped ? 1 : 0
@@ -4104,7 +4354,7 @@ export class QuicConnection {
4104
4354
  if (!this.pathValidating) {
4105
4355
  this.probeBudget = toI64(QUIC_CONN_DATAGRAM_SIZE)
4106
4356
  } else {
4107
- const left: i64 = this.pathReceived * 3 - this.pathSent
4357
+ const left: i64 = quicConnThrice(this.pathReceived, this.pathSent)
4108
4358
  this.probeBudget = left > 0 ? left : 0
4109
4359
  }
4110
4360
  this.probeOwed = true
@@ -4118,16 +4368,20 @@ export class QuicConnection {
4118
4368
  * probe timeout later.
4119
4369
  */
4120
4370
  private drawChallenge(): void {
4121
- this.deriveConnectionId(QUIC_CONN_CHALLENGE_SEQUENCE + this.challengesDrawn)
4122
- const slot: i32 = toI32(this.challengesDrawn % toI64(QUIC_CONN_CHALLENGES))
4123
- 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
+ }
4124
4377
  secureZero(this.cidScratch)
4125
- this.challengesDrawn = this.challengesDrawn + 1
4126
- if (this.challengeCount < QUIC_CONN_CHALLENGES) {
4127
- 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
4128
4382
  }
4129
4383
  this.challengeOwed = true
4130
- this.challengeResendAt = this.now + this.recovery.probeTimeout()
4384
+ this.challengeResendAt = quicConnSum(this.now, this.recovery.probeTimeout())
4131
4385
  }
4132
4386
 
4133
4387
  /**
@@ -4162,7 +4416,7 @@ export class QuicConnection {
4162
4416
  /** Adds `n` bytes sent to the path being validated's count. */
4163
4417
  private notePathSent(n: i32): void {
4164
4418
  if (this.pathValidating) {
4165
- this.pathSent = this.pathSent + toI64(n)
4419
+ this.pathSent = quicConnSum(this.pathSent, toI64(n))
4166
4420
  }
4167
4421
  }
4168
4422
 
@@ -4236,7 +4490,9 @@ export class QuicConnection {
4236
4490
  using _scope = arena()
4237
4491
  n = this.buildProbe(out, at, size)
4238
4492
  }
4239
- 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))
4240
4496
  return n
4241
4497
  }
4242
4498
 
@@ -4244,12 +4500,21 @@ export class QuicConnection {
4244
4500
  private buildProbe(out: u8[], at: i32, size: i32): i32 {
4245
4501
  const space: QuicConnSpace = this.application
4246
4502
  const overhead: i32 = this.overhead(space)
4247
- 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) {
4248
4513
  return 0
4249
4514
  }
4250
4515
  space.clearStaged()
4251
- const payloadStart: i32 = at + overhead - QUIC_AEAD_TAG_SIZE
4252
- const payloadEnd: i32 = at + size - QUIC_AEAD_TAG_SIZE
4516
+ const payloadStart: i32 = toI32(start)
4517
+ const payloadEnd: i32 = toI32(end)
4253
4518
  const next: i32 = quicPutPathData(
4254
4519
  out,
4255
4520
  payloadStart,
@@ -4261,7 +4526,7 @@ export class QuicConnection {
4261
4526
  if (next < 0) {
4262
4527
  return 0
4263
4528
  }
4264
- 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))))
4265
4530
  }
4266
4531
 
4267
4532
  /**
@@ -4303,7 +4568,10 @@ export class QuicConnection {
4303
4568
  return -1
4304
4569
  }
4305
4570
  const half: i64 = this.recovery.smoothedRtt / 2
4306
- 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
+ )
4307
4575
  }
4308
4576
 
4309
4577
  /** The early probe of `earlyProbeAt`, if it is due. */
@@ -4368,14 +4636,15 @@ export class QuicConnection {
4368
4636
  * cannot tell where the next will.
4369
4637
  */
4370
4638
  private scheduleSkip(from: i64): void {
4371
- this.deriveConnectionId(QUIC_CONN_SKIP_SEQUENCE + this.skipsDrawn)
4372
- 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)
4373
4642
  let draw: i64 = 0
4374
4643
  for (let k: i32 = 0; k < 4 && k < toI32(this.cidScratch.length); k += 1) {
4375
4644
  draw = (draw << 8) | toI64(this.cidScratch[k])
4376
4645
  }
4377
4646
  secureZero(this.cidScratch)
4378
- 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))
4379
4648
  }
4380
4649
 
4381
4650
  // ---- Streams ------------------------------------------------------------------
@@ -4496,7 +4765,7 @@ export class QuicConnection {
4496
4765
  while (id >= 0) {
4497
4766
  const stream: QuicStream | null = this.streams.find(id)
4498
4767
  const available: i64 = stream !== null ? stream.readable() : 0
4499
- const data: u8[] = new Array<u8>(toI32(available))
4768
+ const data: u8[] = quicConnBytes(available)
4500
4769
  const n: i32 = this.streams.read(id, data, QUIC_CONN_FROM, toI32(available))
4501
4770
  // Every byte up to the FIN read: one more read sees the end, which lets the side finish.
4502
4771
  const end: boolean =
@@ -4539,8 +4808,8 @@ export class QuicConnection {
4539
4808
  }
4540
4809
  const length: i64 = toI64(toI32(data.length))
4541
4810
  if (
4542
- stream.sendEnd + length > stream.sendLimit ||
4543
- this.streams.writtenTotal + length > this.streams.sendMaxData ||
4811
+ quicConnSum(stream.sendEnd, length) > stream.sendLimit ||
4812
+ quicConnSum(this.streams.writtenTotal, length) > this.streams.sendMaxData ||
4544
4813
  length > stream.room()
4545
4814
  ) {
4546
4815
  return QUIC_STREAM_ERR_FLOW
@@ -4564,10 +4833,15 @@ export class QuicConnection {
4564
4833
  maxDatagramPayload(): i32 {
4565
4834
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
4566
4835
  const cid: i32 = entry !== null ? entry.length : QUIC_CONN_FROM
4567
- 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)
4568
4837
  if (this.peerMaxDatagramFrame < limit) {
4569
4838
  limit = this.peerMaxDatagramFrame
4570
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
+ }
4571
4845
  // The frame is its type, a Length of 1, 2 or 4 bytes, and the payload.
4572
4846
  let payload: i64 = limit - 2
4573
4847
  if (payload > 63) {
@@ -4647,7 +4921,8 @@ export class QuicConnection {
4647
4921
  takeDatagram(now: i64): u8[] | null {
4648
4922
  const out: u8[] = new Array<u8>(QUIC_CONN_DATAGRAM_SIZE)
4649
4923
  const n: i32 = this.takeDatagramInto(out, QUIC_CONN_FROM, now)
4650
- 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
4651
4926
  }
4652
4927
 
4653
4928
  /**
@@ -4689,7 +4964,9 @@ export class QuicConnection {
4689
4964
  * @returns The datagram's length in bytes, at most what `out` holds from `at` and `datagramSize()`, or 0.
4690
4965
  */
4691
4966
  takeDatagramInto(out: u8[], at: i32, now: i64): i32 {
4692
- 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)
4693
4970
  }
4694
4971
 
4695
4972
  /**
@@ -4717,7 +4994,7 @@ export class QuicConnection {
4717
4994
  this.state === QUIC_STATE_TIMED_OUT ||
4718
4995
  at < 0 ||
4719
4996
  room < QUIC_CONN_DATAGRAM_SIZE ||
4720
- at > toI32(out.length) - room
4997
+ toI64(at) > toI64(out.length) - toI64(room)
4721
4998
  ) {
4722
4999
  return 0
4723
5000
  }
@@ -4760,19 +5037,26 @@ export class QuicConnection {
4760
5037
  */
4761
5038
  private beforeDatagram(): void {
4762
5039
  const limit: i64 = this.confidentialityLimit
4763
- 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))) {
4764
5043
  this.updateKeys()
4765
5044
  }
4766
5045
  const pn: i64 = this.application.nextPn
4767
5046
  if (pn !== this.nextSkip) {
4768
5047
  return
4769
5048
  }
4770
- if (this.skipHead >= 0 && this.skipHead < toI32(this.skipped.length)) {
4771
- 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
4772
5053
  }
4773
- this.skipHead = (this.skipHead + 1) % QUIC_CONN_SKIP_RING
4774
- this.application.nextPn = pn + 1
4775
- 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)
4776
5060
  }
4777
5061
 
4778
5062
  /**
@@ -4800,7 +5084,7 @@ export class QuicConnection {
4800
5084
  space.builtStart = -1
4801
5085
  const overhead: i32 = this.overhead(space)
4802
5086
  const sent: QuicSentPackets | null = this.recovery.space(level)
4803
- if (sent === null || overhead === 0 || remaining <= overhead + 8) {
5087
+ if (sent === null || overhead === 0 || toI64(remaining) <= toI64(overhead) + 8) {
4804
5088
  continue
4805
5089
  }
4806
5090
  if (space.probes > 0 && sent.full()) {
@@ -4812,13 +5096,14 @@ export class QuicConnection {
4812
5096
  }
4813
5097
  }
4814
5098
  const elicit: boolean = space.probes > 0 || (open && !sent.full())
4815
- const headerLength: i32 = overhead - QUIC_AEAD_TAG_SIZE
4816
- 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))
4817
5102
  let payloadEnd: i32 = this.buildPayloadInto(
4818
5103
  space,
4819
5104
  out,
4820
5105
  payloadStart,
4821
- payloadStart + remaining - overhead,
5106
+ toI32(toI64(payloadStart) + toI64(remaining) - toI64(overhead)),
4822
5107
  elicit,
4823
5108
  !sent.full()
4824
5109
  )
@@ -4828,8 +5113,11 @@ export class QuicConnection {
4828
5113
  // RFC 9001 §5.4.2: the packet number and payload give header
4829
5114
  // protection at least four bytes to sample from.
4830
5115
  const pnLength: i32 = quicPacketNumberLength(space.nextPn, space.largestAcked)
4831
- if (pnLength + payloadEnd - payloadStart < 4) {
4832
- 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))
4833
5121
  }
4834
5122
  eliciting = eliciting || space.stagedEliciting
4835
5123
  // RFC 9000 §14.1: a datagram with an ack-eliciting Initial is padded.
@@ -4839,8 +5127,8 @@ export class QuicConnection {
4839
5127
  space.builtStart = position
4840
5128
  space.builtEnd = payloadEnd
4841
5129
  last = level
4842
- remaining = remaining - (payloadEnd + QUIC_AEAD_TAG_SIZE - position)
4843
- 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))
4844
5132
  }
4845
5133
  if (last < 0) {
4846
5134
  return 0
@@ -4860,18 +5148,19 @@ export class QuicConnection {
4860
5148
  // make cause, leaves the datagram unsendable: none of it goes.
4861
5149
  let total: i32 = 0
4862
5150
  let sealed: boolean = true
4863
- for (let level: i32 = 0; level <= last; level += 1) {
5151
+ for (let level: i32 = 0; level < 3 && level <= last; level += 1) {
4864
5152
  const space: QuicConnSpace = this.spaceAt(level)
4865
5153
  if (space.builtStart >= 0) {
4866
5154
  const n: i32 = this.sealAt(space, out, space.builtStart, space.builtEnd)
4867
5155
  sealed = sealed && n > 0
4868
- total = total + n
5156
+ // A datagram's packets together fit `out`, so this fits an `i32`.
5157
+ total = toI32(toI64(total) + toI64(n))
4869
5158
  }
4870
5159
  }
4871
5160
  if (!sealed) {
4872
5161
  return 0
4873
5162
  }
4874
- this.bytesSent = this.bytesSent + toI64(total)
5163
+ this.bytesSent = quicConnSum(this.bytesSent, toI64(total))
4875
5164
  this.notePathSent(total)
4876
5165
  return total
4877
5166
  }
@@ -4892,12 +5181,15 @@ export class QuicConnection {
4892
5181
  if (space.level === TLS_LEVEL_APPLICATION) {
4893
5182
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
4894
5183
  const cid: i32 = entry !== null ? entry.length : QUIC_CONN_FROM
4895
- 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))
4896
5186
  }
4897
5187
  // First byte, version, both IDs with their lengths, the Length (two
4898
5188
  // bytes, always) and, for an Initial, the empty token's length.
4899
5189
  const token: i32 = space.level === TLS_LEVEL_INITIAL ? 1 : 0
4900
- 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))
4901
5193
  }
4902
5194
 
4903
5195
  /**
@@ -4952,10 +5244,16 @@ export class QuicConnection {
4952
5244
  * is kept whole, so a byte's index in `cryptoOut` is its offset.
4953
5245
  */
4954
5246
  private buildCrypto(space: QuicConnSpace, out: u8[], at: i32, end: i32): i32 {
4955
- if (space.cryptoResendLow >= 0) {
4956
- const low: i64 = space.cryptoResendLow
4957
- const want: i32 = toI32(space.cryptoResendHigh - low)
4958
- 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)))
4959
5257
  const n: i32 = left < want ? left : want
4960
5258
  if (n <= 0) {
4961
5259
  return at
@@ -4965,7 +5263,7 @@ export class QuicConnection {
4965
5263
  return at
4966
5264
  }
4967
5265
  space.stageCrypto(low, n)
4968
- space.cryptoResendLow = low + toI64(n)
5266
+ space.cryptoResendLow = quicConnSum(low, toI64(n))
4969
5267
  if (space.cryptoResendLow >= space.cryptoResendHigh) {
4970
5268
  space.cryptoResendLow = -1
4971
5269
  space.cryptoResendHigh = -1
@@ -4976,7 +5274,7 @@ export class QuicConnection {
4976
5274
  if (unsent <= 0) {
4977
5275
  return at
4978
5276
  }
4979
- const left: i32 = end - at - quicCryptoOverhead(space.cryptoOutOffset, unsent)
5277
+ const left: i32 = toI32(toI64(end) - toI64(at) - toI64(quicCryptoOverhead(space.cryptoOutOffset, unsent)))
4980
5278
  const n: i32 = left < unsent ? left : unsent
4981
5279
  if (n <= 0) {
4982
5280
  return at
@@ -4994,8 +5292,9 @@ export class QuicConnection {
4994
5292
  return at
4995
5293
  }
4996
5294
  space.stageCrypto(space.cryptoOutOffset, n)
4997
- space.cryptoOutHead = space.cryptoOutHead + n
4998
- 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))
4999
5298
  return next
5000
5299
  }
5001
5300
 
@@ -5009,37 +5308,34 @@ export class QuicConnection {
5009
5308
  */
5010
5309
  private buildPathFrames(space: QuicConnSpace, out: u8[], start: i32, end: i32): i32 {
5011
5310
  let at: i32 = start
5012
- while (this.pathCount > 0 && end - at >= 9) {
5013
- const next: i32 = quicPutPathData(
5014
- out,
5015
- at,
5016
- end,
5017
- QUIC_FRAME_PATH_RESPONSE,
5018
- this.pathData,
5019
- (this.pathHead % 4) * QUIC_PATH_DATA_SIZE
5020
- )
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)
5021
5319
  if (next < 0) {
5022
5320
  break
5023
5321
  }
5024
5322
  at = next
5025
- this.pathHead = (this.pathHead + 1) % 4
5026
- 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
5027
5327
  // Ack-eliciting, but never sent again (RFC 9000 §13.3).
5028
5328
  space.stagedEliciting = true
5029
5329
  this.pathFrameStaged = true
5030
5330
  }
5031
5331
  // The PATH_CHALLENGE on a path being validated; one lost is not sent
5032
5332
  // again, but `runPathClock` draws fresh data a probe timeout later.
5033
- if (this.challengeOwed && this.challengesDrawn > 0 && end - at >= 9) {
5034
- const slot: i32 = toI32((this.challengesDrawn - 1) % toI64(QUIC_CONN_CHALLENGES))
5035
- const next: i32 = quicPutPathData(
5036
- out,
5037
- at,
5038
- end,
5039
- QUIC_FRAME_PATH_CHALLENGE,
5040
- this.challengeData,
5041
- slot * QUIC_PATH_DATA_SIZE
5042
- )
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
5043
5339
  if (next >= 0) {
5044
5340
  at = next
5045
5341
  this.challengeOwed = false
@@ -5067,7 +5363,7 @@ export class QuicConnection {
5067
5363
  // 8-byte ID at most 42.
5068
5364
  while (
5069
5365
  this.cids.retireCount > 0 &&
5070
- end - at >= 9 &&
5366
+ toI64(end) - toI64(at) >= 9 &&
5071
5367
  space.controlCount(space.staging) < QUIC_CONN_PACKET_CONTROL
5072
5368
  ) {
5073
5369
  const sequence: i64 = this.cids.takeRetire()
@@ -5075,7 +5371,11 @@ export class QuicConnection {
5075
5371
  space.stageControl(QUIC_CONN_CONTROL_RETIRE, sequence)
5076
5372
  }
5077
5373
  let entry: QuicCidEntry | null = this.cids.nextUnannounced()
5078
- 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
+ ) {
5079
5379
  const next: i32 = quicPutNewConnectionId(
5080
5380
  out,
5081
5381
  at,
@@ -5168,8 +5468,10 @@ export class QuicConnection {
5168
5468
  const keys: QuicKeys | null = space.writeKeys
5169
5469
  const pn: i64 = space.nextPn
5170
5470
  const pnLength: i32 = quicPacketNumberLength(pn, space.largestAcked)
5171
- const headerLength: i32 = this.overhead(space) - QUIC_AEAD_TAG_SIZE
5172
- 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))
5173
5475
  const entry: QuicCidEntry | null = this.cids.currentPeerEntry()
5174
5476
  const headerEnd: i32 =
5175
5477
  space.level === TLS_LEVEL_APPLICATION
@@ -5196,25 +5498,26 @@ export class QuicConnection {
5196
5498
  pnLength,
5197
5499
  payloadLength
5198
5500
  )
5199
- if (keys === null || headerEnd !== start + headerLength) {
5501
+ if (keys === null || toI64(headerEnd) !== toI64(start) + toI64(headerLength)) {
5200
5502
  return 0
5201
5503
  }
5202
5504
  const end: i32 = quicSealInPlace(keys, out, start, headerLength, payloadLength, pn)
5203
5505
  if (end < 0) {
5204
5506
  return 0
5205
5507
  }
5206
- space.nextPn = pn + 1
5508
+ space.nextPn = quicConnSum(pn, 1)
5207
5509
  if (space.level === TLS_LEVEL_APPLICATION) {
5208
- this.sealedUnderKey = this.sealedUnderKey + 1
5510
+ this.sealedUnderKey = quicConnSum(this.sealedUnderKey, 1)
5209
5511
  }
5210
- 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)
5211
5514
  if (this.pmtuSealing) {
5212
5515
  this.recovery.onProbeSent(space.level, slot)
5213
5516
  }
5214
5517
  if (this.datagramEcn !== 0) {
5215
5518
  this.recovery.onEctSent(space.level, slot)
5216
5519
  }
5217
- return end - start
5520
+ return size
5218
5521
  }
5219
5522
 
5220
5523
  /**
@@ -5233,8 +5536,9 @@ export class QuicConnection {
5233
5536
  const slot: i32 = this.recovery.onPacketSent(space.level, pn, size, this.now)
5234
5537
  if (slot >= 0) {
5235
5538
  space.commitStaged(slot)
5236
- if (space.probes > 0) {
5237
- space.probes -= 1
5539
+ const probes: i32 = space.probes
5540
+ if (probes > 0) {
5541
+ space.probes = probes - 1
5238
5542
  // §6.2.4: a second probe carries unacknowledged data too. When the
5239
5543
  // first took everything queued, the oldest — what it just carried —
5240
5544
  // goes again.
@@ -5253,7 +5557,7 @@ export class QuicConnection {
5253
5557
  private untrack(space: QuicConnSpace, row: i32): void {
5254
5558
  const streams: i32 = space.streamCount(row)
5255
5559
  for (let j: i32 = 0; j < streams; j += 1) {
5256
- const at: i32 = row * QUIC_CONN_PACKET_STREAMS + j
5560
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_STREAMS, toI32(space.sentStreamId.length))
5257
5561
  if (
5258
5562
  at >= 0 &&
5259
5563
  at < toI32(space.sentStreamId.length) &&
@@ -5271,7 +5575,7 @@ export class QuicConnection {
5271
5575
  }
5272
5576
  const control: i32 = space.controlCount(row)
5273
5577
  for (let j: i32 = 0; j < control; j += 1) {
5274
- const at: i32 = row * QUIC_CONN_PACKET_CONTROL + j
5578
+ const at: i32 = quicConnCell(row, j, QUIC_CONN_PACKET_CONTROL, toI32(space.sentControlKind.length))
5275
5579
  if (at >= 0 && at < toI32(space.sentControlKind.length) && at < toI32(space.sentControlValue.length)) {
5276
5580
  this.streams.controlAcked(toI32(space.sentControlKind[at]), space.sentControlValue[at])
5277
5581
  }
@@ -5294,7 +5598,10 @@ export class QuicConnection {
5294
5598
  this.closeSent = true
5295
5599
  this.startClosingPeriod()
5296
5600
  let position: i32 = at
5297
- 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))
5298
5605
  for (let level: i32 = 0; level < 3; level += 1) {
5299
5606
  const space: QuicConnSpace = this.spaceAt(level)
5300
5607
  const overhead: i32 = this.overhead(space)
@@ -5302,8 +5609,8 @@ export class QuicConnection {
5302
5609
  continue
5303
5610
  }
5304
5611
  space.clearStaged()
5305
- const payloadStart: i32 = position + overhead - QUIC_AEAD_TAG_SIZE
5306
- 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))
5307
5614
  let payloadEnd: i32 =
5308
5615
  level === TLS_LEVEL_APPLICATION || !this.errorIsApplication
5309
5616
  ? quicPutConnectionClose(
@@ -5328,14 +5635,18 @@ export class QuicConnection {
5328
5635
  continue
5329
5636
  }
5330
5637
  const pnLength: i32 = quicPacketNumberLength(space.nextPn, space.largestAcked)
5331
- if (pnLength + payloadEnd - payloadStart < 4) {
5332
- 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))
5333
5643
  }
5334
- position = position + this.sealAt(space, out, position, payloadEnd)
5644
+ position = toI32(toI64(position) + toI64(this.sealAt(space, out, position, payloadEnd)))
5335
5645
  }
5336
- this.bytesSent = this.bytesSent + toI64(position - at)
5337
- this.notePathSent(position - at)
5338
- 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
5339
5650
  }
5340
5651
 
5341
5652
  /**