nish 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/README.md +1 -1
  2. package/docs/AI.md +18 -16
  3. package/package.json +5 -5
  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
@@ -65,11 +65,23 @@
65
65
  * buffer grows to the body it holds, so a handler holds at most its slots
66
66
  * times the cap in bodies. `docs/security/handler.md` is the record.
67
67
  *
68
+ * **A compressed body is decoded under its own cap.** A body sent with one
69
+ * `Content-Encoding` of `gzip`, `x-gzip` or `deflate` is decoded before the
70
+ * program takes it, into at most `HandlerLimits.maxDecoded` bytes (one MiB):
71
+ * `req.body` holds the decoded bytes and `req.decodedFrom` the coding they
72
+ * came in. A body that decodes past the cap — a decompression bomb — is
73
+ * answered 413 by the handler, and one that does not decode 400; the program
74
+ * never takes either. Any other coding, or two codings stacked, reaches the
75
+ * program as it arrived, with `decodedFrom` `HTTP_CODING_IDENTITY`.
76
+ *
68
77
  * Misuse — a status outside 200 to 599, a reserved field (`Content-Length`,
69
78
  * `Transfer-Encoding`, `Connection`, `Upgrade`, `Keep-Alive`), more body than
70
79
  * the length said, a second `start` — panics: it is a bug in the program,
71
- * never something a peer can cause. What a peer can cause answers a code the
72
- * program may ignore, so no answer needs its result bound.
80
+ * never something a peer can cause. Each answering method has a `try` twin
81
+ * (`tryWrite`, `tryEnd`, `trySend`, ...) that answers the same misuse as an
82
+ * `Err` instead, for a program built without panics; the class doc says
83
+ * what each refusal leaves of the request. What a peer can cause answers a
84
+ * code the program may ignore, so no answer needs its result bound.
73
85
  *
74
86
  * Private helpers share the importing program's flat symbol namespace
75
87
  * (`docs/wp26-stdlib.md` §3e), which is why each one carries the module's name.
@@ -114,13 +126,30 @@ import {
114
126
  pollWait,
115
127
  tcpListenFlags,
116
128
  } from "nish:net"
117
-
129
+ import {
130
+ HTTP_CODING_DEFLATE,
131
+ HTTP_CODING_GZIP,
132
+ HTTP_CODING_IDENTITY,
133
+ HTTP_CODING_NONE,
134
+ HTTP_DECODE_TOO_LARGE,
135
+ HttpBodyDecoder,
136
+ httpContentEncoding,
137
+ } from "nish/net/http-compress"
138
+
139
+ /** A core's answer when the call broke its contract: `refusal` says how, and the public method panics with it. */
140
+ const HANDLER_REFUSED: i32 = -24
118
141
  /** An answer sent, or queued to be sent. */
119
142
  export const HANDLER_SENT: i32 = 0
120
143
  /** An answer for a request whose connection closed first: nothing was sent. */
121
144
  export const HANDLER_DROPPED: i32 = -21
122
145
  /** `HttpRequest.query` and `header`: no such name. */
123
146
  export const HANDLER_ABSENT: i32 = -20
147
+ /** `before` and `after`: every step bound to the request's route has run, and the request is still the program's to answer. */
148
+ export const HANDLER_NEXT: i32 = -22
149
+ /** `before` and `after`: a step answered the request, so the route body must not. */
150
+ export const HANDLER_ANSWERED: i32 = -23
151
+ /** The most fields `field` adds to one answer. */
152
+ export const HANDLER_MAX_ADDED: i32 = 16
124
153
 
125
154
  /** The most descriptors `watch` takes beside the handler's own. */
126
155
  export const HANDLER_MAX_WATCHED: i32 = 16
@@ -202,11 +231,18 @@ export class HandlerLimits {
202
231
  * to a second, or until `wait` returns.
203
232
  */
204
233
  bodyTimeout: i32 = 30000
234
+ /**
235
+ * The most bytes a `gzip` or `deflate` request body may decode to; past it
236
+ * the request is answered 413 and never taken. 0 decodes nothing, so every
237
+ * body reaches the program as it arrived. Each slot's body buffer may grow
238
+ * to this as well as to `http.maxBody`.
239
+ */
240
+ maxDecoded: i32 = 1048576
205
241
 
206
242
  /**
207
243
  * The defaults: 256 slots, a 64 KiB JSON buffer, 256 events a turn, a 30
208
- * second body timeout, and the carrier's own defaults with the body cap
209
- * lowered to one MiB. Change a field after construction to tune one.
244
+ * second body timeout, a one MiB cap on a decoded body, and the carrier's
245
+ * own defaults with the body cap lowered to one MiB. Set a field to tune it.
210
246
  */
211
247
  constructor() {
212
248
  this.http = new Http1Config()
@@ -290,6 +326,17 @@ export class HttpRequest {
290
326
  headerCount: i32 = 0
291
327
  /** How many bytes of `body` are the request's body, 0 for none; read the body as `body[0 .. bodyLength)`. */
292
328
  bodyLength: i32 = 0
329
+ /**
330
+ * The content coding the handler decoded `body` from: `HTTP_CODING_GZIP`
331
+ * or `HTTP_CODING_DEFLATE`, or `HTTP_CODING_IDENTITY` for a body that is
332
+ * as it arrived. Its `Content-Encoding` field is kept in `head` either way.
333
+ */
334
+ decodedFrom: i32 = 0
335
+ /**
336
+ * The status the handler answers in the program's place, 413 or 400, or 0.
337
+ * @internal Set by `HttpHandler` in this module when a body does not decode, and answered by `ready`.
338
+ */
339
+ refusal: i32 = 0
293
340
  /** The connection's slot, and its generation when this request was read. */
294
341
  slot: i32 = 0
295
342
  /**
@@ -314,6 +361,36 @@ export class HttpRequest {
314
361
  * @internal Advanced by `HttpHandler` in this module as `write` keeps what the carrier had no room for.
315
362
  */
316
363
  pendingEnd: i32 = 0
364
+ /**
365
+ * The steps `before` has still to hand out, one bit each; loaded from the router by the first `before`.
366
+ * @internal Moved only by `HttpHandler.before` in this module.
367
+ */
368
+ stepsLeft: i32 = 0
369
+ /**
370
+ * The steps `before` handed out that `after` has still to hand out again.
371
+ * @internal Moved by `HttpHandler.before` and `after` in this module.
372
+ */
373
+ stepsRan: i32 = 0
374
+ /**
375
+ * Whether `before` has loaded the route's steps into `stepsLeft`.
376
+ * @internal Set by `HttpHandler.before` and cleared when the request is read, in this module.
377
+ */
378
+ stepped: boolean = false
379
+ /**
380
+ * How many fields `field` added: `addedNames[0 .. added)` beside `addedValues`.
381
+ * @internal Counted by `HttpHandler.field` in this module, read by `start`, and cleared when the request is read.
382
+ */
383
+ added: i32 = 0
384
+ /**
385
+ * The names `field` added, kept by reference until the answer starts.
386
+ * @internal Grown by `HttpHandler.field` in this module, to at most `HANDLER_MAX_ADDED`, and kept for the requests after.
387
+ */
388
+ addedNames: u8[][]
389
+ /**
390
+ * The values `field` added, `addedValues[k]` for `addedNames[k]`.
391
+ * @internal Grown beside `addedNames` by `HttpHandler.field` in this module.
392
+ */
393
+ addedValues: u8[][]
317
394
 
318
395
  /**
319
396
  * An empty request for the handler's pool; its buffers grow to the first
@@ -327,6 +404,8 @@ export class HttpRequest {
327
404
  this.params = []
328
405
  this.body = []
329
406
  this.pending = []
407
+ this.addedNames = []
408
+ this.addedValues = []
330
409
  }
331
410
 
332
411
  /**
@@ -348,63 +427,143 @@ export class HttpRequest {
348
427
  }
349
428
 
350
429
  /**
351
- * Where parameter `k` starts in `head`. Panics on a parameter the route does not have.
430
+ * Where parameter `k` starts in `head`. Panics on a parameter the route does not have, a caller contract; `tryParam...` answers `Err` instead.
352
431
  * @param k the parameter's position in the route pattern, from 0
353
432
  * @returns the byte offset in `head` of the parameter's first raw byte
354
433
  */
355
434
  paramStart(k: i32): i32 {
356
- this.checkParam(k)
357
- return this.params[2 * k]
435
+ return this.paramBound(k, HANDLER_ZERO)
358
436
  }
359
437
 
360
438
  /**
361
- * Where parameter `k` ends in `head`.
439
+ * Where parameter `k` ends in `head`. Panics on a parameter the route does not have, a caller contract; `tryParam...` answers `Err` instead.
362
440
  * @param k the parameter's position in the route pattern, from 0
363
441
  * @returns the byte offset in `head` just past the parameter's last raw byte
364
442
  */
365
443
  paramEnd(k: i32): i32 {
366
- this.checkParam(k)
367
- return this.params[2 * k + 1]
444
+ return this.paramBound(k, toI32(1))
368
445
  }
369
446
 
370
447
  /**
371
- * Whether parameter `k`, raw, is exactly `text`.
448
+ * Whether parameter `k`, raw, is exactly `text`. Panics on a parameter the route does not have, a caller contract; `tryParam...` answers `Err` instead.
372
449
  * @param k the parameter's position in the route pattern, from 0
373
450
  * @param text the value to compare with, as it would appear still percent-encoded
374
451
  * @returns true when the raw parameter bytes are exactly `text`
375
452
  */
376
453
  paramIs(k: i32, text: string): boolean {
377
- this.checkParam(k)
378
- return handlerSpanIs(this.head, this.params[2 * k], this.params[2 * k + 1], text)
454
+ return handlerSpanIs(this.head, this.paramBound(k, HANDLER_ZERO), this.paramBound(k, toI32(1)), text)
379
455
  }
380
456
 
381
457
  /**
382
458
  * Parameter `k` percent-decoded into `out` from 0 (`routerDecode`): its
383
459
  * length, `ROUTER_BAD_ESCAPE` for a malformed escape, or `ROUTER_NO_ROOM`
384
- * when `out` is too short. Nothing is written on a code.
460
+ * when `out` is too short. Nothing is written on a code. Panics on a parameter the route does not have, a caller contract; `tryParam...` answers `Err` instead.
385
461
  * @param k the parameter's position in the route pattern, from 0
386
462
  * @param out where the decoded bytes go, from index 0; the caller's buffer
387
463
  * @returns how many decoded bytes were written, or a negative `ROUTER_*` code
388
464
  */
389
465
  param(k: i32, out: u8[]): i32 {
390
- this.checkParam(k)
391
- return routerDecode(this.head, this.params[2 * k], this.params[2 * k + 1], out)
466
+ return routerDecode(this.head, this.paramBound(k, HANDLER_ZERO), this.paramBound(k, toI32(1)), out)
392
467
  }
393
468
 
394
469
  /**
395
- * Parameter `k` read as a decimal number that is not negative and fits an `i32`, or -1.
470
+ * Parameter `k` read as a decimal number that is not negative and fits an
471
+ * `i32`, or -1. Panics on a parameter the route does not have, a caller contract; `tryParam...` answers `Err` instead.
396
472
  * @param k the parameter's position in the route pattern, from 0
397
473
  * @returns the number the parameter's digits spell, or -1 when it is empty, holds a non-digit or overflows
398
474
  */
399
475
  paramDecimal(k: i32): i32 {
400
- this.checkParam(k)
401
- return handlerDecimal(this.head, this.params[2 * k], this.params[2 * k + 1])
476
+ return handlerDecimal(this.head, this.paramBound(k, HANDLER_ZERO), this.paramBound(k, toI32(1)))
402
477
  }
403
478
 
404
- private checkParam(k: i32): void {
479
+ /**
480
+ * Where parameter `k` starts in `head`, or an error naming the parameter the route does not have.
481
+ * @param k the parameter's position in the route pattern, from 0
482
+ * @returns `Ok` with the byte offset in `head` of the parameter's first raw byte, or `Err` when the route has no parameter `k`
483
+ */
484
+ tryParamStart(k: i32): Result<i32, string> {
485
+ return this.tryParamBound(k, HANDLER_ZERO)
486
+ }
487
+
488
+ /**
489
+ * Where parameter `k` ends in `head`, or an error naming the parameter the route does not have.
490
+ * @param k the parameter's position in the route pattern, from 0
491
+ * @returns `Ok` with the byte offset in `head` just past the parameter's last raw byte, or `Err` when the route has no parameter `k`
492
+ */
493
+ tryParamEnd(k: i32): Result<i32, string> {
494
+ return this.tryParamBound(k, toI32(1))
495
+ }
496
+
497
+ /**
498
+ * Parameter `k` read as a decimal number, as `paramDecimal` reads it, or an
499
+ * error naming the parameter the route does not have.
500
+ * @param k the parameter's position in the route pattern, from 0
501
+ * @returns `Ok` with the number, or -1 when the parameter is empty, holds a non-digit or overflows; `Err` when the route has no parameter `k`
502
+ */
503
+ tryParamDecimal(k: i32): Result<i32, string> {
504
+ const start = this.tryParamBound(k, HANDLER_ZERO)
505
+ if (start.isErr()) {
506
+ return Err(start.error)
507
+ }
508
+ const end = this.tryParamBound(k, toI32(1))
509
+ if (end.isErr()) {
510
+ return Err(end.error)
511
+ }
512
+ return Ok(handlerDecimal(this.head, start.value, end.value))
513
+ }
514
+
515
+ /**
516
+ * Parameter `k`'s start (`side` 0) or end (`side` 1) in `head`: the one
517
+ * place the parameter contract panics.
518
+ */
519
+ private paramBound(k: i32, side: i32): i32 {
520
+ const bound: i32 = this.paramAt(k, side)
521
+ if (bound < 0) {
522
+ // A parameter the route does not have: the program's own mistake.
523
+ panic(this.paramFault(k))
524
+ }
525
+ return bound
526
+ }
527
+
528
+ /**
529
+ * Parameter `k`'s start (`side` 0) or end (`side` 1) in `head`, or why the
530
+ * route has no parameter `k`.
531
+ */
532
+ private tryParamBound(k: i32, side: i32): Result<i32, string> {
533
+ const bound: i32 = this.paramAt(k, side)
534
+ if (bound < 0) {
535
+ return Err(this.paramFault(k))
536
+ }
537
+ return Ok(bound)
538
+ }
539
+
540
+ /**
541
+ * Parameter `k`'s start (`side` 0) or end (`side` 1) in `head`, or -1 when
542
+ * the route has no parameter `k`: an offset in `head` is never negative, so
543
+ * -1 is no answer a span gives. It builds no `Result`, so the hot path
544
+ * allocates nothing. The literal bound on `k` comes first, so `2 * k + 1`
545
+ * is seen not to overflow; a route holds far fewer parameters.
546
+ */
547
+ private paramAt(k: i32, side: i32): i32 {
548
+ if (k < 0 || k >= this.paramCount || k > 65535) {
549
+ return -1
550
+ }
551
+ const at: i32 = 2 * k
552
+ if (at + 1 >= toI32(this.params.length)) {
553
+ return -1
554
+ }
555
+ return side === 0 ? this.params[at] : this.params[at + 1]
556
+ }
557
+
558
+ /** Why `paramAt` gave -1 for parameter `k`. */
559
+ private paramFault(k: i32): string {
405
560
  if (k < 0 || k >= this.paramCount) {
406
- panic(`HttpRequest.param: the route has ${this.paramCount} parameter(s), not one at ${k}`)
561
+ return `HttpRequest.param: the route has ${this.paramCount} parameter(s), not one at ${k}`
407
562
  }
563
+ if (k > 65535) {
564
+ return `HttpRequest.param: parameter ${k} is past the 65536 a route can hold`
565
+ }
566
+ return `HttpRequest.param: the request holds no span for parameter ${k}`
408
567
  }
409
568
 
410
569
  /**
@@ -419,11 +578,7 @@ export class HttpRequest {
419
578
  * @returns how many decoded bytes were written, or `HANDLER_ABSENT` or a negative `ROUTER_*` code
420
579
  */
421
580
  query(name: string, out: u8[]): i32 {
422
- const at: i32 = this.queryIndex(name)
423
- if (at < 0) {
424
- return HANDLER_ABSENT
425
- }
426
- return handlerFormDecode(this.head, this.queryValueStart, this.queryValueEnd, out)
581
+ return this.queryScan(name, out, true)
427
582
  }
428
583
 
429
584
  /**
@@ -446,25 +601,63 @@ export class HttpRequest {
446
601
  * @returns the byte offset in `head` where the matching `name=value` pair starts, or -1 when none matches
447
602
  */
448
603
  queryIndex(name: string): i32 {
449
- let at: i32 = this.pathEnd + 1
450
- const end: i32 = this.targetEnd
604
+ // Without `decode` the walk writes nothing to `out`.
605
+ return this.queryScan(name, this.head, false)
606
+ }
607
+
608
+ /**
609
+ * `queryIndex`'s walk: with `decode`, the matching value decoded into `out`
610
+ * as `query` answers it (`HANDLER_ABSENT` when none matches), else the
611
+ * pair's start or -1. The decode reads the span the walk proved inside
612
+ * `head`, so it needs no check of its own.
613
+ */
614
+ private queryScan(name: string, out: u8[], decode: boolean): i32 {
615
+ const none: i32 = decode ? HANDLER_ABSENT : -1
616
+ // The target lies inside `head`; the bound says so to the prover.
617
+ const length: i32 = toI32(this.head.length)
618
+ const end: i32 = this.targetEnd < length ? this.targetEnd : length
619
+ // A path that runs to the target's end has no query.
620
+ const pathEnd: i32 = this.pathEnd
621
+ if (pathEnd < 0 || pathEnd >= end || pathEnd >= length) {
622
+ return none
623
+ }
624
+ let at: i32 = pathEnd + 1
451
625
  while (at < end) {
452
626
  let pairEnd: i32 = at
453
- while (pairEnd < end && toI32(this.head[pairEnd]) !== 38) {
627
+ while (
628
+ pairEnd >= 0 &&
629
+ pairEnd < end &&
630
+ pairEnd < toI32(this.head.length) &&
631
+ toI32(this.head[pairEnd]) !== 38
632
+ ) {
454
633
  pairEnd += 1
455
634
  }
456
635
  let keyEnd: i32 = at
457
- while (keyEnd < pairEnd && toI32(this.head[keyEnd]) !== 61) {
636
+ while (
637
+ keyEnd >= 0 &&
638
+ keyEnd < pairEnd &&
639
+ keyEnd < toI32(this.head.length) &&
640
+ toI32(this.head[keyEnd]) !== 61
641
+ ) {
458
642
  keyEnd += 1
459
643
  }
460
644
  if (handlerFormIs(this.head, at, keyEnd, name)) {
461
- this.queryValueStart = keyEnd < pairEnd ? keyEnd + 1 : pairEnd
645
+ // A pair with no `=` has an empty value, at its end. The length is
646
+ // worked in 64 bits: both ends lie inside `head`, so it is exact, but
647
+ // the prover keeps no lower bound on `keyEnd` across the loop.
648
+ const valueStart: i32 = keyEnd < pairEnd ? keyEnd + 1 : pairEnd
649
+ const valueLength: i32 = keyEnd < pairEnd ? toI32(toI64(pairEnd) - toI64(keyEnd) - 1) : 0
650
+ this.queryValueStart = valueStart
462
651
  this.queryValueEnd = pairEnd
463
- return at
652
+ return decode ? handlerFormDecode(this.head, valueStart, valueLength, out) : at
653
+ }
654
+ // The last pair ends the query.
655
+ if (pairEnd >= end) {
656
+ return none
464
657
  }
465
658
  at = pairEnd + 1
466
659
  }
467
- return -1
660
+ return none
468
661
  }
469
662
 
470
663
  /**
@@ -473,30 +666,95 @@ export class HttpRequest {
473
666
  * @returns the field's index for `valueStart` and `valueEnd`, or `HANDLER_ABSENT` when no field has the name
474
667
  */
475
668
  header(name: string): i32 {
476
- for (let i: i32 = 0; i < this.headerCount; i++) {
477
- if (handlerSpanIs(this.head, this.spans[4 * i], this.spans[4 * i + 1], name)) {
669
+ // `at` steps four slots a field, so it is `4 * i` without the product;
670
+ // the literal bound keeps the step from overflowing.
671
+ let at: i32 = 0
672
+ for (let i: i32 = 0; i < this.headerCount && at < 1048576 && at + 1 < toI32(this.spans.length); i++) {
673
+ if (handlerSpanIs(this.head, this.spans[at], this.spans[at + 1], name)) {
478
674
  return i
479
675
  }
676
+ at += 4
480
677
  }
481
678
  return HANDLER_ABSENT
482
679
  }
483
680
 
484
681
  /**
485
- * Where field `i`'s value starts in `head`.
682
+ * Where field `i`'s value starts in `head`. Panics on an `i` that is not a
683
+ * field index, a caller contract: pass only what `header` answered, after
684
+ * checking it is not `HANDLER_ABSENT`.
486
685
  * @param i a field index, as `header` answered it
487
686
  * @returns the byte offset in `head` of the value's first byte
488
687
  */
489
688
  valueStart(i: i32): i32 {
490
- return this.spans[4 * i + 2]
689
+ return this.valueBound(i, toI32(2))
491
690
  }
492
691
 
493
692
  /**
494
- * Where field `i`'s value ends in `head`.
693
+ * Where field `i`'s value ends in `head`. Panics on an `i` that is not a
694
+ * field index, a caller contract: pass only what `header` answered, after
695
+ * checking it is not `HANDLER_ABSENT`.
495
696
  * @param i a field index, as `header` answered it
496
697
  * @returns the byte offset in `head` just past the value's last byte
497
698
  */
498
699
  valueEnd(i: i32): i32 {
499
- return this.spans[4 * i + 3]
700
+ return this.valueBound(i, toI32(3))
701
+ }
702
+
703
+ /**
704
+ * Where field `i`'s value starts in `head`, or an error when `i` is not a
705
+ * field index `header` answered.
706
+ * @param i a field index, as `header` answered it
707
+ * @returns `Ok` with the byte offset in `head` of the value's first byte, or `Err` naming `i`
708
+ */
709
+ tryValueStart(i: i32): Result<i32, string> {
710
+ return this.tryValueBound(i, toI32(2))
711
+ }
712
+
713
+ /**
714
+ * Where field `i`'s value ends in `head`, or an error when `i` is not a
715
+ * field index `header` answered.
716
+ * @param i a field index, as `header` answered it
717
+ * @returns `Ok` with the byte offset in `head` just past the value's last byte, or `Err` naming `i`
718
+ */
719
+ tryValueEnd(i: i32): Result<i32, string> {
720
+ return this.tryValueBound(i, toI32(3))
721
+ }
722
+
723
+ /** Field `i`'s value start (`part` 2) or end (`part` 3): the one place the field contract panics. */
724
+ private valueBound(i: i32, part: i32): i32 {
725
+ const bound: i32 = this.valueAt(i, part)
726
+ if (bound < 0) {
727
+ // A field index `header` did not answer: the program's own mistake.
728
+ panic(this.valueFault(i))
729
+ }
730
+ return bound
731
+ }
732
+
733
+ /** Field `i`'s value start (`part` 2) or end (`part` 3) in `head`, or why `i` is no field index. */
734
+ private tryValueBound(i: i32, part: i32): Result<i32, string> {
735
+ const bound: i32 = this.valueAt(i, part)
736
+ if (bound < 0) {
737
+ return Err(this.valueFault(i))
738
+ }
739
+ return Ok(bound)
740
+ }
741
+
742
+ /**
743
+ * Field `i`'s value start (`part` 2) or end (`part` 3) in `head`, or -1 when
744
+ * `i` is no field index: an offset in `head` is never negative. It builds
745
+ * no `Result`, so the hot path allocates nothing.
746
+ */
747
+ private valueAt(i: i32, part: i32): i32 {
748
+ const at: i32 = handlerSpanSlot(i, part)
749
+ if (i < 0 || i >= this.headerCount || at < 0 || at >= toI32(this.spans.length)) {
750
+ return -1
751
+ }
752
+ return this.spans[at]
753
+ }
754
+
755
+ /** Why `valueAt` gave -1 for field `i`. */
756
+ private valueFault(i: i32): string {
757
+ return `HttpRequest.value: ${i} is not a field index of the ${this.headerCount} \`header\` answers`
500
758
  }
501
759
 
502
760
  /**
@@ -506,14 +764,37 @@ export class HttpRequest {
506
764
  * @returns true when the field is present and its first occurrence has exactly that value
507
765
  */
508
766
  headerIs(name: string, value: string): boolean {
767
+ // An absent field (`HANDLER_ABSENT`) is no field index: both answer -1.
509
768
  const i: i32 = this.header(name)
510
- return i >= 0 && handlerSpanIs(this.head, this.spans[4 * i + 2], this.spans[4 * i + 3], value)
769
+ const start: i32 = this.valueAt(i, toI32(2))
770
+ const end: i32 = this.valueAt(i, toI32(3))
771
+ if (start < 0 || end < 0) {
772
+ return false
773
+ }
774
+ return handlerSpanIs(this.head, start, end, value)
511
775
  }
512
776
  }
513
777
 
514
778
  /**
515
779
  * The HTTP/1.1 server: a carrier, its readiness loop, a router and a pool of
516
780
  * requests. One per thread; nothing in it is shared.
781
+ *
782
+ * A `try` twin refuses a broken contract with an `Err`, and what it leaves
783
+ * depends on whether the response's head went out:
784
+ *
785
+ * - **Refused before the head** — a request not taken or already answered,
786
+ * a status outside 200 to 599, a one-shot answer's body window outside its
787
+ * buffer (`trySend`): nothing is sent and `r` is as it was, so a request
788
+ * still owed an answer can be answered again (a bare 500, say).
789
+ * - **Abandoned after the head** — a head the carrier refuses (a reserved
790
+ * field, a name or value that is not field text), a `tryWrite` window
791
+ * outside its buffer or more body than the declared length (the head went
792
+ * out with `tryStart`, so these fall here, not above), or a body short of
793
+ * it (`tryEnd`): the response cannot be completed, so the connection is
794
+ * closed and `r` is the handler's again. Nothing more is owed for `r`; a
795
+ * further answer for it is refused too.
796
+ *
797
+ * The plain methods panic with the same message where their twins refuse.
517
798
  */
518
799
  export class HttpHandler {
519
800
  /**
@@ -558,7 +839,12 @@ export class HttpHandler {
558
839
  private allowBytes: u8[][]
559
840
  private jsonType: u8[]
560
841
  private problemType: u8[]
842
+ /** Decodes `gzip` and `deflate` bodies under `HandlerLimits.maxDecoded`. */
843
+ private decoder: HttpBodyDecoder
561
844
  private noFields: u8[][]
845
+ /** Per length: the array `start` gathers an answer's fields and the fields `field` added into, kept for the answers after. */
846
+ private namesBy: u8[][][]
847
+ private valuesBy: u8[][][]
562
848
  /**
563
849
  * When an accept failed for want of a resource (EMFILE for descriptors,
564
850
  * ENFILE for ring slots, ENOMEM): the listener is out of the loop until
@@ -584,6 +870,8 @@ export class HttpHandler {
584
870
  private queueStart: i32 = 0
585
871
  private queueCount: i32 = 0
586
872
  private owedCount: i32 = 0
873
+ /** `HandlerLimits.maxDecoded`, 0 to decode nothing. */
874
+ private maxDecoded: i32 = 0
587
875
  private sent: i64 = 0
588
876
  private outputSize: i32 = 0
589
877
  /** Set by `drain`: accept nothing more and close each connection once it is idle. */
@@ -592,6 +880,8 @@ export class HttpHandler {
592
880
  private deferring: boolean = false
593
881
  /** Whether `json` gave out the writer for a value `sendJson` has not yet sent. */
594
882
  private jsonBegun: boolean = false
883
+ /** Why the last core answered `HANDLER_REFUSED`. */
884
+ private refusal: string = ""
595
885
 
596
886
  /**
597
887
  * A handler over `listener`, a listening socket the program made
@@ -606,13 +896,19 @@ export class HttpHandler {
606
896
  * caps live
607
897
  * @param listener the listening socket's descriptor, still the program's to close
608
898
  * @param router the routes, which the handler keeps and consults at each request head
609
- */
610
- constructor(limits: HandlerLimits, listener: i32, router: Router) {
611
- if (limits.slots < 1 || limits.jsonBytes < 256 || limits.maxEvents < 1 || limits.bodyTimeout < 1) {
612
- panic(
613
- `HttpHandler: slots ${limits.slots}, jsonBytes ${limits.jsonBytes}, maxEvents ${limits.maxEvents} and bodyTimeout ${limits.bodyTimeout} need at least 1, 256, 1 and 1`
614
- )
615
- }
899
+ * @param loop a readiness loop from `pollCreate` for the handler to own, or
900
+ * -1 (the default) to make one here; any other negative is a failed
901
+ * `pollCreate` passed through. Panics on limits below their least and on
902
+ * a failed loop, each a contract of this constructor: use
903
+ * `openHttpHandler` for a `Result`.
904
+ */
905
+ constructor(limits: HandlerLimits, listener: i32, router: Router, loop: i32 = -1) {
906
+ const fault: string = handlerLimitsFault(limits)
907
+ if (fault.length > 0) {
908
+ panic(fault)
909
+ }
910
+ this.maxDecoded = limits.maxDecoded
911
+ this.decoder = new HttpBodyDecoder(limits.maxDecoded > 0 ? limits.maxDecoded : 1)
616
912
  this.bodyTimeout = toI64(limits.bodyTimeout) * HANDLER_NANOS_PER_MS
617
913
  this.server = new Http1Server(limits.http, listener, limits.slots)
618
914
  this.router = router
@@ -621,19 +917,16 @@ export class HttpHandler {
621
917
  this.requests = []
622
918
  this.free = []
623
919
  this.queue = new Array<i32>(16)
624
- this.slotGen = new Array<i32>(limits.slots)
625
- this.current = new Array<i32>(limits.slots)
626
- this.open = new Array<boolean>(limits.slots)
627
- this.owing = new Array<boolean>(limits.slots)
628
- this.owed = new Array<i32>(limits.slots)
629
- for (let s: i32 = 0; s < limits.slots; s++) {
630
- this.current[s] = -1
631
- }
632
- this.readyFds = new Array<i32>(2 * limits.maxEvents)
633
- this.watchedFired = new Array<boolean>(HANDLER_MAX_WATCHED)
634
- this.scratch = new Array<u8>(limits.jsonBytes)
920
+ this.slotGen = handlerInts(limits.slots, HANDLER_ZERO)
921
+ this.current = handlerInts(limits.slots, -1)
922
+ this.open = handlerFlags(limits.slots)
923
+ this.owing = handlerFlags(limits.slots)
924
+ this.owed = handlerInts(limits.slots, HANDLER_ZERO)
925
+ this.readyFds = handlerInts(handlerAdd(limits.maxEvents, limits.maxEvents), HANDLER_ZERO)
926
+ this.watchedFired = handlerFlags(HANDLER_MAX_WATCHED)
927
+ this.scratch = handlerBytes(limits.jsonBytes)
635
928
  this.writer = new JsonWriter(this.scratch, HANDLER_ZERO)
636
- this.probe = new Array<i32>(2 * router.maxParams + 2)
929
+ this.probe = handlerInts(handlerProbeLength(router.maxParams), HANDLER_ZERO)
637
930
  this.jsonType = httpFieldBytes("application/json")
638
931
  this.problemType = httpFieldBytes("application/problem+json")
639
932
  const contentType: u8[] = httpFieldBytes("content-type")
@@ -645,7 +938,9 @@ export class HttpHandler {
645
938
  this.allowMasks = []
646
939
  this.allowBytes = []
647
940
  this.noFields = []
648
- this.loop = pollCreate()
941
+ this.namesBy = []
942
+ this.valuesBy = []
943
+ this.loop = loop === -1 ? pollCreate() : loop
649
944
  if (this.loop < 0) {
650
945
  panic(`HttpHandler: pollCreate failed: ${this.loop}`)
651
946
  }
@@ -669,13 +964,29 @@ export class HttpHandler {
669
964
  pollAdd(this.loop, fd, H1_WANT_READ, -2 - id)
670
965
  }
671
966
 
967
+ /**
968
+ * `watch`, with an id outside the range answered as an `Err` instead of a panic.
969
+ * @param fd the program's descriptor to watch for reading; it stays the program's to read and close
970
+ * @param id the name `fired` asks about it by, from 0 to `HANDLER_MAX_WATCHED - 1`
971
+ * @returns `Ok(true)` once `fd` is watched, or `Err` naming the id outside the range
972
+ */
973
+ tryWatch(fd: i32, id: i32): Result<boolean, string> {
974
+ if (id < 0 || id >= HANDLER_MAX_WATCHED) {
975
+ return Err(`HttpHandler.watch: id ${id} is outside 0 to ${HANDLER_MAX_WATCHED - 1}`)
976
+ }
977
+ pollAdd(this.loop, fd, H1_WANT_READ, -2 - id)
978
+ return Ok(true)
979
+ }
980
+
672
981
  /**
673
982
  * Whether watched descriptor `id` was ready in the last `wait`.
674
983
  * @param id the name the descriptor was given to `watch`
675
984
  * @returns true when it was readable in the last turn; false for an id outside the range
676
985
  */
677
986
  fired(id: i32): boolean {
678
- return id >= 0 && id < HANDLER_MAX_WATCHED && this.watchedFired[id]
987
+ return (
988
+ id >= 0 && id < HANDLER_MAX_WATCHED && id < toI32(this.watchedFired.length) && this.watchedFired[id]
989
+ )
679
990
  }
680
991
 
681
992
  /**
@@ -688,8 +999,9 @@ export class HttpHandler {
688
999
  */
689
1000
  wait(timeoutMs: i32): i32 {
690
1001
  this.flush()
691
- for (let id: i32 = 0; id < HANDLER_MAX_WATCHED; id++) {
692
- this.watchedFired[id] = false
1002
+ const fired: boolean[] = this.watchedFired
1003
+ for (let id: i32 = 0; id < HANDLER_MAX_WATCHED && id < toI32(fired.length); id++) {
1004
+ fired[id] = false
693
1005
  }
694
1006
  if (this.acceptRestUntil > 0 && monotonicNanos() >= this.acceptRestUntil) {
695
1007
  this.endAcceptRest()
@@ -697,7 +1009,10 @@ export class HttpHandler {
697
1009
  let timeout: i32 = timeoutMs
698
1010
  if (this.acceptRestUntil > 0 && !this.draining) {
699
1011
  // Wake for the listener's return, whatever the program asked.
700
- const rest: i32 = toI32((this.acceptRestUntil - monotonicNanos()) / toI64(1000000)) + 1
1012
+ const rest: i32 = handlerAdd(
1013
+ toI32(handlerSince(monotonicNanos(), this.acceptRestUntil) / toI64(1000000)),
1014
+ 1
1015
+ )
701
1016
  if (timeout < 0 || rest < timeout) {
702
1017
  timeout = rest
703
1018
  }
@@ -711,17 +1026,24 @@ export class HttpHandler {
711
1026
  const n: i32 = pollWait(this.loop, this.readyFds, timeout)
712
1027
  const now: i64 = monotonicNanos()
713
1028
  this.turnAt = now
714
- for (let k: i32 = 0; k < n; k++) {
715
- const token: i32 = this.readyFds[2 * k]
1029
+ const fds: i32[] = this.readyFds
1030
+ // Two numbers an event; the literal bound keeps `2 * k + 1` in an `i32`.
1031
+ for (let k: i32 = 0; k < n && k < 1048576; k++) {
1032
+ const at: i32 = 2 * k
1033
+ if (at + 1 >= toI32(fds.length)) {
1034
+ break
1035
+ }
1036
+ const token: i32 = fds[at]
1037
+ const bits: i32 = fds[at + 1]
716
1038
  if (token === HANDLER_LISTENER) {
717
1039
  this.acceptAll()
718
1040
  } else if (token <= -2) {
719
- const id: i32 = -2 - token
720
- if (id < HANDLER_MAX_WATCHED) {
721
- this.watchedFired[id] = true
1041
+ const id: i32 = handlerSub(-2, token)
1042
+ if (id >= 0 && id < HANDLER_MAX_WATCHED && id < toI32(fired.length)) {
1043
+ fired[id] = true
722
1044
  }
723
1045
  } else if (token >= 0 && this.server.holds(token)) {
724
- if ((this.readyFds[2 * k + 1] & HANDLER_READ_BITS) !== 0) {
1046
+ if ((bits & HANDLER_READ_BITS) !== 0) {
725
1047
  this.server.readable(token)
726
1048
  } else {
727
1049
  this.server.writable(token)
@@ -733,7 +1055,7 @@ export class HttpHandler {
733
1055
  this.sweep()
734
1056
  }
735
1057
  if (now >= this.bodyCheckAt) {
736
- this.bodyCheckAt = now + HANDLER_BODY_SWEEP
1058
+ this.bodyCheckAt = handlerLater(now, HANDLER_BODY_SWEEP)
737
1059
  this.expireBodies(now)
738
1060
  }
739
1061
  return this.queueCount
@@ -765,15 +1087,19 @@ export class HttpHandler {
765
1087
  if (this.acceptRestUntil === 0) {
766
1088
  pollRemove(this.loop, this.listener)
767
1089
  }
768
- for (let s: i32 = 0; s < toI32(this.open.length) && s < toI32(this.current.length); s++) {
1090
+ const open: boolean[] = this.open
1091
+ const current: i32[] = this.current
1092
+ for (let s: i32 = 0; s < toI32(open.length) && s < toI32(current.length); s++) {
1093
+ const isOpen: boolean = open[s]
1094
+ const idle: boolean = current[s] === -1
769
1095
  if (
770
- this.open[s] &&
1096
+ isOpen &&
771
1097
  this.server.holds(s) &&
772
- this.current[s] === -1 &&
1098
+ idle &&
773
1099
  (this.server.resting(s) || !this.server.connection(s).wantsWrite())
774
1100
  ) {
775
1101
  this.closeSlot(s)
776
- } else if (this.open[s] && this.server.holds(s)) {
1102
+ } else if (isOpen && this.server.holds(s)) {
777
1103
  // Its exchange is its last: the answer says `Connection: close` if
778
1104
  // it is not yet started, and no pipelined request is read behind it.
779
1105
  this.server.connection(s).closeAfter = true
@@ -788,9 +1114,12 @@ export class HttpHandler {
788
1114
  }
789
1115
  let slot: i32 = this.server.accept()
790
1116
  while (slot >= 0 || slot === H1_POOL_FULL || slot === HANDLER_ACCEPT_ABORTED) {
791
- if (slot >= 0) {
792
- this.open[slot] = true
793
- this.current[slot] = -1
1117
+ const open: boolean[] = this.open
1118
+ const current: i32[] = this.current
1119
+ // The carrier hands only its own slots, each with a place in both.
1120
+ if (slot >= 0 && slot < toI32(open.length) && slot < toI32(current.length)) {
1121
+ open[slot] = true
1122
+ current[slot] = -1
794
1123
  pollAdd(this.loop, this.server.fd(slot), H1_WANT_READ, slot)
795
1124
  }
796
1125
  slot = this.server.accept()
@@ -800,7 +1129,7 @@ export class HttpHandler {
800
1129
  // stays in the backlog and the listener stays readable, so rest it
801
1130
  // rather than spin, until a close frees one or the rest ends.
802
1131
  pollRemove(this.loop, this.listener)
803
- this.acceptRestUntil = monotonicNanos() + HANDLER_ACCEPT_REST
1132
+ this.acceptRestUntil = handlerLater(monotonicNanos(), HANDLER_ACCEPT_REST)
804
1133
  }
805
1134
  }
806
1135
 
@@ -812,10 +1141,16 @@ export class HttpHandler {
812
1141
  flush(): void {
813
1142
  const n: i32 = this.owedCount
814
1143
  this.owedCount = 0
815
- for (let k: i32 = 0; k < n; k++) {
816
- const slot: i32 = this.owed[k]
817
- this.owing[slot] = false
818
- if (this.open[slot] && this.server.holds(slot)) {
1144
+ const owed: i32[] = this.owed
1145
+ const owing: boolean[] = this.owing
1146
+ const open: boolean[] = this.open
1147
+ for (let k: i32 = 0; k < n && k < toI32(owed.length); k++) {
1148
+ const slot: i32 = owed[k]
1149
+ if (slot < 0 || slot >= toI32(owing.length) || slot >= toI32(open.length)) {
1150
+ continue
1151
+ }
1152
+ owing[slot] = false
1153
+ if (open[slot] && this.server.holds(slot)) {
819
1154
  this.settle(slot, this.server.connection(slot))
820
1155
  }
821
1156
  }
@@ -854,13 +1189,18 @@ export class HttpHandler {
854
1189
  // The carrier has written its refusal and ends the connection; a
855
1190
  // request it was reading is nobody's.
856
1191
  this.releaseReading(slot)
857
- } else if (this.owable(slot, conn)) {
858
- if (!this.owing[slot]) {
1192
+ } else if (this.owable(slot, conn) && slot >= 0 && slot < toI32(this.owing.length)) {
1193
+ if (this.owing[slot]) {
1194
+ return
1195
+ }
1196
+ // `owed` has a place for every slot and holds each at most once, so `n` is in range.
1197
+ const n: i32 = this.owedCount
1198
+ if (n >= 0 && n < toI32(this.owed.length)) {
859
1199
  this.owing[slot] = true
860
- this.owed[this.owedCount] = slot
861
- this.owedCount += 1
1200
+ this.owed[n] = slot
1201
+ this.owedCount = n + 1
1202
+ return
862
1203
  }
863
- return
864
1204
  }
865
1205
  this.settle(slot, conn)
866
1206
  }
@@ -877,21 +1217,48 @@ export class HttpHandler {
877
1217
  * the handler waits.
878
1218
  */
879
1219
  private owable(slot: i32, conn: Http1Connection): boolean {
880
- const at: i32 = this.current[slot]
1220
+ const r: HttpRequest | null = this.requestAt(this.currentOf(slot))
881
1221
  return (
882
1222
  this.deferring &&
883
1223
  !this.draining &&
884
1224
  conn.wantsWrite() &&
885
1225
  !conn.writeHeld &&
886
1226
  this.roomy(conn) &&
887
- (at < 0 || this.requests[at].state !== HANDLER_PARKED)
1227
+ (r === null || r.state !== HANDLER_PARKED)
888
1228
  )
889
1229
  }
890
1230
 
1231
+ /** The index of the request `slot` is reading or answering, or -1 for none (or a slot out of range). */
1232
+ private currentOf(slot: i32): i32 {
1233
+ return slot >= 0 && slot < toI32(this.current.length) ? this.current[slot] : -1
1234
+ }
1235
+
1236
+ /** The request at index `at`, or null for -1 (or an index out of range). */
1237
+ private requestAt(at: i32): HttpRequest | null {
1238
+ return at >= 0 && at < toI32(this.requests.length) ? this.requests[at] : null
1239
+ }
1240
+
1241
+ /** The request at the head of the queue, or null when the queue is empty. */
1242
+ private queued(): HttpRequest | null {
1243
+ const start: i32 = this.queueStart
1244
+ if (this.queueCount <= 0 || start < 0 || start >= toI32(this.queue.length)) {
1245
+ return null
1246
+ }
1247
+ return this.requestAt(this.queue[start])
1248
+ }
1249
+
1250
+ /** Drops the request at the head of the queue. */
1251
+ private dequeue(): void {
1252
+ this.queueStart = handlerRing(this.queueStart, 1, toI32(this.queue.length))
1253
+ this.queueCount = handlerSub(this.queueCount, 1)
1254
+ }
1255
+
891
1256
  /** Sends what `slot` holds and re-arms it, or closes it once it is over; enqueues a parked request once there is room. */
892
1257
  private settle(slot: i32, conn: Http1Connection): void {
893
1258
  if (conn.wantsWrite()) {
894
- this.sent += 1
1259
+ // Worked in `u64`, whose wrapping sum has the bits of the signed one: a
1260
+ // count of sends is centuries short of 2^63.
1261
+ this.sent = toI64(toU64(this.sent) + toU64(1))
895
1262
  }
896
1263
  // `flush` arms a held write for writing even once its send emptied the output.
897
1264
  const wants: i32 = this.server.flush(slot)
@@ -899,26 +1266,34 @@ export class HttpHandler {
899
1266
  this.closeSlot(slot)
900
1267
  return
901
1268
  }
902
- if (this.draining && this.current[slot] === -1 && !conn.wantsWrite()) {
1269
+ if (this.draining && this.currentOf(slot) === -1 && !conn.wantsWrite()) {
903
1270
  this.closeSlot(slot)
904
1271
  return
905
1272
  }
906
1273
  if (this.server.rearm(slot, wants)) {
907
1274
  pollModify(this.loop, this.server.fd(slot), wants & (H1_WANT_READ | H1_WANT_WRITE), slot)
908
1275
  }
909
- const at: i32 = this.current[slot]
910
- if (at >= 0 && this.requests[at].state === HANDLER_PARKED && this.roomy(conn)) {
911
- this.enqueue(this.requests[at])
1276
+ const r: HttpRequest | null = this.requestAt(this.currentOf(slot))
1277
+ if (r !== null && r.state === HANDLER_PARKED && this.roomy(conn)) {
1278
+ this.enqueue(r)
912
1279
  }
913
1280
  }
914
1281
 
915
1282
  /** Whether `conn`'s output holds at most half its size unsent, so a response head fits behind it. */
916
1283
  private roomy(conn: Http1Connection): boolean {
917
- return (conn.outputEnd - conn.outputStart) * 2 <= this.outputSize
1284
+ // `2 * unsent <= size` is `unsent <= size / 2` for whole numbers, without the doubling.
1285
+ return toI64(conn.outputEnd) - toI64(conn.outputStart) <= toI64(this.outputSize) / toI64(2)
918
1286
  }
919
1287
 
920
1288
  /** A head: a request from the free list, the head copied into it, and its route. */
921
1289
  private begin(slot: i32, conn: Http1Connection): void {
1290
+ const current: i32[] = this.current
1291
+ const slotGen: i32[] = this.slotGen
1292
+ // `drive` hands only the carrier's slots, each with a place in both.
1293
+ if (slot < 0 || slot >= toI32(current.length) || slot >= toI32(slotGen.length)) {
1294
+ return
1295
+ }
1296
+ const gen: i32 = slotGen[slot]
922
1297
  if (this.draining) {
923
1298
  // A head read during the drain is the connection's last.
924
1299
  conn.closeAfter = true
@@ -927,15 +1302,18 @@ export class HttpHandler {
927
1302
  const p = conn.parser
928
1303
  const length: i32 = p.headLength
929
1304
  if (toI32(r.head.length) < length) {
930
- r.head = new Array<u8>(handlerGrown(toI32(r.head.length), length))
1305
+ r.head = handlerBytes(handlerGrown(toI32(r.head.length), length))
931
1306
  }
932
1307
  copyBytes(r.head, HANDLER_ZERO, p.head, HANDLER_ZERO, length)
933
- // The parser's spans are copied whole, as one `set`: only the first
934
- // `4 * headerCount` are this head's, and only those are ever read.
935
- if (toI32(r.spans.length) < toI32(p.spans.length)) {
936
- r.spans = new Array<i32>(handlerGrown(toI32(r.spans.length), toI32(p.spans.length)))
1308
+ // Only the first `4 * headerCount` spans are this head's, and only those
1309
+ // are ever read, so only those are copied.
1310
+ const spanCount: i32 = handlerSpanSlot(p.headerCount, 0)
1311
+ if (toI32(r.spans.length) < spanCount) {
1312
+ r.spans = handlerInts(handlerGrown(toI32(r.spans.length), spanCount), HANDLER_ZERO)
1313
+ }
1314
+ for (let k: i32 = 0; k < spanCount && k < toI32(r.spans.length) && k < toI32(p.spans.length); k++) {
1315
+ r.spans[k] = p.spans[k]
937
1316
  }
938
- r.spans.set(p.spans)
939
1317
  r.headLength = length
940
1318
  r.headerCount = p.headerCount
941
1319
  r.methodStart = p.methodStart
@@ -943,16 +1321,22 @@ export class HttpHandler {
943
1321
  r.targetStart = p.targetStart
944
1322
  r.targetEnd = p.targetEnd
945
1323
  r.bodyLength = 0
1324
+ r.decodedFrom = HTTP_CODING_IDENTITY
1325
+ r.refusal = 0
946
1326
  r.slot = slot
947
- r.gen = this.slotGen[slot]
1327
+ r.gen = gen
948
1328
  r.since = this.turnAt
949
1329
  r.state = HANDLER_READING
950
1330
  r.pendingStart = 0
951
1331
  r.pendingEnd = 0
1332
+ r.stepped = false
1333
+ r.added = 0
952
1334
  this.route(r)
953
1335
  // The router found where the path ends, before any query, as it matched.
954
1336
  r.pathEnd = this.router.pathEnd
955
- this.current[slot] = r.index
1337
+ if (slot < toI32(current.length)) {
1338
+ current[slot] = r.index
1339
+ }
956
1340
  }
957
1341
 
958
1342
  /**
@@ -973,7 +1357,11 @@ export class HttpHandler {
973
1357
  )
974
1358
  if (route === ROUTER_METHOD_NOT_ALLOWED && r.methodIs("HEAD")) {
975
1359
  const get: i32 = this.router.methodIndex("GET")
976
- if (get >= 0) {
1360
+ if (
1361
+ get >= 0 &&
1362
+ get < toI32(this.router.methodStart.length) &&
1363
+ get < toI32(this.router.methodEnd.length)
1364
+ ) {
977
1365
  const viaGet: i32 = this.router.match(
978
1366
  this.router.methodBytes,
979
1367
  this.router.methodStart[get],
@@ -994,15 +1382,18 @@ export class HttpHandler {
994
1382
 
995
1383
  /** Body bytes: appended to the request's body, which the carrier's cap bounds. */
996
1384
  private gather(slot: i32, conn: Http1Connection): void {
997
- const at: i32 = this.current[slot]
998
- if (at < 0) {
1385
+ const r: HttpRequest | null = this.requestAt(this.currentOf(slot))
1386
+ if (r === null) {
999
1387
  return
1000
1388
  }
1001
- const r: HttpRequest = this.requests[at]
1002
1389
  const n: i32 = conn.dataLength
1003
- const need: i32 = r.bodyLength + n
1390
+ // The carrier's cap keeps a body far below 2^31 bytes.
1391
+ const need: i32 = handlerAdd(r.bodyLength, n)
1392
+ if (need < 0) {
1393
+ return
1394
+ }
1004
1395
  if (toI32(r.body.length) < need) {
1005
- const grown: u8[] = new Array<u8>(handlerGrown(toI32(r.body.length), need))
1396
+ const grown: u8[] = handlerBytes(handlerGrown(toI32(r.body.length), need))
1006
1397
  copyBytes(grown, HANDLER_ZERO, r.body, HANDLER_ZERO, r.bodyLength)
1007
1398
  r.body = grown
1008
1399
  }
@@ -1012,11 +1403,11 @@ export class HttpHandler {
1012
1403
 
1013
1404
  /** The request is whole: queued for `take`, or parked while the response before it is still mostly unsent. */
1014
1405
  private whole(slot: i32, conn: Http1Connection): void {
1015
- const at: i32 = this.current[slot]
1016
- if (at < 0) {
1406
+ const r: HttpRequest | null = this.requestAt(this.currentOf(slot))
1407
+ if (r === null) {
1017
1408
  return
1018
1409
  }
1019
- const r: HttpRequest = this.requests[at]
1410
+ this.decode(r)
1020
1411
  if (this.roomy(conn)) {
1021
1412
  this.enqueue(r)
1022
1413
  } else {
@@ -1024,28 +1415,77 @@ export class HttpHandler {
1024
1415
  }
1025
1416
  }
1026
1417
 
1418
+ /**
1419
+ * Decodes `r`'s body when its one `Content-Encoding` is gzip or deflate,
1420
+ * swapping the decoded bytes in as its body; a body that decodes past
1421
+ * `maxDecoded`, or not at all, is marked for `ready` to refuse.
1422
+ */
1423
+ private decode(r: HttpRequest): void {
1424
+ if (this.maxDecoded === 0 || r.bodyLength === 0) {
1425
+ return
1426
+ }
1427
+ let coding: i32 = HTTP_CODING_IDENTITY
1428
+ const spans: i32[] = r.spans
1429
+ for (let i: i32 = 0; i < r.headerCount; i++) {
1430
+ // A head's spans are four a field; the literal bound keeps `at + 3` in an `i32`.
1431
+ const at: i32 = handlerSpanSlot(i, 0)
1432
+ if (at < 0 || at > 1048576 || at + 3 >= toI32(spans.length)) {
1433
+ break
1434
+ }
1435
+ const valueStart: i32 = spans[at + 2]
1436
+ const valueEnd: i32 = spans[at + 3]
1437
+ if (handlerSpanIs(r.head, spans[at], spans[at + 1], "content-encoding")) {
1438
+ const named: i32 = httpContentEncoding(r.head, valueStart, valueEnd)
1439
+ // A second field stacks its codings on the first's (RFC 9110 §5.3).
1440
+ coding = coding === HTTP_CODING_IDENTITY ? named : HTTP_CODING_NONE
1441
+ }
1442
+ }
1443
+ if (coding !== HTTP_CODING_GZIP && coding !== HTTP_CODING_DEFLATE) {
1444
+ return
1445
+ }
1446
+ const got: i32 = this.decoder.decode(coding, r.body, HANDLER_ZERO, r.bodyLength)
1447
+ if (got < 0) {
1448
+ r.refusal = got === HTTP_DECODE_TOO_LARGE ? toI32(413) : toI32(400)
1449
+ return
1450
+ }
1451
+ // The buffers change hands, so neither is copied or grown twice.
1452
+ const decoded: u8[] = this.decoder.output
1453
+ this.decoder.output = r.body
1454
+ r.body = decoded
1455
+ r.bodyLength = got
1456
+ r.decodedFrom = coding
1457
+ }
1458
+
1027
1459
  private enqueue(r: HttpRequest): void {
1028
1460
  r.state = HANDLER_QUEUED
1029
- const size: i32 = toI32(this.queue.length)
1030
- if (this.queueCount === size) {
1031
- const grown: i32[] = new Array<i32>(2 * size)
1461
+ const old: i32[] = this.queue
1462
+ const size: i32 = toI32(old.length)
1463
+ if (this.queueCount >= size) {
1464
+ const grown: i32[] = handlerInts(handlerAdd(size, size), -1)
1032
1465
  for (let k: i32 = 0; k < size && k < toI32(grown.length); k++) {
1033
- grown[k] = this.queue[(this.queueStart + k) % size]
1466
+ const from: i32 = handlerRing(this.queueStart, k, size)
1467
+ if (from >= 0 && from < toI32(old.length)) {
1468
+ grown[k] = old[from]
1469
+ }
1034
1470
  }
1035
1471
  this.queue = grown
1036
1472
  this.queueStart = 0
1037
1473
  }
1038
- this.queue[(this.queueStart + this.queueCount) % toI32(this.queue.length)] = r.index
1039
- this.queueCount += 1
1474
+ const queue: i32[] = this.queue
1475
+ // `handlerRing` answers in `[0, size)` for a queue of `size` places.
1476
+ const end: i32 = handlerRing(this.queueStart, this.queueCount, toI32(queue.length))
1477
+ if (end >= 0 && end < toI32(queue.length)) {
1478
+ queue[end] = r.index
1479
+ this.queueCount = handlerAdd(this.queueCount, 1)
1480
+ }
1040
1481
  }
1041
1482
 
1042
1483
  /** `H1_WRITE`: the carrier has room again for the response under way. */
1043
1484
  private resume(slot: i32, conn: Http1Connection): void {
1044
- const at: i32 = this.current[slot]
1045
- if (at < 0) {
1485
+ const r: HttpRequest | null = this.requestAt(this.currentOf(slot))
1486
+ if (r === null) {
1046
1487
  return
1047
1488
  }
1048
- const r: HttpRequest = this.requests[at]
1049
1489
  if (r.state !== HANDLER_STREAMING && r.state !== HANDLER_FLUSHING) {
1050
1490
  return
1051
1491
  }
@@ -1057,13 +1497,13 @@ export class HttpHandler {
1057
1497
 
1058
1498
  /** Hands the carrier as much of `r`'s pending bytes as it takes. */
1059
1499
  private pushPending(r: HttpRequest, conn: Http1Connection): void {
1060
- const left: i32 = r.pendingEnd - r.pendingStart
1500
+ const left: i32 = handlerSub(r.pendingEnd, r.pendingStart)
1061
1501
  if (left === 0) {
1062
1502
  return
1063
1503
  }
1064
1504
  const taken: i32 = conn.write(r.pending, r.pendingStart, left)
1065
1505
  if (taken > 0) {
1066
- r.pendingStart += taken
1506
+ r.pendingStart = handlerAdd(r.pendingStart, taken)
1067
1507
  }
1068
1508
  if (r.pendingStart === r.pendingEnd) {
1069
1509
  r.pendingStart = 0
@@ -1081,20 +1521,30 @@ export class HttpHandler {
1081
1521
  if (conn.end() === H1_AGAIN) {
1082
1522
  return
1083
1523
  }
1084
- this.current[r.slot] = -1
1524
+ const current: i32[] = this.current
1525
+ const slot: i32 = r.slot
1526
+ if (slot >= 0 && slot < toI32(current.length)) {
1527
+ current[slot] = -1
1528
+ }
1085
1529
  this.release(r)
1086
1530
  }
1087
1531
 
1088
1532
  /** A free request, or a new one. */
1089
1533
  private obtain(): HttpRequest {
1090
- const count: i32 = toI32(this.free.length)
1534
+ const free: i32[] = this.free
1535
+ const count: i32 = toI32(free.length)
1091
1536
  if (count > 0) {
1092
- const at: i32 = this.free[count - 1]
1093
- this.free.pop()
1094
- return this.requests[at]
1537
+ const at: i32 = free[count - 1]
1538
+ if (free.length > 0) {
1539
+ free.pop()
1540
+ }
1541
+ const reused: HttpRequest | null = this.requestAt(at)
1542
+ if (reused !== null) {
1543
+ return reused
1544
+ }
1095
1545
  }
1096
1546
  const r: HttpRequest = new HttpRequest(toI32(this.requests.length))
1097
- r.params = new Array<i32>(2 * this.router.maxParams + 2)
1547
+ r.params = handlerInts(handlerProbeLength(this.router.maxParams), HANDLER_ZERO)
1098
1548
  this.requests.push(r)
1099
1549
  return r
1100
1550
  }
@@ -1109,10 +1559,11 @@ export class HttpHandler {
1109
1559
 
1110
1560
  /** Hands back the request `slot` was reading when the carrier refused it. */
1111
1561
  private releaseReading(slot: i32): void {
1112
- const at: i32 = this.current[slot]
1113
- if (at >= 0 && this.requests[at].state === HANDLER_READING) {
1114
- this.current[slot] = -1
1115
- this.release(this.requests[at])
1562
+ const r: HttpRequest | null = this.requestAt(this.currentOf(slot))
1563
+ const current: i32[] = this.current
1564
+ if (r !== null && r.state === HANDLER_READING && slot >= 0 && slot < toI32(current.length)) {
1565
+ current[slot] = -1
1566
+ this.release(r)
1116
1567
  }
1117
1568
  }
1118
1569
 
@@ -1142,12 +1593,23 @@ export class HttpHandler {
1142
1593
  if (this.acceptRestUntil > 0 && !this.draining) {
1143
1594
  this.endAcceptRest()
1144
1595
  }
1145
- this.open[slot] = false
1146
- this.slotGen[slot] = this.slotGen[slot] + 1
1147
- const at: i32 = this.current[slot]
1148
- this.current[slot] = -1
1149
- if (at >= 0) {
1150
- const r: HttpRequest = this.requests[at]
1596
+ const open: boolean[] = this.open
1597
+ const slotGen: i32[] = this.slotGen
1598
+ const current: i32[] = this.current
1599
+ // Every slot the carrier hands has a place in all three.
1600
+ if (
1601
+ slot < 0 ||
1602
+ slot >= toI32(open.length) ||
1603
+ slot >= toI32(slotGen.length) ||
1604
+ slot >= toI32(current.length)
1605
+ ) {
1606
+ return
1607
+ }
1608
+ open[slot] = false
1609
+ slotGen[slot] = handlerAdd(slotGen[slot], 1)
1610
+ const r: HttpRequest | null = this.requestAt(current[slot])
1611
+ current[slot] = -1
1612
+ if (r !== null) {
1151
1613
  if (r.state === HANDLER_READING || r.state === HANDLER_PARKED || r.state === HANDLER_FLUSHING) {
1152
1614
  this.release(r)
1153
1615
  }
@@ -1160,7 +1622,8 @@ export class HttpHandler {
1160
1622
  const at: i32 = this.current[s]
1161
1623
  if (this.open[s] && at >= 0 && at < toI32(this.requests.length)) {
1162
1624
  const r: HttpRequest = this.requests[at]
1163
- if (r.state === HANDLER_READING && now - r.since > this.bodyTimeout) {
1625
+ const since: i64 = r.since
1626
+ if (r.state === HANDLER_READING && handlerSince(since, now) > this.bodyTimeout) {
1164
1627
  this.closeSlot(s)
1165
1628
  }
1166
1629
  }
@@ -1179,18 +1642,50 @@ export class HttpHandler {
1179
1642
  // ---- Requests -------------------------------------------------------------------
1180
1643
 
1181
1644
  /**
1182
- * Whether a whole request is waiting for `take`. Requests whose connection closed while queued are handed back here.
1645
+ * Whether a whole request is waiting for `take`. Requests whose connection
1646
+ * closed while queued are handed back here, and a body that decoded past
1647
+ * `maxDecoded` (413) or did not decode (400) is answered here.
1183
1648
  * @returns true when `take` will give out a request whose connection is still open
1184
1649
  */
1185
1650
  ready(): boolean {
1186
1651
  while (this.queueCount > 0) {
1187
- const r: HttpRequest = this.requests[this.queue[this.queueStart]]
1188
- if (this.live(r)) {
1652
+ const r: HttpRequest | null = this.queued()
1653
+ if (r === null) {
1654
+ // A place that names no request: none is ever queued, but it is passed over all the same.
1655
+ this.dequeue()
1656
+ continue
1657
+ }
1658
+ const live: boolean = this.live(r)
1659
+ if (live && r.refusal === 0) {
1189
1660
  return true
1190
1661
  }
1191
- this.queueStart = (this.queueStart + 1) % toI32(this.queue.length)
1192
- this.queueCount -= 1
1193
- this.release(r)
1662
+ this.dequeue()
1663
+ if (live) {
1664
+ r.state = HANDLER_HELD
1665
+ let sent: i32 = HANDLER_REFUSED
1666
+ if (r.refusal === 413) {
1667
+ sent = this.problemCore(
1668
+ r,
1669
+ toI32(413),
1670
+ "Content Too Large",
1671
+ "the body decodes to more than this server takes"
1672
+ )
1673
+ } else {
1674
+ sent = this.problemCore(
1675
+ r,
1676
+ toI32(400),
1677
+ "Bad Request",
1678
+ "the body is not in the coding its Content-Encoding names"
1679
+ )
1680
+ }
1681
+ // Held a line above, with a status in range, so it is not refused;
1682
+ // were it, the request goes back rather than staying held.
1683
+ if (sent === HANDLER_REFUSED) {
1684
+ this.release(r)
1685
+ }
1686
+ } else {
1687
+ this.release(r)
1688
+ }
1194
1689
  }
1195
1690
  return false
1196
1691
  }
@@ -1200,16 +1695,114 @@ export class HttpHandler {
1200
1695
  * @returns the oldest queued request, the program's until it answers it
1201
1696
  */
1202
1697
  take(): HttpRequest {
1203
- if (!this.ready()) {
1698
+ const r: HttpRequest | null = this.next()
1699
+ if (r === null) {
1204
1700
  panic("HttpHandler.take: no request is ready")
1205
1701
  }
1206
- const r: HttpRequest = this.requests[this.queue[this.queueStart]]
1207
- this.queueStart = (this.queueStart + 1) % toI32(this.queue.length)
1208
- this.queueCount -= 1
1702
+ return r
1703
+ }
1704
+
1705
+ /**
1706
+ * The next whole request, as `take` hands it over, or null when none is `ready`.
1707
+ * @returns the oldest queued request, the program's until it answers it, or null
1708
+ */
1709
+ next(): HttpRequest | null {
1710
+ const r: HttpRequest | null = this.ready() ? this.queued() : null
1711
+ if (r === null) {
1712
+ return null
1713
+ }
1714
+ this.dequeue()
1209
1715
  r.state = HANDLER_HELD
1210
1716
  return r
1211
1717
  }
1212
1718
 
1719
+ /**
1720
+ * The next step to run before `r`'s route body, lowest id first, or
1721
+ * `HANDLER_NEXT` once every step `Router.use` bound to `r.route` has run,
1722
+ * or `HANDLER_ANSWERED` once a step has answered `r`. A step reads `r`,
1723
+ * and may answer it — `refuse`, `problem`, `empty` or any other answer —
1724
+ * or add answer fields with `field`; call `before` again straight after
1725
+ * each step, before the next `take`, until it answers a negative code.
1726
+ * Only a request `take` handed over runs steps: what the handler answers
1727
+ * itself, to a bad request, a timeout or a full pool, runs none.
1728
+ *
1729
+ * let s = handler.before(req)
1730
+ * while (s >= 0) { switch (s) { case AUTH: ... } s = handler.before(req) }
1731
+ * if (s === HANDLER_NEXT) { switch (req.route) { ... } }
1732
+ *
1733
+ * @param r a request `take` handed over
1734
+ * @returns the next step's id, `HANDLER_NEXT`, or `HANDLER_ANSWERED`
1735
+ */
1736
+ before(r: HttpRequest): i32 {
1737
+ if (r.state !== HANDLER_HELD) {
1738
+ return HANDLER_ANSWERED
1739
+ }
1740
+ if (!r.stepped) {
1741
+ r.stepped = true
1742
+ r.stepsLeft = this.router.steps(r.route)
1743
+ r.stepsRan = 0
1744
+ }
1745
+ const left: i32 = r.stepsLeft
1746
+ if (left === 0) {
1747
+ return HANDLER_NEXT
1748
+ }
1749
+ // The lowest bit set, `left & -left`, negated in wrapping unsigned arithmetic.
1750
+ const low: i32 = toI32(toU32(left) & (toU32(0) - toU32(left)))
1751
+ r.stepsLeft = left ^ low
1752
+ r.stepsRan = r.stepsRan | low
1753
+ return toI32(31) - toI32(Math.clz32(toU32(low)))
1754
+ }
1755
+
1756
+ /**
1757
+ * The next step to run after `r`'s route body has chosen its answer and
1758
+ * before it sends it: the steps `before` handed out, highest id first, then
1759
+ * `HANDLER_NEXT`; or `HANDLER_ANSWERED` once a step has answered `r`. A
1760
+ * step here may still `field` or answer in the body's place. A request
1761
+ * `before` was never called for runs no step here.
1762
+ * @param r a request `take` handed over, not yet answered
1763
+ * @returns the next step's id, `HANDLER_NEXT`, or `HANDLER_ANSWERED`
1764
+ */
1765
+ after(r: HttpRequest): i32 {
1766
+ if (r.state !== HANDLER_HELD) {
1767
+ return HANDLER_ANSWERED
1768
+ }
1769
+ const ran: i32 = r.stepped ? r.stepsRan : 0
1770
+ if (ran === 0) {
1771
+ return HANDLER_NEXT
1772
+ }
1773
+ const step: i32 = toI32(31) - toI32(Math.clz32(toU32(ran)))
1774
+ r.stepsRan = ran ^ (1 << step)
1775
+ return step
1776
+ }
1777
+
1778
+ /**
1779
+ * Adds the field `name: value` to `r`'s answer, after the fields the answer
1780
+ * names itself, whichever answer it is. Both are kept by reference, so they
1781
+ * stay the caller's bytes, unchanged, until the answer starts. Panics past
1782
+ * `HANDLER_MAX_ADDED` fields, or on a request not held; a name or value the
1783
+ * carrier refuses panics as the answer's own would.
1784
+ * @param r a request `take` handed over, not yet answered
1785
+ * @param name the field name, a lowercase token
1786
+ * @param value the field value, field text
1787
+ */
1788
+ field(r: HttpRequest, name: u8[], value: u8[]): void {
1789
+ if (r.state !== HANDLER_HELD) {
1790
+ panic(`HttpHandler.field: the request is not one taken and unanswered (state ${r.state})`)
1791
+ }
1792
+ const at: i32 = r.added
1793
+ if (at >= HANDLER_MAX_ADDED) {
1794
+ panic(`HttpHandler.field: more than ${HANDLER_MAX_ADDED} fields added to one answer`)
1795
+ }
1796
+ if (at >= 0 && at < toI32(r.addedNames.length) && at < toI32(r.addedValues.length)) {
1797
+ r.addedNames[at] = name
1798
+ r.addedValues[at] = value
1799
+ } else {
1800
+ r.addedNames.push(name)
1801
+ r.addedValues.push(value)
1802
+ }
1803
+ r.added = at + 1
1804
+ }
1805
+
1213
1806
  /**
1214
1807
  * Whether the client of `r` has hung up: its connection is closed or
1215
1808
  * reused, or the peer ended its stream while `r` is held. A half-close
@@ -1224,7 +1817,9 @@ export class HttpHandler {
1224
1817
 
1225
1818
  /** Whether `r`'s connection is the one it was read on, still open. */
1226
1819
  private live(r: HttpRequest): boolean {
1227
- return this.server.holds(r.slot) && this.slotGen[r.slot] === r.gen
1820
+ const gens: i32[] = this.slotGen
1821
+ const slot: i32 = r.slot
1822
+ return slot >= 0 && slot < toI32(gens.length) && gens[slot] === r.gen && this.server.holds(slot)
1228
1823
  }
1229
1824
 
1230
1825
  /**
@@ -1273,14 +1868,35 @@ export class HttpHandler {
1273
1868
  * the connection was closed for it
1274
1869
  */
1275
1870
  start(r: HttpRequest, status: i32, names: u8[][], values: u8[][], bodyLength: i32): i32 {
1871
+ return this.kept(this.startCore(r, status, names, values, bodyLength))
1872
+ }
1873
+
1874
+ /**
1875
+ * `start`, with a broken contract answered as an `Err` instead of a panic:
1876
+ * a request not taken or already answered, a status outside 200 to 599 or
1877
+ * a body length below `HTTP1_CHUNKED` leave `r` as it was; a field the
1878
+ * carrier refuses closes the connection and hands `r` back.
1879
+ * @param r a request taken and not yet answered
1880
+ * @param status the response status, from 200 to 599
1881
+ * @param names the field names, as bytes, beside `values`
1882
+ * @param values each field's value, `values[k]` for `names[k]`
1883
+ * @param bodyLength how many body bytes will follow, or `HTTP1_CHUNKED` for a body of unknown length
1884
+ * @returns `Ok` with what `start` answers, or `Err` saying which contract the call broke
1885
+ */
1886
+ tryStart(r: HttpRequest, status: i32, names: u8[][], values: u8[][], bodyLength: i32): Result<i32, string> {
1887
+ return this.checked(this.startCore(r, status, names, values, bodyLength))
1888
+ }
1889
+
1890
+ /** `start`'s work, answering `HANDLER_REFUSED` where `start` panics. */
1891
+ private startCore(r: HttpRequest, status: i32, names: u8[][], values: u8[][], bodyLength: i32): i32 {
1276
1892
  if (r.state !== HANDLER_HELD) {
1277
- panic(`HttpHandler.start: the request is not one taken and unanswered (state ${r.state})`)
1893
+ return this.refused(`HttpHandler.start: the request is not one taken and unanswered (state ${r.state})`)
1278
1894
  }
1279
1895
  if (status < 200 || status > 599) {
1280
- panic(`HttpHandler.start: status ${status} is outside 200 to 599`)
1896
+ return this.refused(`HttpHandler.start: status ${status} is outside 200 to 599`)
1281
1897
  }
1282
1898
  if (bodyLength < HTTP1_CHUNKED) {
1283
- panic(`HttpHandler.start: body length ${bodyLength}`)
1899
+ return this.refused(`HttpHandler.start: body length ${bodyLength}`)
1284
1900
  }
1285
1901
  r.state = HANDLER_STREAMING
1286
1902
  if (!this.live(r)) {
@@ -1288,7 +1904,13 @@ export class HttpHandler {
1288
1904
  }
1289
1905
  const conn: Http1Connection = this.server.connection(r.slot)
1290
1906
  const framing: i32 = status === 204 || status === 304 ? HTTP1_NO_BODY : bodyLength
1291
- const sent: i32 = conn.respond(status, names, values, framing)
1907
+ let outNames: u8[][] = names
1908
+ let outValues: u8[][] = values
1909
+ if (r.added > 0) {
1910
+ outNames = handlerWithAdded(this.namesBy, names, r.addedNames, r.added)
1911
+ outValues = handlerWithAdded(this.valuesBy, values, r.addedValues, r.added)
1912
+ }
1913
+ const sent: i32 = conn.respond(status, outNames, outValues, framing)
1292
1914
  if (sent === H1_AGAIN) {
1293
1915
  // The output still holds more of the response before this one than a
1294
1916
  // head can fit behind — only for a head near half the output, since a
@@ -1298,7 +1920,8 @@ export class HttpHandler {
1298
1920
  return HANDLER_DROPPED
1299
1921
  }
1300
1922
  if (sent !== 0) {
1301
- panic(
1923
+ this.abandon(r)
1924
+ return this.refused(
1302
1925
  `HttpHandler.start: the carrier refused the head (${sent}): a reserved field, or a name or value that is not a token or field text`
1303
1926
  )
1304
1927
  }
@@ -1308,7 +1931,9 @@ export class HttpHandler {
1308
1931
  /**
1309
1932
  * Writes `buf[off .. off + len)` of `r`'s body. What the carrier has no room
1310
1933
  * for is copied and sent as room comes, so `buf` is the caller's again on
1311
- * return. Answers `HANDLER_SENT` or `HANDLER_DROPPED`.
1934
+ * return. Answers `HANDLER_SENT` or `HANDLER_DROPPED`. A response not
1935
+ * started, a window outside `buf`, or more bytes than the declared length
1936
+ * leaves panics; `tryWrite` answers those instead, closing the connection.
1312
1937
  * @param r a request whose response `start` began
1313
1938
  * @param buf the bytes to send from; the caller's again on return
1314
1939
  * @param off where in `buf` the body bytes start
@@ -1316,6 +1941,28 @@ export class HttpHandler {
1316
1941
  * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection closed first
1317
1942
  */
1318
1943
  write(r: HttpRequest, buf: u8[], off: i32, len: i32): i32 {
1944
+ return this.kept(this.writeCore(r, buf, off, len))
1945
+ }
1946
+
1947
+ /**
1948
+ * `write`, with a broken contract answered as an `Err` instead of a panic.
1949
+ * A response not started leaves `r` as it was. A window outside `buf`, or
1950
+ * more bytes than the declared length leaves (whether this check or the
1951
+ * carrier finds it), abandons the response: the head is out and the body
1952
+ * cannot follow it as declared, so the connection is closed and `r` is
1953
+ * the handler's again. The caller answers nothing more for `r`.
1954
+ * @param r a request whose response `start` began
1955
+ * @param buf the bytes to send from; the caller's again on return
1956
+ * @param off where in `buf` the body bytes start
1957
+ * @param len how many bytes to send
1958
+ * @returns `Ok` with what `write` answers, or `Err` saying which contract the call broke
1959
+ */
1960
+ tryWrite(r: HttpRequest, buf: u8[], off: i32, len: i32): Result<i32, string> {
1961
+ return this.checked(this.writeCore(r, buf, off, len))
1962
+ }
1963
+
1964
+ /** `write`'s work, answering `HANDLER_REFUSED` where `write` panics. */
1965
+ private writeCore(r: HttpRequest, buf: u8[], off: i32, len: i32): i32 {
1319
1966
  const put: i32 = this.put(r, buf, off, len)
1320
1967
  if (put === HANDLER_SENT) {
1321
1968
  this.drive(r.slot)
@@ -1332,10 +1979,13 @@ export class HttpHandler {
1332
1979
  */
1333
1980
  private put(r: HttpRequest, buf: u8[], off: i32, len: i32): i32 {
1334
1981
  if (r.state !== HANDLER_STREAMING) {
1335
- panic(`HttpHandler.write: the response is not started (state ${r.state})`)
1982
+ return this.refused(`HttpHandler.write: the response is not started (state ${r.state})`)
1336
1983
  }
1337
- if (off < 0 || len < 0 || off > toI32(buf.length) - len) {
1338
- panic(`HttpHandler.write: the window ${off} + ${len} is outside its ${buf.length} bytes`)
1984
+ // From here a refusal abandons `r`: its head is out, so a body the
1985
+ // program cannot write as declared leaves no response to complete.
1986
+ if (handlerOutside(buf, off, len)) {
1987
+ this.abandon(r)
1988
+ return this.refused(`HttpHandler.write: the window ${off} + ${len} is outside its ${buf.length} bytes`)
1339
1989
  }
1340
1990
  if (!this.live(r)) {
1341
1991
  return HANDLER_DROPPED
@@ -1343,9 +1993,10 @@ export class HttpHandler {
1343
1993
  const conn: Http1Connection = this.server.connection(r.slot)
1344
1994
  // The carrier checks the length of what it takes; what is pending it has
1345
1995
  // not seen, so the check counts it here.
1346
- const owed: i32 = conn.responseLeft - (r.pendingEnd - r.pendingStart)
1996
+ const owed: i32 = handlerSub(conn.responseLeft, handlerSub(r.pendingEnd, r.pendingStart))
1347
1997
  if (conn.responseFraming >= 0 && !conn.responseEmpty && len > owed) {
1348
- panic(
1998
+ this.abandon(r)
1999
+ return this.refused(
1349
2000
  `HttpHandler.write: ${len} byte(s) is more than the ${owed} the length the response declared leaves`
1350
2001
  )
1351
2002
  }
@@ -1355,25 +2006,29 @@ export class HttpHandler {
1355
2006
  if (taken === H1_AGAIN) {
1356
2007
  taken = 0
1357
2008
  } else if (taken < 0) {
1358
- panic(
2009
+ // The same contract as the length check above, as `write` has always
2010
+ // answered it, and abandoned the same way.
2011
+ this.abandon(r)
2012
+ return this.refused(
1359
2013
  `HttpHandler.write: the carrier refused the body (${taken}): more than the length the response declared`
1360
2014
  )
1361
2015
  }
1362
2016
  }
1363
2017
  if (taken < len) {
1364
- this.keep(r, buf, off + taken, len - taken)
2018
+ this.keep(r, buf, handlerAdd(off, taken), handlerSub(len, taken))
1365
2019
  }
1366
2020
  return HANDLER_SENT
1367
2021
  }
1368
2022
 
1369
2023
  /** Appends bytes to `r`'s pending buffer, growing it once to the largest response it has held. */
1370
2024
  private keep(r: HttpRequest, buf: u8[], off: i32, len: i32): void {
1371
- const live: i32 = r.pendingEnd - r.pendingStart
1372
- if (toI32(r.pending.length) - r.pendingEnd < len) {
1373
- if (r.pendingStart > 0 || toI32(r.pending.length) < live + len) {
2025
+ const live: i32 = handlerSub(r.pendingEnd, r.pendingStart)
2026
+ const want: i32 = handlerAdd(live, len)
2027
+ if (handlerSub(toI32(r.pending.length), r.pendingEnd) < len) {
2028
+ if (r.pendingStart > 0 || toI32(r.pending.length) < want) {
1374
2029
  const target: u8[] =
1375
- toI32(r.pending.length) < live + len
1376
- ? new Array<u8>(handlerGrown(toI32(r.pending.length), live + len))
2030
+ toI32(r.pending.length) < want
2031
+ ? handlerBytes(handlerGrown(toI32(r.pending.length), want))
1377
2032
  : r.pending
1378
2033
  copyBytes(target, HANDLER_ZERO, r.pending, r.pendingStart, live)
1379
2034
  r.pending = target
@@ -1382,7 +2037,7 @@ export class HttpHandler {
1382
2037
  }
1383
2038
  }
1384
2039
  copyBytes(r.pending, r.pendingEnd, buf, off, len)
1385
- r.pendingEnd += len
2040
+ r.pendingEnd = handlerAdd(r.pendingEnd, len)
1386
2041
  }
1387
2042
 
1388
2043
  /**
@@ -1395,8 +2050,25 @@ export class HttpHandler {
1395
2050
  * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection closed first
1396
2051
  */
1397
2052
  end(r: HttpRequest): i32 {
2053
+ return this.kept(this.endCore(r))
2054
+ }
2055
+
2056
+ /**
2057
+ * `end`, with a broken contract answered as an `Err` instead of a panic: a
2058
+ * response not started leaves `r` as it was; a body short of the declared
2059
+ * length closes the connection, since the response cannot be completed,
2060
+ * and hands `r` back.
2061
+ * @param r a request whose response `start` began; the handler's again after an `Ok`
2062
+ * @returns `Ok` with what `end` answers, or `Err` saying which contract the call broke
2063
+ */
2064
+ tryEnd(r: HttpRequest): Result<i32, string> {
2065
+ return this.checked(this.endCore(r))
2066
+ }
2067
+
2068
+ /** `end`'s work, answering `HANDLER_REFUSED` where `end` panics. */
2069
+ private endCore(r: HttpRequest): i32 {
1398
2070
  if (r.state !== HANDLER_STREAMING) {
1399
- panic(`HttpHandler.end: the response is not started (state ${r.state})`)
2071
+ return this.refused(`HttpHandler.end: the response is not started (state ${r.state})`)
1400
2072
  }
1401
2073
  if (!this.live(r)) {
1402
2074
  this.release(r)
@@ -1404,9 +2076,12 @@ export class HttpHandler {
1404
2076
  }
1405
2077
  const slot: i32 = r.slot
1406
2078
  const conn: Http1Connection = this.server.connection(slot)
1407
- const short: i32 = conn.responseLeft - (r.pendingEnd - r.pendingStart)
2079
+ const short: i32 = handlerSub(conn.responseLeft, handlerSub(r.pendingEnd, r.pendingStart))
1408
2080
  if (conn.responseFraming >= 0 && short > 0 && !conn.responseEmpty) {
1409
- panic(`HttpHandler.end: the body is ${short} byte(s) short of the length the response declared`)
2081
+ this.abandon(r)
2082
+ return this.refused(
2083
+ `HttpHandler.end: the body is ${short} byte(s) short of the length the response declared`
2084
+ )
1410
2085
  }
1411
2086
  this.finish(r, conn)
1412
2087
  this.drive(slot)
@@ -1426,8 +2101,39 @@ export class HttpHandler {
1426
2101
  * the connection was closed for it
1427
2102
  */
1428
2103
  send(r: HttpRequest, status: i32, contentType: u8[], body: u8[], off: i32, len: i32): i32 {
1429
- this.typeValue[0] = contentType
1430
- return this.sendFields(r, status, this.typeName, this.typeValue, body, off, len)
2104
+ return this.kept(this.sendCore(r, status, contentType, body, off, len))
2105
+ }
2106
+
2107
+ /**
2108
+ * `send`, with a broken contract answered as an `Err` instead of a panic,
2109
+ * as `trySendFields` answers it.
2110
+ * @param r a request taken and not yet answered; the handler's again after an `Ok`
2111
+ * @param status the response status, from 200 to 599
2112
+ * @param contentType the `Content-Type` value, as bytes
2113
+ * @param body the buffer holding the body; the caller's again on return
2114
+ * @param off where in `body` the body bytes start
2115
+ * @param len how many body bytes to send
2116
+ * @returns `Ok` with what `send` answers, or `Err` saying which contract the call broke
2117
+ */
2118
+ trySend(
2119
+ r: HttpRequest,
2120
+ status: i32,
2121
+ contentType: u8[],
2122
+ body: u8[],
2123
+ off: i32,
2124
+ len: i32
2125
+ ): Result<i32, string> {
2126
+ return this.checked(this.sendCore(r, status, contentType, body, off, len))
2127
+ }
2128
+
2129
+ /** `send`'s work, answering `HANDLER_REFUSED` where `send` panics. */
2130
+ private sendCore(r: HttpRequest, status: i32, contentType: u8[], body: u8[], off: i32, len: i32): i32 {
2131
+ if (this.typeValue.length > 0) {
2132
+ this.typeValue[0] = contentType
2133
+ } else {
2134
+ this.typeValue.push(contentType)
2135
+ }
2136
+ return this.sendFieldsCore(r, status, this.typeName, this.typeValue, body, off, len)
1431
2137
  }
1432
2138
 
1433
2139
  /**
@@ -1452,16 +2158,70 @@ export class HttpHandler {
1452
2158
  off: i32,
1453
2159
  len: i32
1454
2160
  ): i32 {
1455
- const started: i32 = this.start(r, status, names, values, len)
2161
+ return this.kept(this.sendFieldsCore(r, status, names, values, body, off, len))
2162
+ }
2163
+
2164
+ /**
2165
+ * `sendFields`, with a broken contract answered as an `Err` instead of a
2166
+ * panic: a request not taken or already answered, a status outside 200 to
2167
+ * 599 or, when a body is sent (`len` above 0, a status other than 204 and
2168
+ * 304), a window outside `body` leave `r` as it was; a field the carrier
2169
+ * refuses closes the connection and hands `r` back.
2170
+ * @param r a request taken and not yet answered; the handler's again after an `Ok`
2171
+ * @param status the response status, from 200 to 599
2172
+ * @param names the field names, as bytes, beside `values`
2173
+ * @param values each field's value, `values[k]` for `names[k]`
2174
+ * @param body the buffer holding the body; the caller's again on return
2175
+ * @param off where in `body` the body bytes start
2176
+ * @param len how many body bytes to send
2177
+ * @returns `Ok` with what `sendFields` answers, or `Err` saying which contract the call broke
2178
+ */
2179
+ trySendFields(
2180
+ r: HttpRequest,
2181
+ status: i32,
2182
+ names: u8[][],
2183
+ values: u8[][],
2184
+ body: u8[],
2185
+ off: i32,
2186
+ len: i32
2187
+ ): Result<i32, string> {
2188
+ return this.checked(this.sendFieldsCore(r, status, names, values, body, off, len))
2189
+ }
2190
+
2191
+ /** `sendFields`'s work, answering `HANDLER_REFUSED` where `sendFields` panics. */
2192
+ private sendFieldsCore(
2193
+ r: HttpRequest,
2194
+ status: i32,
2195
+ names: u8[][],
2196
+ values: u8[][],
2197
+ body: u8[],
2198
+ off: i32,
2199
+ len: i32
2200
+ ): i32 {
2201
+ // Only a body that is sent has a window; it is checked before the head
2202
+ // goes, so a refused one leaves `r` untouched. A chunked length or a
2203
+ // 204 or 304 sends none, as before.
2204
+ const sends: boolean = len > 0 && status !== 204 && status !== 304
2205
+ if (sends && handlerOutside(body, off, len)) {
2206
+ return this.refused(`HttpHandler.write: the window ${off} + ${len} is outside its ${body.length} bytes`)
2207
+ }
2208
+ const started: i32 = this.startCore(r, status, names, values, len)
1456
2209
  if (started === HANDLER_DROPPED) {
1457
2210
  this.release(r)
1458
2211
  return HANDLER_DROPPED
1459
2212
  }
1460
- if (len > 0 && status !== 204 && status !== 304) {
2213
+ if (started !== HANDLER_SENT) {
2214
+ return started
2215
+ }
2216
+ if (sends) {
1461
2217
  // No pass between the body and the end: `end` drives the slot once.
1462
- this.put(r, body, off, len)
2218
+ // The head declared `len` and the window is checked, so `put` has no
2219
+ // contract left to refuse; should it refuse one, it abandons `r`.
2220
+ if (this.put(r, body, off, len) === HANDLER_REFUSED) {
2221
+ return HANDLER_REFUSED
2222
+ }
1463
2223
  }
1464
- return this.end(r)
2224
+ return this.endCore(r)
1465
2225
  }
1466
2226
 
1467
2227
  /**
@@ -1473,7 +2233,31 @@ export class HttpHandler {
1473
2233
  * the connection was closed for it
1474
2234
  */
1475
2235
  empty(r: HttpRequest, status: i32): i32 {
1476
- return this.sendFields(r, status, this.noFields, this.noFields, this.scratch, HANDLER_ZERO, HANDLER_ZERO)
2236
+ return this.kept(this.emptyCore(r, status))
2237
+ }
2238
+
2239
+ /**
2240
+ * `empty`, with a broken contract answered as an `Err` instead of a panic:
2241
+ * a request not taken or already answered, or a status outside 200 to 599,
2242
+ * leaves `r` as it was.
2243
+ * @param r a request taken and not yet answered; the handler's again after an `Ok`
2244
+ * @param status the response status, from 200 to 599
2245
+ * @returns `Ok` with what `empty` answers, or `Err` saying which contract the call broke
2246
+ */
2247
+ tryEmpty(r: HttpRequest, status: i32): Result<i32, string> {
2248
+ return this.checked(this.emptyCore(r, status))
2249
+ }
2250
+
2251
+ private emptyCore(r: HttpRequest, status: i32): i32 {
2252
+ return this.sendFieldsCore(
2253
+ r,
2254
+ status,
2255
+ this.noFields,
2256
+ this.noFields,
2257
+ this.scratch,
2258
+ HANDLER_ZERO,
2259
+ HANDLER_ZERO
2260
+ )
1477
2261
  }
1478
2262
 
1479
2263
  /**
@@ -1499,14 +2283,30 @@ export class HttpHandler {
1499
2283
  * the connection was closed for it
1500
2284
  */
1501
2285
  sendJson(r: HttpRequest, status: i32): i32 {
2286
+ return this.kept(this.sendJsonCore(r, status))
2287
+ }
2288
+
2289
+ /**
2290
+ * `sendJson`, with a broken contract answered as an `Err` instead of a
2291
+ * panic: no value begun with `json`, a request not taken or already
2292
+ * answered, or a status outside 200 to 599, leaves `r` as it was.
2293
+ * @param r a request taken and not yet answered; the handler's again after an `Ok`
2294
+ * @param status the response status for a value that fit, from 200 to 599
2295
+ * @returns `Ok` with what `sendJson` answers, or `Err` saying which contract the call broke
2296
+ */
2297
+ trySendJson(r: HttpRequest, status: i32): Result<i32, string> {
2298
+ return this.checked(this.sendJsonCore(r, status))
2299
+ }
2300
+
2301
+ private sendJsonCore(r: HttpRequest, status: i32): i32 {
1502
2302
  if (!this.jsonBegun) {
1503
- panic("HttpHandler.sendJson: no value was begun with json()")
2303
+ return this.refused("HttpHandler.sendJson: no value was begun with json()")
1504
2304
  }
1505
2305
  this.jsonBegun = false
1506
2306
  if (!this.writer.complete()) {
1507
- return this.problem(r, toI32(500), "Internal Server Error", "the response did not fit its buffer")
2307
+ return this.problemCore(r, toI32(500), "Internal Server Error", "the response did not fit its buffer")
1508
2308
  }
1509
- return this.send(r, status, this.jsonType, this.scratch, HANDLER_ZERO, this.writer.end)
2309
+ return this.sendCore(r, status, this.jsonType, this.scratch, HANDLER_ZERO, this.writer.end)
1510
2310
  }
1511
2311
 
1512
2312
  /**
@@ -1524,8 +2324,26 @@ export class HttpHandler {
1524
2324
  * the connection was closed for it
1525
2325
  */
1526
2326
  problem(r: HttpRequest, status: i32, title: string, detail: string): i32 {
2327
+ return this.kept(this.problemCore(r, status, title, detail))
2328
+ }
2329
+
2330
+ /**
2331
+ * `problem`, with a broken contract answered as an `Err` instead of a
2332
+ * panic: a request not taken or already answered, or a status outside 200
2333
+ * to 599, leaves `r` as it was.
2334
+ * @param r a request taken and not yet answered; the handler's again after an `Ok`
2335
+ * @param status the response status, from 200 to 599, also written into the object
2336
+ * @param title the status's reason phrase, or empty to leave it out
2337
+ * @param detail a sentence for a person about this occurrence, or empty to leave it out
2338
+ * @returns `Ok` with what `problem` answers, or `Err` saying which contract the call broke
2339
+ */
2340
+ tryProblem(r: HttpRequest, status: i32, title: string, detail: string): Result<i32, string> {
2341
+ return this.checked(this.problemCore(r, status, title, detail))
2342
+ }
2343
+
2344
+ private problemCore(r: HttpRequest, status: i32, title: string, detail: string): i32 {
1527
2345
  const length: i32 = this.writeProblem(status, title, detail)
1528
- return this.send(r, status, this.problemType, this.scratch, HANDLER_ZERO, length)
2346
+ return this.sendCore(r, status, this.problemType, this.scratch, HANDLER_ZERO, length)
1529
2347
  }
1530
2348
 
1531
2349
  /**
@@ -1576,10 +2394,33 @@ export class HttpHandler {
1576
2394
  * the connection was closed for it
1577
2395
  */
1578
2396
  refuse(r: HttpRequest): i32 {
2397
+ return this.kept(this.refuseCore(r))
2398
+ }
2399
+
2400
+ /**
2401
+ * `refuse`, with a broken contract answered as an `Err` instead of a
2402
+ * panic: a request not taken or already answered leaves `r` as it was.
2403
+ * @param r a request whose `route` is negative, taken and not yet answered; the handler's again after an `Ok`
2404
+ * @returns `Ok` with what `refuse` answers, or `Err` saying which contract the call broke
2405
+ */
2406
+ tryRefuse(r: HttpRequest): Result<i32, string> {
2407
+ return this.checked(this.refuseCore(r))
2408
+ }
2409
+
2410
+ private refuseCore(r: HttpRequest): i32 {
1579
2411
  if (r.route === ROUTER_METHOD_NOT_ALLOWED) {
1580
2412
  const length: i32 = this.writeProblem(toI32(405), "Method Not Allowed", "")
1581
- this.allowValues[1] = this.allowFor(r)
1582
- return this.sendFields(
2413
+ // The `Allow` value goes in the pair the constructor made, one store a
2414
+ // 405; the length test, after `allowFor` runs, proves the index, and
2415
+ // its other branch, never taken, answers the same by making the pair.
2416
+ const allow: u8[] = this.allowFor(r)
2417
+ const values: u8[][] = this.allowValues
2418
+ if (toI32(values.length) >= 2) {
2419
+ values[1] = allow
2420
+ } else {
2421
+ this.allowValues = [this.problemType, allow]
2422
+ }
2423
+ return this.sendFieldsCore(
1583
2424
  r,
1584
2425
  toI32(405),
1585
2426
  this.allowNames,
@@ -1589,7 +2430,37 @@ export class HttpHandler {
1589
2430
  length
1590
2431
  )
1591
2432
  }
1592
- return this.problem(r, toI32(404), "Not Found", "")
2433
+ return this.problemCore(r, toI32(404), "Not Found", "")
2434
+ }
2435
+
2436
+ /** Records why a call broke its contract and answers `HANDLER_REFUSED`. */
2437
+ private refused(why: string): i32 {
2438
+ this.refusal = why
2439
+ return HANDLER_REFUSED
2440
+ }
2441
+
2442
+ /** A core's answer for a public method: the panic it keeps for a broken contract, or the answer. */
2443
+ private kept(code: i32): i32 {
2444
+ if (code === HANDLER_REFUSED) {
2445
+ panic(this.refusal)
2446
+ }
2447
+ return code
2448
+ }
2449
+
2450
+ /** A core's answer for a `try` twin. */
2451
+ private checked(code: i32): Result<i32, string> {
2452
+ if (code === HANDLER_REFUSED) {
2453
+ return Err(this.refusal)
2454
+ }
2455
+ return Ok(code)
2456
+ }
2457
+
2458
+ /** Gives up on `r`'s answer: its connection is closed, since the response cannot be completed, and `r` goes back. */
2459
+ private abandon(r: HttpRequest): void {
2460
+ if (this.live(r)) {
2461
+ this.closeSlot(r.slot)
2462
+ }
2463
+ this.release(r)
1593
2464
  }
1594
2465
 
1595
2466
  /**
@@ -1599,13 +2470,17 @@ export class HttpHandler {
1599
2470
  */
1600
2471
  private allowFor(r: HttpRequest): u8[] {
1601
2472
  const router: Router = this.router
1602
- const methods: i32 = toI32(router.methodStart.length)
2473
+ const starts: i32[] = router.methodStart
2474
+ const ends: i32[] = router.methodEnd
2475
+ const methods: i32 = toI32(starts.length) < toI32(ends.length) ? toI32(starts.length) : toI32(ends.length)
1603
2476
  let mask: i64 = 0
1604
- for (let m: i32 = 0; m < methods; m++) {
2477
+ for (let m: i32 = 0; m < methods && m < toI32(starts.length) && m < toI32(ends.length); m++) {
2478
+ const start: i32 = starts[m]
2479
+ const end: i32 = ends[m]
1605
2480
  const route: i32 = router.match(
1606
2481
  router.methodBytes,
1607
- router.methodStart[m],
1608
- router.methodEnd[m],
2482
+ start,
2483
+ end,
1609
2484
  r.head,
1610
2485
  r.targetStart,
1611
2486
  r.targetEnd,
@@ -1615,18 +2490,20 @@ export class HttpHandler {
1615
2490
  mask = mask | (toI64(1) << toI64(m))
1616
2491
  }
1617
2492
  }
1618
- for (let k: i32 = 0; k < toI32(this.allowMasks.length); k++) {
1619
- if (this.allowMasks[k] === mask) {
1620
- return this.allowBytes[k]
2493
+ const masks: i64[] = this.allowMasks
2494
+ const made: u8[][] = this.allowBytes
2495
+ for (let k: i32 = 0; k < toI32(masks.length) && k < toI32(made.length); k++) {
2496
+ if (masks[k] === mask) {
2497
+ return made[k]
1621
2498
  }
1622
2499
  }
1623
2500
  let get: boolean = false
1624
2501
  let head: boolean = false
1625
2502
  const value: u8[] = []
1626
- for (let m: i32 = 0; m < methods; m++) {
2503
+ for (let m: i32 = 0; m < methods && m < toI32(starts.length) && m < toI32(ends.length); m++) {
1627
2504
  if ((mask & (toI64(1) << toI64(m))) !== toI64(0)) {
1628
- const start: i32 = router.methodStart[m]
1629
- const end: i32 = router.methodEnd[m]
2505
+ const start: i32 = starts[m]
2506
+ const end: i32 = ends[m]
1630
2507
  get = get || handlerSpanIs(router.methodBytes, start, end, "GET")
1631
2508
  head = head || handlerSpanIs(router.methodBytes, start, end, "HEAD")
1632
2509
  handlerAllowAppend(value, router.methodBytes, start, end)
@@ -1655,11 +2532,133 @@ const handlerAllowAppend = (value: u8[], bytes: u8[], start: i32, end: i32): voi
1655
2532
  }
1656
2533
  }
1657
2534
 
2535
+ /**
2536
+ * The first `n` elements' length as a `u16`, at most 65535, and 0 when `n` is
2537
+ * not positive: an allocation of a `u16` length is not an `array-length`
2538
+ * site, so the helpers below allocate once up to it and push only past it.
2539
+ */
2540
+ const handlerHead = (n: i32): u16 => {
2541
+ if (n <= 0) {
2542
+ return 0
2543
+ }
2544
+ return toU16(n < 65535 ? n : toI32(65535))
2545
+ }
2546
+
2547
+ /** `n` copies of `fill`, none when `n` is not positive: one allocation up to 65535, pushed past it. */
2548
+ const handlerInts = (n: i32, fill: i32): i32[] => {
2549
+ const out: i32[] = new Array<i32>(handlerHead(n))
2550
+ if (fill !== 0) {
2551
+ out.fill(fill)
2552
+ }
2553
+ for (let k: i32 = 65535; k < n; k++) {
2554
+ out.push(fill)
2555
+ }
2556
+ return out
2557
+ }
2558
+
2559
+ /** `n` flags, each false, made as `handlerInts` makes its numbers. */
2560
+ const handlerFlags = (n: i32): boolean[] => {
2561
+ const out: boolean[] = new Array<boolean>(handlerHead(n))
2562
+ for (let k: i32 = 65535; k < n; k++) {
2563
+ out.push(false)
2564
+ }
2565
+ return out
2566
+ }
2567
+
2568
+ /** `n` zero bytes, made as `handlerInts` makes its numbers. */
2569
+ const handlerBytes = (n: i32): u8[] => {
2570
+ const out: u8[] = new Array<u8>(handlerHead(n))
2571
+ for (let k: i32 = 65535; k < n; k++) {
2572
+ out.push(0)
2573
+ }
2574
+ return out
2575
+ }
2576
+
2577
+ /** The length of `Router.match`'s scratch for routes of up to `maxParams` parameters: two a parameter and two more. */
2578
+ const handlerProbeLength = (maxParams: i32): i32 => toI32(toI64(maxParams) * toI64(2) + toI64(2))
2579
+
2580
+ /**
2581
+ * The nanoseconds from the `monotonicNanos` instant `from` to `to`, or 0 when
2582
+ * `to` is not after it. Worked in `u64`, which has the bits of the signed
2583
+ * difference once `to` is the later.
2584
+ */
2585
+ const handlerSince = (from: i64, to: i64): i64 => (to > from ? toI64(toU64(to) - toU64(from)) : toI64(0))
2586
+
2587
+ /**
2588
+ * The `monotonicNanos` instant `span` nanoseconds after `now`. Worked in
2589
+ * `u64`, whose wrapping sum has the bits of the signed one: an instant is
2590
+ * centuries short of 2^63 and the span a constant of a second or less.
2591
+ */
2592
+ const handlerLater = (now: i64, span: i64): i64 => toI64(toU64(now) + toU64(span))
2593
+
2594
+ /** Place `start + k` of a ring of `size` places, in `[0, size)`; -1 for an empty ring or a negative place. */
2595
+ const handlerRing = (start: i32, k: i32, size: i32): i32 => {
2596
+ const n: i64 = toI64(size)
2597
+ if (n < 1 || start < 0 || k < 0) {
2598
+ return -1
2599
+ }
2600
+ // Two non-negative `i32`s sum below 2^32, so the `i64` sum is exact.
2601
+ const at: i64 = toI64(start) + toI64(k)
2602
+ return toI32(at % n)
2603
+ }
2604
+
2605
+ /**
2606
+ * A handler as `new HttpHandler(limits, listener, router)` makes one, with
2607
+ * what that constructor panics on answered as an `Err`: limits below their
2608
+ * least, or a readiness loop `pollCreate` could not make.
2609
+ * @param limits the caps and timeouts, as the constructor reads them
2610
+ * @param listener the listening socket's descriptor, still the program's to close
2611
+ * @param router the routes, which the handler keeps and consults at each request head
2612
+ * @returns `Ok` with the handler, or `Err` saying which limit is below its least or how `pollCreate` failed
2613
+ */
2614
+ export const openHttpHandler = (
2615
+ limits: HandlerLimits,
2616
+ listener: i32,
2617
+ router: Router
2618
+ ): Result<HttpHandler, string> => {
2619
+ const fault: string = handlerLimitsFault(limits)
2620
+ if (fault.length > 0) {
2621
+ return Err(fault)
2622
+ }
2623
+ const loop: i32 = pollCreate()
2624
+ if (loop < 0) {
2625
+ return Err(`HttpHandler: pollCreate failed: ${loop}`)
2626
+ }
2627
+ return Ok(new HttpHandler(limits, listener, router, loop))
2628
+ }
2629
+
2630
+ /** Why `limits` cannot make a handler, or `""` when it can. */
2631
+ const handlerLimitsFault = (limits: HandlerLimits): string => {
2632
+ if (limits.slots < 1 || limits.jsonBytes < 256 || limits.maxEvents < 1 || limits.bodyTimeout < 1) {
2633
+ return `HttpHandler: slots ${limits.slots}, jsonBytes ${limits.jsonBytes}, maxEvents ${limits.maxEvents} and bodyTimeout ${limits.bodyTimeout} need at least 1, 256, 1 and 1`
2634
+ }
2635
+ if (limits.maxDecoded < 0) {
2636
+ return `HttpHandler: maxDecoded ${limits.maxDecoded} is negative`
2637
+ }
2638
+ return ""
2639
+ }
2640
+
2641
+ /** Whether `buf[off .. off + len)` is not a window of `buf`. */
2642
+ const handlerOutside = (buf: u8[], off: i32, len: i32): boolean =>
2643
+ off < 0 || len < 0 || toI64(off) + toI64(len) > toI64(buf.length)
2644
+
2645
+ /** `a + b`, wrapped to an `i32`: the sum is taken in `i64`, where two `i32`s cannot overflow. */
2646
+ const handlerAdd = (a: i32, b: i32): i32 => toI32(toI64(a) + toI64(b))
2647
+
2648
+ /** `a - b`, wrapped to an `i32`, taken in `i64` as `handlerAdd` takes a sum. */
2649
+ const handlerSub = (a: i32, b: i32): i32 => toI32(toI64(a) - toI64(b))
2650
+
2651
+ /** Where slot `part` of field `i` sits in `spans`, four to a field, or -1 when that is past an `i32`. */
2652
+ const handlerSpanSlot = (i: i32, part: i32): i32 => {
2653
+ const at: i64 = toI64(i) * toI64(4) + toI64(part)
2654
+ return at < toI64(0) || at > toI64(2147483647) ? -1 : toI32(at)
2655
+ }
2656
+
1658
2657
  /** A buffer size of at least `need`: `have` doubled until it is, starting from 64. */
1659
2658
  const handlerGrown = (have: i32, need: i32): i32 => {
1660
2659
  let size: i32 = have < 64 ? 64 : have
1661
2660
  while (size < need && size < 1073741824) {
1662
- size = size * 2
2661
+ size = handlerAdd(size, size)
1663
2662
  }
1664
2663
  return size < need ? need : size
1665
2664
  }
@@ -1667,31 +2666,38 @@ const handlerGrown = (have: i32, need: i32): i32 => {
1667
2666
  /** Whether `bytes[start .. end)` is exactly `text`. */
1668
2667
  const handlerSpanIs = (bytes: u8[], start: i32, end: i32, text: string): boolean => {
1669
2668
  const n: i32 = toI32(text.length)
1670
- if (end - start !== n || start < 0 || end > toI32(bytes.length)) {
2669
+ if (start < 0 || end < start || end > toI32(bytes.length) || handlerSub(end, start) !== n) {
1671
2670
  return false
1672
2671
  }
2672
+ let at: i32 = start
1673
2673
  for (let k: i32 = 0; k < n; k++) {
1674
- if (toI32(bytes[start + k]) !== toI32(text.charCodeAt(k))) {
2674
+ if (at < 0 || at >= toI32(bytes.length) || toI32(bytes[at]) !== toI32(text.charCodeAt(k))) {
1675
2675
  return false
1676
2676
  }
2677
+ at = handlerAdd(at, 1)
1677
2678
  }
1678
2679
  return true
1679
2680
  }
1680
2681
 
1681
2682
  /** `bytes[start .. end)` as a decimal number that is not negative and fits an `i32`, or -1. */
1682
2683
  const handlerDecimal = (bytes: u8[], start: i32, end: i32): i32 => {
1683
- if (start < 0 || end <= start || end - start > 10 || end > toI32(bytes.length)) {
2684
+ if (start < 0 || end <= start || end > toI32(bytes.length) || handlerSub(end, start) > 10) {
1684
2685
  return -1
1685
2686
  }
1686
- let n: i64 = 0
2687
+ let value: i32 = 0
1687
2688
  for (let k: i32 = start; k < end && k < toI32(bytes.length); k++) {
1688
- const digit: i32 = toI32(bytes[k]) - 48
1689
- if (digit < 0 || digit > 9) {
2689
+ const c: i32 = toI32(bytes[k])
2690
+ // A value past 999999999 has ten digits already, and an eleventh is past an `i32`.
2691
+ if (c < 48 || c > 57 || value < 0 || value > 999999999) {
1690
2692
  return -1
1691
2693
  }
1692
- n = n * toI64(10) + toI64(digit)
2694
+ const next: i64 = toI64(value) * toI64(10) + toI64(c - 48)
2695
+ if (next > toI64(2147483647)) {
2696
+ return -1
2697
+ }
2698
+ value = toI32(next)
1693
2699
  }
1694
- return n > toI64(2147483647) ? -1 : toI32(n)
2700
+ return value
1695
2701
  }
1696
2702
 
1697
2703
  /**
@@ -1699,6 +2705,11 @@ const handlerDecimal = (bytes: u8[], start: i32, end: i32): i32 => {
1699
2705
  * many bytes it took, packed as `byte | taken << 8`; -1 for a malformed escape.
1700
2706
  */
1701
2707
  const handlerFormByte = (bytes: u8[], at: i32, end: i32): i32 => {
2708
+ // Its callers step `at` inside a span of `bytes`; the literal bound keeps
2709
+ // `at + 2` from overflowing, far past any head.
2710
+ if (at < 0 || at >= end || at >= toI32(bytes.length) || at > 1073741823) {
2711
+ return -1
2712
+ }
1702
2713
  const c: i32 = toI32(bytes[at])
1703
2714
  if (c === 43) {
1704
2715
  return 32 | HANDLER_TOOK_ONE
@@ -1706,12 +2717,15 @@ const handlerFormByte = (bytes: u8[], at: i32, end: i32): i32 => {
1706
2717
  if (c !== 37) {
1707
2718
  return c | HANDLER_TOOK_ONE
1708
2719
  }
1709
- if (at + 2 >= end) {
2720
+ if (at + 2 >= end || at + 2 >= toI32(bytes.length)) {
1710
2721
  return -1
1711
2722
  }
1712
- const hi: i32 = http1HexValue(toI32(bytes[at + 1]))
1713
- const lo: i32 = http1HexValue(toI32(bytes[at + 2]))
1714
- if (hi < 0 || lo < 0) {
2723
+ // Both bytes read before either call, which the prover takes to move lengths.
2724
+ const high: i32 = toI32(bytes[at + 1])
2725
+ const low: i32 = toI32(bytes[at + 2])
2726
+ const hi: i32 = http1HexValue(high)
2727
+ const lo: i32 = http1HexValue(low)
2728
+ if (hi < 0 || lo < 0 || hi > 15 || lo > 15) {
1715
2729
  return -1
1716
2730
  }
1717
2731
  return (hi * 16 + lo) | HANDLER_TOOK_THREE
@@ -1722,27 +2736,34 @@ const handlerFormIs = (bytes: u8[], start: i32, end: i32, name: string): boolean
1722
2736
  const n: i32 = toI32(name.length)
1723
2737
  let at: i32 = start
1724
2738
  let k: i32 = 0
1725
- while (at < end) {
2739
+ // A head is capped far below the literal bound, which keeps `at + 3` in an `i32`.
2740
+ while (at < end && at >= 0 && at < 1073741824) {
1726
2741
  const packed: i32 = handlerFormByte(bytes, at, end)
1727
2742
  if (packed < 0 || k >= n || (packed & 255) !== toI32(name.charCodeAt(k))) {
1728
2743
  return false
1729
2744
  }
1730
- at += packed >> 8
2745
+ // One byte taken, or three for an escape; `handlerFormByte` kept `at` far
2746
+ // below the top of an `i32`.
2747
+ if ((packed & HANDLER_TOOK_THREE) === HANDLER_TOOK_THREE) {
2748
+ at += 3
2749
+ } else {
2750
+ at += 1
2751
+ }
1731
2752
  k += 1
1732
2753
  }
1733
2754
  return k === n
1734
2755
  }
1735
2756
 
1736
2757
  /**
1737
- * `bytes[start .. end)` form-decoded into `out` from 0: its length,
2758
+ * `bytes[start .. start + len)` form-decoded into `out` from 0: its length,
1738
2759
  * `ROUTER_BAD_ESCAPE`, or `ROUTER_NO_ROOM`. `%00` decodes like any byte, as a
1739
2760
  * route parameter's does.
1740
2761
  */
1741
- const handlerFormDecode = (bytes: u8[], start: i32, end: i32, out: u8[]): i32 => {
2762
+ const handlerFormDecode = (bytes: u8[], start: i32, len: i32, out: u8[]): i32 => {
1742
2763
  const length: i32 = percentDecode(
1743
2764
  bytes,
1744
2765
  start,
1745
- end - start,
2766
+ len,
1746
2767
  out,
1747
2768
  HANDLER_ZERO,
1748
2769
  URL_DECODE_FORM | URL_DECODE_ALLOW_NUL
@@ -1752,3 +2773,40 @@ const handlerFormDecode = (bytes: u8[], start: i32, end: i32, out: u8[]): i32 =>
1752
2773
  }
1753
2774
  return length < 0 ? ROUTER_BAD_ESCAPE : length
1754
2775
  }
2776
+
2777
+ /**
2778
+ * `given` followed by `added[0 .. count)`, in the array `byLength` keeps for
2779
+ * that length: made the first time an answer has that many fields, and
2780
+ * written over by each answer after.
2781
+ */
2782
+ const handlerWithAdded = (byLength: u8[][][], given: u8[][], added: u8[][], count: i32): u8[][] => {
2783
+ const have: i32 = toI32(given.length)
2784
+ const length: i32 = handlerAdd(have, count)
2785
+ if (length < 0 || added.length === 0) {
2786
+ return given
2787
+ }
2788
+ const first: u8[] = added.length > 0 ? added[0] : []
2789
+ while (toI32(byLength.length) <= length) {
2790
+ const size: i32 = toI32(byLength.length)
2791
+ const made: u8[][] = []
2792
+ for (let k: i32 = 0; k < size; k++) {
2793
+ made.push(first)
2794
+ }
2795
+ byLength.push(made)
2796
+ }
2797
+ if (length >= toI32(byLength.length)) {
2798
+ return given
2799
+ }
2800
+ const out: u8[][] = byLength[length]
2801
+ for (let k: i32 = 0; k < toI32(given.length) && k < toI32(out.length); k++) {
2802
+ out[k] = given[k]
2803
+ }
2804
+ let at: i32 = have
2805
+ for (let k: i32 = 0; k < count && k < toI32(added.length); k++) {
2806
+ if (at >= 0 && at < toI32(out.length)) {
2807
+ out[at] = added[k]
2808
+ }
2809
+ at = handlerAdd(at, 1)
2810
+ }
2811
+ return out
2812
+ }