@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
@@ -74,7 +74,7 @@
74
74
  *
75
75
  * Written from RFC 9110 and RFC 9112, not ported from another implementation.
76
76
  */
77
- import { copyBytes } from "nish/bytes"
77
+ import { tryCopyBytes } from "nish/bytes"
78
78
  import { DNS_ADDRESS_BYTES } from "nish/net/dns-message"
79
79
  import { DNS_RESOLVE_MAX_ADDRESSES } from "nish/net/dns-resolver"
80
80
  import { resolveHost } from "nish/net/dns"
@@ -88,7 +88,12 @@ import {
88
88
  HTTP1_NEED_MORE,
89
89
  HTTP1_NO_BODY,
90
90
  } from "nish/net/http1-codec"
91
- import { HTTP1_INFORMATIONAL, Http1ResponseParser, http1WriteRequestHead } from "nish/net/http1-client-codec"
91
+ import {
92
+ HTTP1_E_BODY_LIMIT,
93
+ HTTP1_INFORMATIONAL,
94
+ Http1ResponseParser,
95
+ http1WriteRequestHead,
96
+ } from "nish/net/http1-client-codec"
92
97
  import { OutboundPolicy, outboundAddressText, outboundFilter, outboundHostAllowed } from "nish/net/outbound"
93
98
  import { Url, urlParse } from "nish/net/url"
94
99
  import {
@@ -105,7 +110,7 @@ import { monotonicNanos } from "nish:process"
105
110
 
106
111
  /** The call was read to its end: `ok`. */
107
112
  export const UPSTREAM_E_NONE: i32 = 0
108
- // 1 to 17 are the codec's own `HTTP1_E_` refusals, passed through as they are.
113
+ // 1 to 18 are the codec's own `HTTP1_E_` refusals, passed through as they are.
109
114
  /** The origin is not an `http:` URL with a host and nothing past its authority but `/`. */
110
115
  export const UPSTREAM_E_ORIGIN: i32 = 32
111
116
  /** The origin's host could not be looked up at start-up. */
@@ -137,6 +142,9 @@ const UPSTREAM_READ_CHUNK: i32 = 16384
137
142
  /** The largest body a call takes, whatever `maxBody` says: doubling the buffer up to it stays in i32's range. */
138
143
  const UPSTREAM_MAX_BODY: i64 = 1073741824
139
144
 
145
+ /** Room for every address one lookup gives. */
146
+ const UPSTREAM_ADDRESS_ROOM: i32 = DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES
147
+
140
148
  /** A connection with no socket. */
141
149
  const UPSTREAM_C_CLOSED: i32 = 0
142
150
  /** Connecting, with a call waiting on it. */
@@ -207,13 +215,13 @@ export class UpstreamResponse {
207
215
  /**
208
216
  * An empty call slot; `Upstream` makes its pool of them.
209
217
  * @param index The slot's place in the pool.
210
- * @param headRoom The most bytes the request head may take.
218
+ * @param headRoom The most bytes the request head may take; below 1, none.
211
219
  * @param placeholder The request the slot names until a call takes it.
212
220
  */
213
221
  constructor(index: i32, headRoom: i32, placeholder: HttpRequest) {
214
222
  this.index = index
215
223
  this.req = placeholder
216
- this.head = new Array<u8>(headRoom)
224
+ this.head = upstreamBytes(headRoom)
217
225
  this.body = new Array<u8>(0)
218
226
  }
219
227
  }
@@ -260,9 +268,9 @@ export class Upstream {
260
268
  private calls: UpstreamResponse[]
261
269
  private free: i32[]
262
270
  /** Calls written into their slot and waiting for a connection, oldest first. */
263
- private waiting: i32[]
271
+ private waiting: UpstreamQueue
264
272
  /** Calls ended and not yet taken, in the order they ended. */
265
- private done: i32[]
273
+ private done: UpstreamQueue
266
274
  /** Why the origin is unusable; empty when it is not. For a log. */
267
275
  errorText: string = ""
268
276
  /** The handler turn `pump` last read. */
@@ -270,10 +278,6 @@ export class Upstream {
270
278
  /** Not `UPSTREAM_E_NONE` when the origin is unusable: every call then fails with it. */
271
279
  error: i32 = 0
272
280
  private freeCount: i32 = 0
273
- private waitingStart: i32 = 0
274
- private waitingCount: i32 = 0
275
- private doneStart: i32 = 0
276
- private doneCount: i32 = 0
277
281
 
278
282
  /**
279
283
  * Parses `origin`, looks its host up once (this blocks for at most
@@ -286,17 +290,17 @@ export class Upstream {
286
290
  * @param limits The pool's sizes, watch ids, deadlines and the codec's caps.
287
291
  */
288
292
  constructor(h: HttpHandler, origin: string, limits: UpstreamLimits) {
289
- if (limits.connections < 1 || limits.calls < 1 || limits.maxHead < 1 || limits.timeoutMs < 1) {
293
+ // Read once into locals: the checks below then still hold after the calls that build the pool.
294
+ const connections: i32 = limits.connections
295
+ const slots: i32 = limits.calls
296
+ const firstId: i32 = limits.firstId
297
+ if (connections < 1 || slots < 1 || limits.maxHead < 1 || limits.timeoutMs < 1) {
290
298
  panic("Upstream: connections, calls, maxHead and timeoutMs must each be at least 1")
291
299
  }
292
- // Each operand on its own: their sum could pass i32's range.
293
- if (
294
- limits.firstId < 0 ||
295
- limits.connections > HANDLER_MAX_WATCHED ||
296
- limits.firstId > HANDLER_MAX_WATCHED - limits.connections
297
- ) {
300
+ // Both are in 0 .. 2^31, so their unsigned sum cannot wrap.
301
+ if (firstId < 0 || toU32(firstId) + toU32(connections) > toU32(HANDLER_MAX_WATCHED)) {
298
302
  panic(
299
- `Upstream: watch ids ${limits.firstId} to ${limits.firstId + limits.connections - 1} are outside 0 to ${HANDLER_MAX_WATCHED - 1}`
303
+ `Upstream: ${connections} watch ids from ${firstId} are not all inside 0 to ${HANDLER_MAX_WATCHED - 1}`
300
304
  )
301
305
  }
302
306
  this.h = h
@@ -305,19 +309,25 @@ export class Upstream {
305
309
  this.hostNames = ["host"]
306
310
  this.hostValues = [""]
307
311
  this.connections = []
308
- for (let k: i32 = 0; k < limits.connections; k += 1) {
309
- this.connections.push(new UpstreamConnection(limits.firstId + k, upstreamParser(limits)))
312
+ for (let k: i32 = 0; k < connections; k += 1) {
313
+ // `firstId + k` is below `firstId + connections`, which the check above holds to HANDLER_MAX_WATCHED.
314
+ const id: i32 = toI32(toU32(firstId) + toU32(k))
315
+ this.connections.push(new UpstreamConnection(id, upstreamParser(limits)))
310
316
  }
311
317
  const placeholder: HttpRequest = new HttpRequest(-1)
312
318
  this.calls = []
313
- this.free = new Array<i32>(limits.calls)
314
- this.waiting = new Array<i32>(limits.calls)
315
- this.done = new Array<i32>(limits.calls)
316
- for (let k: i32 = 0; k < limits.calls; k += 1) {
319
+ const free: i32[] = upstreamSlots(slots)
320
+ for (let k: i32 = 0; k < slots && k < toI32(free.length); k += 1) {
321
+ // `k` is below `slots`, so `slots - 1 - k` is in 0 .. slots - 1 and the unsigned difference cannot wrap.
322
+ free[k] = toI32(toU32(slots) - 1 - toU32(k))
323
+ }
324
+ for (let k: i32 = 0; k < slots; k += 1) {
317
325
  this.calls.push(new UpstreamResponse(k, limits.maxHead, placeholder))
318
- this.free[k] = limits.calls - 1 - k
319
326
  }
320
- this.freeCount = limits.calls
327
+ this.free = free
328
+ this.waiting = new UpstreamQueue(upstreamSlots(slots))
329
+ this.done = new UpstreamQueue(upstreamSlots(slots))
330
+ this.freeCount = slots
321
331
  this.settle(origin)
322
332
  }
323
333
 
@@ -340,13 +350,13 @@ export class Upstream {
340
350
  const host: string = url.host
341
351
  const port: i32 = url.port >= 0 ? url.port : 80
342
352
  const named: string = host.indexOf(":") >= 0 ? `[${host}]` : host
343
- this.hostValues[0] = url.port >= 0 ? `${named}:${port}` : named
353
+ this.hostValues = [url.port >= 0 ? `${named}:${port}` : named]
344
354
  const policy: OutboundPolicy | null = this.limits.outbound
345
355
  if (policy !== null && !outboundHostAllowed(policy, host)) {
346
356
  this.fail(UPSTREAM_E_BLOCKED, `${host} is not a host the outbound policy allows`)
347
357
  return
348
358
  }
349
- const addresses: u8[] = new Array<u8>(DNS_RESOLVE_MAX_ADDRESSES * DNS_ADDRESS_BYTES)
359
+ const addresses: u8[] = new Array<u8>(UPSTREAM_ADDRESS_ROOM)
350
360
  const ttls: i32[] = new Array<i32>(DNS_RESOLVE_MAX_ADDRESSES)
351
361
  const count: i32 = resolveHost(host, this.limits.lookupMs, port, addresses, ttls)
352
362
  if (count <= 0) {
@@ -368,7 +378,10 @@ export class Upstream {
368
378
  return
369
379
  }
370
380
  }
371
- copyBytes(this.address, 0, addresses, 0, DNS_ADDRESS_BYTES)
381
+ // `usable` is at least 1 here, so the first address is filled and the copy does not fail.
382
+ if (!tryCopyBytes(this.address, 0, addresses, 0, DNS_ADDRESS_BYTES)) {
383
+ this.fail(UPSTREAM_E_LOOKUP, `${host} gave no address to copy`)
384
+ }
372
385
  }
373
386
 
374
387
  private fail(code: i32, text: string): void {
@@ -389,24 +402,38 @@ export class Upstream {
389
402
  * @returns `UPSTREAM_E_NONE` when the call started, `UPSTREAM_E_FULL` when no slot is free.
390
403
  */
391
404
  get(req: HttpRequest, path: string): i32 {
392
- if (this.freeCount === 0) {
405
+ const count: i32 = this.freeCount
406
+ if (count <= 0) {
407
+ return UPSTREAM_E_FULL
408
+ }
409
+ const top: i32 = count - 1
410
+ const free: i32[] = this.free
411
+ // The free list holds `calls` places and `freeCount` never passes it; this only lets the index be proven.
412
+ if (top >= toI32(free.length)) {
393
413
  return UPSTREAM_E_FULL
394
414
  }
395
- this.freeCount -= 1
396
- const r: UpstreamResponse = this.calls[this.free[this.freeCount]]
415
+ const r: UpstreamResponse | null = this.slot(free[top])
416
+ // The free list holds only places of `calls`, so `r` is never null; the test proves the read.
417
+ if (r === null) {
418
+ return UPSTREAM_E_FULL
419
+ }
420
+ this.freeCount = top
397
421
  r.req = req
398
422
  r.ok = false
399
423
  r.status = 0
400
424
  r.error = UPSTREAM_E_NONE
401
425
  r.length = 0
402
426
  r.retried = false
403
- r.deadline = monotonicNanos() + toI64(this.limits.timeoutMs) * UPSTREAM_NS_PER_MS
427
+ // The clock counts nanoseconds since boot and the span is under 2^52 ns, so the sum is far inside
428
+ // i64; added as u64 it is the same two's-complement sum without an overflow check.
429
+ const span: i64 = toI64(this.limits.timeoutMs) * UPSTREAM_NS_PER_MS
430
+ r.deadline = toI64(toU64(monotonicNanos()) + toU64(span))
404
431
  if (this.error !== UPSTREAM_E_NONE) {
405
432
  this.end(r, this.error)
406
433
  return UPSTREAM_E_NONE
407
434
  }
408
435
  // An origin-form target only: an absolute-form one would name another host on this pool's connection.
409
- if (path.length === 0 || path.charCodeAt(0) !== 47) {
436
+ if (path.length <= 0 || path.charCodeAt(0) !== 47) {
410
437
  this.end(r, UPSTREAM_E_REQUEST)
411
438
  return UPSTREAM_E_NONE
412
439
  }
@@ -424,9 +451,7 @@ export class Upstream {
424
451
  return UPSTREAM_E_NONE
425
452
  }
426
453
  r.headLength = n
427
- const at: i32 = (this.waitingStart + this.waitingCount) % toI32(this.waiting.length)
428
- this.waiting[at] = r.index
429
- this.waitingCount += 1
454
+ this.waiting.push(r.index)
430
455
  this.dispatch()
431
456
  return UPSTREAM_E_NONE
432
457
  }
@@ -437,7 +462,7 @@ export class Upstream {
437
462
  */
438
463
  ready(): boolean {
439
464
  this.pump()
440
- return this.doneCount > 0
465
+ return this.done.count > 0
441
466
  }
442
467
 
443
468
  /**
@@ -445,12 +470,10 @@ export class Upstream {
445
470
  * @returns The call, with `ok`, `status` and its body, or `error` saying why it failed.
446
471
  */
447
472
  take(): UpstreamResponse {
448
- if (!this.ready()) {
473
+ const r: UpstreamResponse | null = this.ready() ? this.slot(this.done.shift()) : null
474
+ if (r === null) {
449
475
  panic("Upstream.take: no call is ready")
450
476
  }
451
- const r: UpstreamResponse = this.calls[this.done[this.doneStart]]
452
- this.doneStart = (this.doneStart + 1) % toI32(this.done.length)
453
- this.doneCount -= 1
454
477
  r.taken = true
455
478
  return r
456
479
  }
@@ -465,9 +488,15 @@ export class Upstream {
465
488
  if (!r.taken) {
466
489
  panic("Upstream.release: the call is not taken, or was released already")
467
490
  }
491
+ const top: i32 = this.freeCount
492
+ const free: i32[] = this.free
493
+ // A taken slot is not on the free list, so the list has room for it: this only lets the index be proven.
494
+ if (top < 0 || top >= toI32(free.length)) {
495
+ return
496
+ }
468
497
  r.taken = false
469
- this.free[this.freeCount] = r.index
470
- this.freeCount += 1
498
+ free[top] = r.index
499
+ this.freeCount = top + 1
471
500
  }
472
501
 
473
502
  /**
@@ -475,7 +504,8 @@ export class Upstream {
475
504
  * @returns The count of slots in use.
476
505
  */
477
506
  pending(): i32 {
478
- return toI32(this.free.length) - this.freeCount
507
+ // `freeCount` stays in 0 .. free.length, so the unsigned difference cannot wrap.
508
+ return toI32(toU32(toI32(this.free.length)) - toU32(this.freeCount))
479
509
  }
480
510
 
481
511
  /**
@@ -483,13 +513,14 @@ export class Upstream {
483
513
  * @returns The count of open connections.
484
514
  */
485
515
  openConnections(): i32 {
486
- let n: i32 = 0
516
+ // Counted unsigned: it is at most `connections.length`, so it cannot wrap.
517
+ let n: u32 = 0
487
518
  for (let k: i32 = 0; k < toI32(this.connections.length); k += 1) {
488
519
  if (this.connections[k].fd >= 0) {
489
520
  n += 1
490
521
  }
491
522
  }
492
- return n
523
+ return toI32(n)
493
524
  }
494
525
 
495
526
  // ---- The loop ---------------------------------------------------------------
@@ -509,15 +540,20 @@ export class Upstream {
509
540
  const now: i64 = monotonicNanos()
510
541
  for (let k: i32 = 0; k < toI32(this.connections.length); k += 1) {
511
542
  const c: UpstreamConnection = this.connections[k]
512
- if (c.call >= 0 && this.calls[c.call].deadline <= now) {
543
+ const r: UpstreamResponse | null = this.slot(c.call)
544
+ if (r !== null && r.deadline <= now) {
513
545
  this.finish(c, UPSTREAM_E_TIMEOUT)
514
546
  }
515
547
  }
516
548
  // Every call has the same timeout, so the oldest waiting call is the first to expire.
517
- while (this.waitingCount > 0 && this.calls[this.waiting[this.waitingStart]].deadline <= now) {
518
- const r: UpstreamResponse = this.calls[this.waiting[this.waitingStart]]
519
- this.waitingStart = (this.waitingStart + 1) % toI32(this.waiting.length)
520
- this.waitingCount -= 1
549
+ while (this.waiting.count > 0) {
550
+ const r: UpstreamResponse | null = this.slot(this.waiting.peek())
551
+ // `waiting` holds only places of `calls` and is not empty here, so `r` is never null;
552
+ // stopping on null leaves the ring as it is rather than spinning on a place it cannot read.
553
+ if (r === null || r.deadline > now) {
554
+ break
555
+ }
556
+ this.waiting.shift()
521
557
  this.end(r, UPSTREAM_E_TIMEOUT)
522
558
  }
523
559
  this.dispatch()
@@ -525,15 +561,12 @@ export class Upstream {
525
561
 
526
562
  /** Puts waiting calls on connections: a kept-alive one first, then a new one. */
527
563
  private dispatch(): void {
528
- while (this.waitingCount > 0) {
564
+ while (this.waiting.count > 0) {
529
565
  const c: UpstreamConnection | null = this.idle()
530
566
  if (c === null) {
531
567
  return
532
568
  }
533
- const index: i32 = this.waiting[this.waitingStart]
534
- this.waitingStart = (this.waitingStart + 1) % toI32(this.waiting.length)
535
- this.waitingCount -= 1
536
- c.call = index
569
+ c.call = this.waiting.shift()
537
570
  c.sent = 0
538
571
  c.answered = false
539
572
  c.reused = c.state === UPSTREAM_C_IDLE
@@ -587,7 +620,7 @@ export class Upstream {
587
620
  this.finish(c, UPSTREAM_E_CONNECT)
588
621
  return
589
622
  }
590
- if (pollAdd(this.h.loop, fd, UPSTREAM_WRITE, -2 - c.id) < 0) {
623
+ if (pollAdd(this.h.loop, fd, UPSTREAM_WRITE, upstreamToken(c.id)) < 0) {
591
624
  netClose(fd)
592
625
  this.finish(c, UPSTREAM_E_CONNECT)
593
626
  return
@@ -609,7 +642,8 @@ export class Upstream {
609
642
  }
610
643
  c.state = UPSTREAM_C_BUSY
611
644
  }
612
- if (c.state === UPSTREAM_C_BUSY && c.call >= 0 && c.sent < this.calls[c.call].headLength) {
645
+ const r: UpstreamResponse | null = this.slot(c.call)
646
+ if (c.state === UPSTREAM_C_BUSY && r !== null && c.sent < r.headLength) {
613
647
  this.send(c)
614
648
  return
615
649
  }
@@ -618,9 +652,24 @@ export class Upstream {
618
652
 
619
653
  /** Writes what the socket takes of the call's head, then waits to read. */
620
654
  private send(c: UpstreamConnection): void {
621
- const r: UpstreamResponse = this.calls[c.call]
622
- while (c.sent < r.headLength) {
623
- const n: i32 = netWrite(c.fd, r.head, c.sent, r.headLength - c.sent)
655
+ const r: UpstreamResponse | null = this.slot(c.call)
656
+ // `dispatch` sends only a connection it gave a place of `calls`, so `r` is never null.
657
+ if (r === null) {
658
+ this.finish(c, UPSTREAM_E_CLOSED)
659
+ return
660
+ }
661
+ const head: u8[] = r.head
662
+ const end: i32 = r.headLength
663
+ // `get` wrote `end` bytes into `head` and `sent` only grows to `end`, so this never fires.
664
+ if (c.sent < 0 || end > toI32(head.length)) {
665
+ this.finish(c, UPSTREAM_E_REQUEST)
666
+ return
667
+ }
668
+ let sent: i32 = c.sent
669
+ while (sent < end) {
670
+ // Unsigned, as `0 <= sent < end` makes the difference fit and the prover cannot relate the two.
671
+ const left: i32 = toI32(toU32(end) - toU32(sent))
672
+ const n: i32 = netWrite(c.fd, head, sent, left)
624
673
  if (n === UPSTREAM_WOULD_BLOCK) {
625
674
  this.interest(c, UPSTREAM_WRITE)
626
675
  return
@@ -629,7 +678,9 @@ export class Upstream {
629
678
  this.finish(c, UPSTREAM_E_CLOSED)
630
679
  return
631
680
  }
632
- c.sent += n
681
+ // Unsigned, as `n <= left` keeps the sum at most `end`.
682
+ sent = toI32(toU32(sent) + toU32(n))
683
+ c.sent = sent
633
684
  }
634
685
  this.interest(c, UPSTREAM_READ)
635
686
  }
@@ -670,14 +721,22 @@ export class Upstream {
670
721
  const p: Http1ResponseParser = c.parser
671
722
  while (c.call >= 0) {
672
723
  const event: i32 = p.next()
673
- const r: UpstreamResponse = this.calls[c.call]
724
+ const r: UpstreamResponse | null = this.slot(c.call)
674
725
  if (event === HTTP1_NEED_MORE) {
675
726
  return
676
727
  }
728
+ // The loop runs only while `c.call` is a place `dispatch` gave it, so `r` is never null.
729
+ if (r === null) {
730
+ this.finish(c, UPSTREAM_E_CLOSED)
731
+ return
732
+ }
677
733
  if (event === HTTP1_HEAD) {
678
734
  r.status = p.status
679
735
  } else if (event === HTTP1_BODY) {
680
- upstreamAppend(r, p.body, p.bodyOff, p.bodyLen)
736
+ if (!upstreamAppend(r, p.body, p.bodyOff, p.bodyLen)) {
737
+ // The codec caps a body at `maxBody`, at most 1 GiB, so this is a body past the cap.
738
+ this.finish(c, HTTP1_E_BODY_LIMIT)
739
+ }
681
740
  } else if (event === HTTP1_END) {
682
741
  const again: boolean = p.keepAlive() && p.buffered() === 0
683
742
  this.finish(c, UPSTREAM_E_NONE)
@@ -708,15 +767,12 @@ export class Upstream {
708
767
  * safe to send again. Past its deadline it is not.
709
768
  */
710
769
  private finish(c: UpstreamConnection, code: i32): void {
711
- if (c.call >= 0) {
712
- const r: UpstreamResponse = this.calls[c.call]
713
- c.call = -1
770
+ const r: UpstreamResponse | null = this.slot(c.call)
771
+ c.call = -1
772
+ if (r !== null) {
714
773
  if (code !== UPSTREAM_E_NONE && code !== UPSTREAM_E_TIMEOUT && c.reused && !c.answered && !r.retried) {
715
774
  r.retried = true
716
- const length: i32 = toI32(this.waiting.length)
717
- this.waitingStart = (this.waitingStart + length - 1) % length
718
- this.waiting[this.waitingStart] = r.index
719
- this.waitingCount += 1
775
+ this.waiting.unshift(r.index)
720
776
  } else {
721
777
  this.end(r, code)
722
778
  }
@@ -733,15 +789,24 @@ export class Upstream {
733
789
  if (!r.ok) {
734
790
  r.length = 0
735
791
  }
736
- const at: i32 = (this.doneStart + this.doneCount) % toI32(this.done.length)
737
- this.done[at] = r.index
738
- this.doneCount += 1
792
+ this.done.push(r.index)
793
+ }
794
+
795
+ /**
796
+ * The call slot at `index`, or null for -1 (no call). Every index the pool
797
+ * stores is a slot's own, so null for any other value is only the proof's.
798
+ */
799
+ private slot(index: i32): UpstreamResponse | null {
800
+ if (index < 0 || index >= toI32(this.calls.length)) {
801
+ return null
802
+ }
803
+ return this.calls[index]
739
804
  }
740
805
 
741
806
  /** Watches `c` for `events` alone. */
742
807
  private interest(c: UpstreamConnection, events: i32): void {
743
808
  if (c.events !== events) {
744
- pollModify(this.h.loop, c.fd, events, -2 - c.id)
809
+ pollModify(this.h.loop, c.fd, events, upstreamToken(c.id))
745
810
  c.events = events
746
811
  }
747
812
  }
@@ -774,22 +839,154 @@ const upstreamParser = (limits: UpstreamLimits): Http1ResponseParser => {
774
839
  return p
775
840
  }
776
841
 
842
+ /**
843
+ * `n` zero bytes, none when `n` is below 1. Filled by `push`, so no `i32`
844
+ * length is computed for `new Array`.
845
+ */
846
+ const upstreamBytes = (n: i32): u8[] => {
847
+ const a: u8[] = []
848
+ for (let i: i32 = 0; i < n; i += 1) {
849
+ a.push(0)
850
+ }
851
+ return a
852
+ }
853
+
854
+ /** Room for `n` slot indexes, filled the way `upstreamBytes` is. */
855
+ const upstreamSlots = (n: i32): i32[] => {
856
+ const a: i32[] = []
857
+ for (let i: i32 = 0; i < n; i += 1) {
858
+ a.push(0)
859
+ }
860
+ return a
861
+ }
862
+
863
+ /**
864
+ * The poll token the handler's loop reports for watch id `id`: `-2 - id`.
865
+ * Watch ids are in 0 .. HANDLER_MAX_WATCHED, so the unsigned difference is
866
+ * that same small negative number and does not wrap past it.
867
+ */
868
+ const upstreamToken = (id: i32): i32 => toI32(toU32(-2) - toU32(id))
869
+
870
+ /**
871
+ * A ring of call slot indexes, one place per slot. Each slot sits in at most
872
+ * one ring at a time, so a ring is never full when a slot is put in it.
873
+ */
874
+ class UpstreamQueue {
875
+ /** @internal */
876
+ items: i32[]
877
+ /** Where the oldest index sits. @internal */
878
+ start: i32 = 0
879
+ /** How many indexes the ring holds. @internal */
880
+ count: i32 = 0
881
+
882
+ constructor(items: i32[]) {
883
+ this.items = items
884
+ }
885
+
886
+ /** The place `offset` past `start`, or -1 when the ring cannot hold it. */
887
+ at(offset: i32): i32 {
888
+ const n: i32 = toI32(this.items.length)
889
+ if (this.start < 0 || this.start >= n || offset < 0 || offset >= n) {
890
+ return -1
891
+ }
892
+ // Both are below `n`, under 2^31, so the unsigned sum cannot wrap, and one lap brings it back under `n`.
893
+ const sum: u32 = toU32(this.start) + toU32(offset)
894
+ return toI32(sum < toU32(n) ? sum : sum - toU32(n))
895
+ }
896
+
897
+ /** Puts `index` last. */
898
+ push(index: i32): void {
899
+ const count: i32 = this.count
900
+ if (count < 0 || count >= toI32(this.items.length)) {
901
+ return
902
+ }
903
+ const at: i32 = this.at(count)
904
+ if (at >= 0 && at < toI32(this.items.length)) {
905
+ this.items[at] = index
906
+ this.count = count + 1
907
+ }
908
+ }
909
+
910
+ /** Puts `index` first. */
911
+ unshift(index: i32): void {
912
+ const count: i32 = this.count
913
+ const n: i32 = toI32(this.items.length)
914
+ if (count < 0 || count >= n) {
915
+ return
916
+ }
917
+ // One place back is `n - 1` places on, round the ring.
918
+ const at: i32 = this.at(n - 1)
919
+ if (at >= 0 && at < toI32(this.items.length)) {
920
+ this.items[at] = index
921
+ this.start = at
922
+ this.count = count + 1
923
+ }
924
+ }
925
+
926
+ /** The first index, or -1 when the ring is empty. */
927
+ peek(): i32 {
928
+ const items: i32[] = this.items
929
+ const start: i32 = this.start
930
+ if (this.count <= 0 || start < 0 || start >= toI32(items.length)) {
931
+ return -1
932
+ }
933
+ return items[start]
934
+ }
935
+
936
+ /** Takes the first index out, or -1 when the ring is empty. */
937
+ shift(): i32 {
938
+ const count: i32 = this.count
939
+ const first: i32 = this.peek()
940
+ if (first >= 0 && count > 0) {
941
+ // A ring of one place has no place 1 on: its next start is 0 again.
942
+ const next: i32 = this.at(toI32(1))
943
+ this.start = next >= 0 ? next : 0
944
+ this.count = count - 1
945
+ }
946
+ return first
947
+ }
948
+ }
949
+
777
950
  /**
778
951
  * Appends `data[off .. off + len)` to `r`'s body, growing its buffer by
779
952
  * doubling when it is full: to under twice the body, and at least 1 KiB.
953
+ * False, with the body as it was, when the body would pass
954
+ * UPSTREAM_MAX_BODY or the window is outside `data`; the codec caps a body
955
+ * below that, so neither comes from a response it accepted.
780
956
  */
781
- const upstreamAppend = (r: UpstreamResponse, data: u8[], off: i32, len: i32): void => {
782
- const need: i32 = r.length + len
783
- if (need > toI32(r.body.length)) {
784
- let size: i32 = toI32(r.body.length) < 1024 ? 1024 : toI32(r.body.length)
785
- // `need` is at most UPSTREAM_MAX_BODY, 2^30, so `size` doubles to 2^30 at most.
957
+ const upstreamAppend = (r: UpstreamResponse, data: u8[], off: i32, len: i32): boolean => {
958
+ const length: i32 = r.length
959
+ if (length < 0 || len < 0) {
960
+ return false
961
+ }
962
+ // Both are in 0 .. 2^31, so the unsigned sum cannot wrap.
963
+ const need: u32 = toU32(length) + toU32(len)
964
+ if (toI64(need) > UPSTREAM_MAX_BODY) {
965
+ return false
966
+ }
967
+ if (need > toU32(toI32(r.body.length))) {
968
+ let size: u32 = toI32(r.body.length) < 1024 ? 1024 : toU32(toI32(r.body.length))
969
+ // `need` is at most 2^30, so `size` doubles to under 2^31 and the unsigned product cannot wrap.
786
970
  while (size < need) {
787
971
  size = size * 2
788
972
  }
789
- const grown: u8[] = new Array<u8>(size)
790
- copyBytes(grown, 0, r.body, 0, r.length)
973
+ const old: u8[] = r.body
974
+ if (length > toI32(old.length)) {
975
+ return false
976
+ }
977
+ // Built by `push`, so no `i32` length is computed for `new Array`.
978
+ const grown: u8[] = []
979
+ for (let i: i32 = 0; i < length && i < toI32(old.length); i += 1) {
980
+ grown.push(old[i])
981
+ }
982
+ while (toU32(grown.length) < size) {
983
+ grown.push(0)
984
+ }
791
985
  r.body = grown
792
986
  }
793
- copyBytes(r.body, r.length, data, off, len)
794
- r.length = need
987
+ if (!tryCopyBytes(r.body, length, data, off, len)) {
988
+ return false
989
+ }
990
+ r.length = toI32(need)
991
+ return true
795
992
  }