@amritk/nish-aarch64-linux 0.38.0 → 0.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/bin/nish +0 -0
  2. package/docs/AI.md +348 -37
  3. package/package.json +1 -1
  4. package/runtime/core/host.d.ts +11 -0
  5. package/runtime/core/host.mjs +35 -0
  6. package/runtime/nish.d.ts +301 -18
  7. package/runtime/nish.h +74 -10
  8. package/runtime/nish.mjs +69 -6
  9. package/runtime/node.mjs +117 -0
  10. package/runtime/runtime-aes.c +12 -4
  11. package/runtime/runtime-async.c +43 -10
  12. package/runtime/runtime-checksum.c +207 -15
  13. package/runtime/runtime-net.c +32 -3
  14. package/runtime/runtime-os.c +174 -27
  15. package/runtime/runtime-region.c +94 -10
  16. package/runtime/runtime-sandbox.c +377 -17
  17. package/runtime/runtime-sha256.c +11 -4
  18. package/runtime/runtime-wasm.c +15 -0
  19. package/runtime/runtime.c +5 -0
  20. package/scripts/build.sh +27 -8
  21. package/std/README.md +5 -4
  22. package/std/compress/checksum.ts +13 -0
  23. package/std/compress/deflate.ts +0 -2
  24. package/std/crypto/p256.ts +247 -74
  25. package/std/crypto/p384.ts +3 -1
  26. package/std/crypto/pki.ts +35 -9
  27. package/std/crypto/x25519.ts +153 -64
  28. package/std/crypto/x509.ts +113 -10
  29. package/std/json-tokenizer.ts +20 -0
  30. package/std/json-typed.ts +217 -8
  31. package/std/net/handler.ts +130 -16
  32. package/std/net/http1-codec.ts +499 -150
  33. package/std/net/http1-server.ts +495 -22
  34. package/std/net/http2-cleartext.ts +526 -0
  35. package/std/net/http2-tls.ts +48 -0
  36. package/std/net/http2.ts +84 -0
  37. package/std/net/postgres-async.ts +1304 -86
  38. package/std/net/postgres-carrier.ts +343 -10
  39. package/std/net/postgres.ts +122 -7
  40. package/std/net/prefork.ts +195 -11
  41. package/std/net/quic-datagram.ts +30 -0
  42. package/std/net/quic-listener.ts +38 -12
  43. package/std/net/quic-packet.ts +19 -6
  44. package/std/net/quic-recovery.ts +134 -19
  45. package/std/net/quic-stream.ts +174 -36
  46. package/std/net/quic.ts +418 -18
  47. package/std/net/router.ts +39 -17
  48. package/std/net/serve.ts +162 -58
  49. package/std/net/tls/codec.ts +110 -32
  50. package/std/net/tls/record-server.ts +37 -7
  51. package/std/net/tls-tcp.ts +56 -1
  52. package/std/net/tls.ts +196 -50
  53. package/std/net/websocket.ts +55 -18
  54. package/std/net/webtransport.ts +179 -1
  55. package/std/regex.ts +69 -47
  56. package/std/region.ts +62 -11
  57. package/std/secret.ts +26 -59
  58. package/std/text.ts +233 -0
@@ -132,7 +132,7 @@ import {
132
132
  HttpCompressor,
133
133
  httpAcceptEncoding,
134
134
  } from "nish/net/http-compress"
135
- import { netClose, netMss, netRead, netWrite, netWrite2, tcpAccept } from "nish:net"
135
+ import { netClose, netMss, netRead, netShutdown, netWrite, netWrite2, tcpAccept } from "nish:net"
136
136
  import {
137
137
  HTTP1_BODY,
138
138
  HTTP1_CHUNKED,
@@ -171,6 +171,7 @@ import { TlsServerConfig } from "nish/net/tls"
171
171
  import { HTTP_DATE_LAST_SECOND, HTTP_DATE_SIZE, httpDateWrite } from "nish/net/http-fields"
172
172
  import { TLS_RECORD_DONE, TLS_RECORD_STATE_OPEN, TLS_RECORD_WANT_WRITE } from "nish/net/tls/record-server"
173
173
  import { TlsTcpServer } from "nish/net/tls-tcp"
174
+ import { any, loadU8x16, ne } from "nish:simd"
174
175
 
175
176
  /** `next`: nothing to hand over until more input arrives, the output drains, or the program answers. */
176
177
  export const H1_NEED_MORE: i32 = 0
@@ -240,11 +241,153 @@ const H1_S_CLOSING: i32 = 2
240
241
  /** `H1_ERROR` was answered; sending what is left, then done. */
241
242
  const H1_S_FAILED: i32 = 3
242
243
 
244
+ /** `netShutdown`'s write side, for the lingering close. */
245
+ const H1_SHUT_WRITE: i32 = 1
246
+
243
247
  // Where the current exchange's response stands.
244
248
  const H1_R_NONE: i32 = 0
245
249
  const H1_R_BODY: i32 = 1
246
250
  const H1_R_DONE: i32 = 2
247
251
 
252
+ /**
253
+ * The longest final head `respond` keeps to write again (`Http1Connection`'s
254
+ * `headBytes`): one buffer of this size per connection, made at its first
255
+ * kept head. A longer head is written fresh every time.
256
+ */
257
+ const H1_HEAD_KEEP: i32 = 1024
258
+
259
+ /** The most program fields a kept head carries: a head with more is written fresh every time. */
260
+ const H1_HEAD_FIELDS: i32 = 16
261
+
262
+ /**
263
+ * How many responses in a row may miss the kept head before `respond` stops
264
+ * comparing and keeping until the `Date` turns: past it, a head is written as
265
+ * if nothing were kept, so heads that never repeat cost no more than that.
266
+ */
267
+ const H1_HEAD_MISSES: i32 = 4
268
+
269
+ // `respond`'s `Connection` field, as the kept head records it.
270
+ const H1_CONN_NONE: i32 = 0
271
+ const H1_CONN_CLOSE: i32 = 1
272
+ const H1_CONN_KEEP_ALIVE: i32 = 2
273
+
274
+ /** Whether `kept[at ..)` begins with all of `bytes`, a byte at a time: the path for a range a word load cannot prove inside its array. */
275
+ const http1ServerSameByByte = (kept: readonly u8[], at: i32, bytes: readonly u8[]): boolean => {
276
+ for (let k: i32 = 0; k < toI32(bytes.length); k += 1) {
277
+ if (kept[at + k] !== bytes[k]) {
278
+ return false
279
+ }
280
+ }
281
+ return true
282
+ }
283
+
284
+ /**
285
+ * Whether `kept[at ..)` begins with all of `bytes`, eight to fifteen of them:
286
+ * two eight-byte loads a side, the second overlapping the first. One range
287
+ * check comes first and each load's ors are grouped in pairs, as `getU64BE`'s
288
+ * are, so LLVM folds every eight loads into one.
289
+ */
290
+ const http1ServerSame8 = (kept: readonly u8[], at: i32, bytes: readonly u8[]): boolean => {
291
+ const n: i32 = toI32(bytes.length)
292
+ const e: i32 = at + n - 8
293
+ const f: i32 = n - 8
294
+ if (
295
+ !(at >= 0 && at < 2147483640 && at + 8 <= toI32(kept.length)) ||
296
+ !(e >= 0 && e < 2147483640 && e + 8 <= toI32(kept.length)) ||
297
+ !(toI32(bytes.length) >= 8 && f >= 0 && f < 2147483640 && f + 8 <= toI32(bytes.length))
298
+ ) {
299
+ return http1ServerSameByByte(kept, at, bytes)
300
+ }
301
+ return (
302
+ ((toU64(kept[at]) << toU64(56)) |
303
+ (toU64(kept[at + 1]) << toU64(48)) |
304
+ ((toU64(kept[at + 2]) << toU64(40)) | (toU64(kept[at + 3]) << toU64(32))) |
305
+ ((toU64(kept[at + 4]) << toU64(24)) |
306
+ (toU64(kept[at + 5]) << toU64(16)) |
307
+ ((toU64(kept[at + 6]) << toU64(8)) | toU64(kept[at + 7])))) ===
308
+ ((toU64(bytes[0]) << toU64(56)) |
309
+ (toU64(bytes[1]) << toU64(48)) |
310
+ ((toU64(bytes[2]) << toU64(40)) | (toU64(bytes[3]) << toU64(32))) |
311
+ ((toU64(bytes[4]) << toU64(24)) |
312
+ (toU64(bytes[5]) << toU64(16)) |
313
+ ((toU64(bytes[6]) << toU64(8)) | toU64(bytes[7])))) &&
314
+ ((toU64(kept[e]) << toU64(56)) |
315
+ (toU64(kept[e + 1]) << toU64(48)) |
316
+ ((toU64(kept[e + 2]) << toU64(40)) | (toU64(kept[e + 3]) << toU64(32))) |
317
+ ((toU64(kept[e + 4]) << toU64(24)) |
318
+ (toU64(kept[e + 5]) << toU64(16)) |
319
+ ((toU64(kept[e + 6]) << toU64(8)) | toU64(kept[e + 7])))) ===
320
+ ((toU64(bytes[f]) << toU64(56)) |
321
+ (toU64(bytes[f + 1]) << toU64(48)) |
322
+ ((toU64(bytes[f + 2]) << toU64(40)) | (toU64(bytes[f + 3]) << toU64(32))) |
323
+ ((toU64(bytes[f + 4]) << toU64(24)) |
324
+ (toU64(bytes[f + 5]) << toU64(16)) |
325
+ ((toU64(bytes[f + 6]) << toU64(8)) | toU64(bytes[f + 7]))))
326
+ )
327
+ }
328
+
329
+ /** `http1ServerSame8` for four to seven bytes, with four-byte loads. */
330
+ const http1ServerSame4 = (kept: readonly u8[], at: i32, bytes: readonly u8[]): boolean => {
331
+ const n: i32 = toI32(bytes.length)
332
+ const e: i32 = at + n - 4
333
+ const f: i32 = n - 4
334
+ if (
335
+ !(at >= 0 && at < 2147483640 && at + 4 <= toI32(kept.length)) ||
336
+ !(e >= 0 && e < 2147483640 && e + 4 <= toI32(kept.length)) ||
337
+ !(toI32(bytes.length) >= 4 && f >= 0 && f < 2147483640 && f + 4 <= toI32(bytes.length))
338
+ ) {
339
+ return http1ServerSameByByte(kept, at, bytes)
340
+ }
341
+ return (
342
+ ((toU32(kept[at]) << 24) |
343
+ (toU32(kept[at + 1]) << 16) |
344
+ ((toU32(kept[at + 2]) << 8) | toU32(kept[at + 3]))) ===
345
+ ((toU32(bytes[0]) << 24) | (toU32(bytes[1]) << 16) | ((toU32(bytes[2]) << 8) | toU32(bytes[3]))) &&
346
+ ((toU32(kept[e]) << 24) |
347
+ (toU32(kept[e + 1]) << 16) |
348
+ ((toU32(kept[e + 2]) << 8) | toU32(kept[e + 3]))) ===
349
+ ((toU32(bytes[f]) << 24) |
350
+ (toU32(bytes[f + 1]) << 16) |
351
+ ((toU32(bytes[f + 2]) << 8) | toU32(bytes[f + 3])))
352
+ )
353
+ }
354
+
355
+ /**
356
+ * Where `kept[at ..)` holds `bytes` and then the byte `after`: the offset one
357
+ * past the byte that follows `after` (the space of `: `, the LF of CR LF), or
358
+ * -1 when it does not, or when `after` would be at or past `limit`. Sixteen
359
+ * bytes at a time with a last load that overlaps the one before; a name or
360
+ * value under sixteen bytes is two overlapping eight- or four-byte loads, and
361
+ * one under four a byte at a time. A kept value holds no CR (it is field
362
+ * text), so a value that matches is the whole kept value; a name is held to
363
+ * the kept name's length by `sameHead`, since a kept value may hold a colon.
364
+ */
365
+ const http1ServerKept = (kept: u8[], at: i32, limit: i32, bytes: u8[], after: i32): i32 => {
366
+ const n: i32 = toI32(bytes.length)
367
+ if (at < 0 || limit > toI32(kept.length) || n > limit - at - 2 || toI32(kept[at + n]) !== after) {
368
+ return -1
369
+ }
370
+ if (n >= 16) {
371
+ let k: i32 = 0
372
+ while (k < n - 16) {
373
+ if (any(ne(loadU8x16(kept, at + k), loadU8x16(bytes, k)))) {
374
+ return -1
375
+ }
376
+ k += 16
377
+ }
378
+ return any(ne(loadU8x16(kept, at + n - 16), loadU8x16(bytes, n - 16))) ? -1 : at + n + 2
379
+ }
380
+ let same: boolean = false
381
+ if (n >= 8) {
382
+ same = http1ServerSame8(kept, at, bytes)
383
+ } else if (n >= 4) {
384
+ same = http1ServerSame4(kept, at, bytes)
385
+ } else {
386
+ same = http1ServerSameByByte(kept, at, bytes)
387
+ }
388
+ return same ? at + n + 2 : -1
389
+ }
390
+
248
391
  /** Panics unless `value` is in `low .. high`: a cap no connection could work with is the program's mistake. */
249
392
  const http1ServerCheckCap = (name: string, value: i32, low: i32, high: i32): void => {
250
393
  if (value < low || value > high) {
@@ -429,6 +572,20 @@ export class Http1Config {
429
572
  * of its head each `idleTimeout` would hold its slot for good (slowloris).
430
573
  */
431
574
  headTimeout: i32 = 30000
575
+ /**
576
+ * Milliseconds `Http1Server` keeps reading, and throwing away, what a
577
+ * refused client still sends after its error response, before `expire`
578
+ * closes the slot (RFC 9112 §9.6). The server shuts its write side and
579
+ * drains rather than closing at once: a close with unread bytes resets the
580
+ * connection, and the reset can destroy the response before the client
581
+ * reads it.
582
+ */
583
+ lingerTimeout: i32 = 2000
584
+ /**
585
+ * The most bytes a refused slot drains before it is closed whatever is
586
+ * left (RFC 9112 §9.6); 0 closes at once, without a lingering close.
587
+ */
588
+ lingerBytes: i32 = 65536
432
589
  /**
433
590
  * Lend a slot's input and head buffers back to the server between
434
591
  * exchanges: once a response is sent and no byte of the next request has
@@ -596,6 +753,8 @@ export class Http1Connection {
596
753
  lastActive: i64 = 0
597
754
  /** When the head being read began to arrive, in `monotonicNanos`; meaningful while `headTimed`. */
598
755
  headSince: i64 = 0
756
+ /** When the lingering close began, in `monotonicNanos`; meaningful while `lingering`. */
757
+ lingerSince: i64 = 0
599
758
  private state: i32 = 0
600
759
  private response: i32 = 0
601
760
  /**
@@ -659,6 +818,8 @@ export class Http1Connection {
659
818
  mss: i32 = 0
660
819
  /** The MSS `Http1Server.accept` read from this connection's socket (`netMss`), or 0 when it reports none. */
661
820
  socketMss: i32 = 0
821
+ /** How many bytes the lingering close has drained, or -1 while the connection does not linger. */
822
+ private lingered: i32 = -1
662
823
  /**
663
824
  * The plain TCP socket the carrier sends `output` on, which `sendBody`
664
825
  * writes to directly: `Http1Server.accept` sets it, and `restart` and
@@ -680,6 +841,51 @@ export class Http1Connection {
680
841
  pong: u8[]
681
842
  /** No fields, for the responses the connection writes itself: made once. */
682
843
  private noFields: u8[][]
844
+ /**
845
+ * The last final head `respond` wrote, `headBytes[0 .. headLength)`, kept
846
+ * so that a response asking for the same head is a copy of it: the same
847
+ * status, the same field names and values byte for byte, the same framing
848
+ * and `Connection`, and the same `date` not reformatted since (`formats`).
849
+ * Empty until the first head that is kept (one of at most `H1_HEAD_KEEP`
850
+ * bytes, after a head of the same shape); then made once and kept for the
851
+ * slot's later peers, since what it holds is a function of those inputs
852
+ * alone.
853
+ */
854
+ private headBytes: u8[]
855
+ /** How many bytes of `headBytes` the kept head is; 0 while none is kept. */
856
+ private headLength: i32 = 0
857
+ /** Where the kept head's first field line starts, past the status line. */
858
+ private headFieldsAt: i32 = 0
859
+ /** The kept head's status. */
860
+ private headStatus: i32 = 0
861
+ /** The kept head's framing: a length, `HTTP1_CHUNKED` or `HTTP1_NO_BODY`. */
862
+ private headFraming: i32 = 0
863
+ /** The kept head's `Connection` field: `H1_CONN_NONE`, `H1_CONN_CLOSE` or `H1_CONN_KEEP_ALIVE`. */
864
+ private headConnection: i32 = 0
865
+ /** How many of the program's fields the kept head carries. */
866
+ private headFields: i32 = 0
867
+ /**
868
+ * The length of each of the kept head's field names and values, in order,
869
+ * name then value: `2 * H1_HEAD_FIELDS` of them, made with `headBytes`.
870
+ */
871
+ private headLengths: i32[]
872
+ /** The `HttpDate` the kept head's `Date` came from. */
873
+ private headDate: HttpDate
874
+ /** `headDate.formats()` when the kept head was written: a later format is a new second. */
875
+ private headFormats: i64 = 0
876
+ /** How many responses in a row have missed the kept head, up to `H1_HEAD_MISSES`. */
877
+ private headMisses: i32 = 0
878
+ /**
879
+ * `date.formats()` when the misses reached `H1_HEAD_MISSES`: while the date
880
+ * still has that count, `respond` neither compares nor keeps. -1 while on.
881
+ */
882
+ private headOff: i64 = -1
883
+ /**
884
+ * How many heads `respond` has copied from the kept one rather than written.
885
+ *
886
+ * @internal Read by `tests/link/net_http1_server_head_reuse` to tell a copied head from a written one.
887
+ */
888
+ headCopies: i64 = 0
683
889
 
684
890
  /**
685
891
  * A connection under `config`. A cap outside what the connection can work with panics.
@@ -700,6 +906,8 @@ export class Http1Connection {
700
906
  http1ServerCheckCap("maxMessage", config.maxMessage, H1_ZERO, big - H1_FRAME_HEADER)
701
907
  http1ServerCheckCap("idleTimeout", config.idleTimeout, one, big)
702
908
  http1ServerCheckCap("headTimeout", config.headTimeout, one, big)
909
+ http1ServerCheckCap("lingerTimeout", config.lingerTimeout, one, big)
910
+ http1ServerCheckCap("lingerBytes", config.lingerBytes, H1_ZERO, big)
703
911
  // The buffers the peer's bytes fill grow by doubling and stop at 2^30
704
912
  // (`Http1Parser`'s input and head, `WsDecoder`'s input), so a cap whose
705
913
  // buffer could need more is refused here rather than reached by a peer:
@@ -727,6 +935,9 @@ export class Http1Connection {
727
935
  this.data = this.noOutput
728
936
  this.pong = this.noOutput
729
937
  this.noFields = []
938
+ this.headBytes = this.noOutput
939
+ this.headDate = this.date
940
+ this.headLengths = []
730
941
  // A line must fit whole before the parser can read it, so the buffer
731
942
  // holds the longest request line or field line however small a chunk is.
732
943
  let limit: i32 = config.chunkSize
@@ -769,6 +980,14 @@ export class Http1Connection {
769
980
  this.inputEnded = false
770
981
  this.headTimed = false
771
982
  this.headSince = 0
983
+ // A slot's next connection starts with no kept head, and its first
984
+ // head is not taken for a repeat of the last connection's.
985
+ this.headLength = 0
986
+ this.headStatus = 0
987
+ this.headMisses = 0
988
+ this.headOff = -1
989
+ this.lingerSince = 0
990
+ this.lingered = -1
772
991
  this.mss = 0
773
992
  this.socketMss = 0
774
993
  this.fd = -1
@@ -900,6 +1119,7 @@ export class Http1Connection {
900
1119
  /** The socket failed: nothing more is sent or read, and the connection is done. */
901
1120
  abort(): void {
902
1121
  this.state = H1_S_FAILED
1122
+ this.lingered = -1
903
1123
  this.outputStart = 0
904
1124
  this.outputEnd = 0
905
1125
  this.pongPending = false
@@ -979,7 +1199,10 @@ export class Http1Connection {
979
1199
 
980
1200
  /** The room at the end of the output, once what was sent is moved out of the way. */
981
1201
  private room(): i32 {
982
- this.acquire()
1202
+ // Tested here, so that the usual case, an output already held, is no call.
1203
+ if (this.outputCap === 0) {
1204
+ this.acquire()
1205
+ }
983
1206
  const output: u8[] = this.output
984
1207
  const live: i32 = this.outputEnd - this.outputStart
985
1208
  if (this.outputStart > 0) {
@@ -1259,11 +1482,6 @@ export class Http1Connection {
1259
1482
  if (status < 100 || status > 599 || status === 101) {
1260
1483
  return H1_INVALID
1261
1484
  }
1262
- for (const name of names) {
1263
- if (http1ServerReserved(name)) {
1264
- return H1_INVALID
1265
- }
1266
- }
1267
1485
  const interim: boolean = status < 200
1268
1486
  const empty: boolean = interim || status === 204 || status === 304 || this.parser.methodIs("HEAD")
1269
1487
  if (!empty && bodyLength === HTTP1_NO_BODY) {
@@ -1277,32 +1495,59 @@ export class Http1Connection {
1277
1495
  close = true
1278
1496
  }
1279
1497
  let connection: string = ""
1498
+ let code: i32 = H1_CONN_NONE
1280
1499
  if (!interim && close) {
1281
1500
  connection = "close"
1501
+ code = H1_CONN_CLOSE
1282
1502
  } else if (!interim && this.parser.minor === 0) {
1283
1503
  connection = "keep-alive"
1504
+ code = H1_CONN_KEEP_ALIVE
1505
+ }
1506
+ // Asked first, so that a second that has turned is a new head.
1507
+ const date: u8[] = this.date.current()
1508
+ // Off for the rest of the second once heads stop repeating, so that a
1509
+ // program whose heads differ pays this test and no more.
1510
+ if (!interim && this.date.formats() !== this.headOff) {
1511
+ if (this.sameHead(status, names, values, framing, code)) {
1512
+ if (this.headLength <= this.bodyRoom()) {
1513
+ // `bodyRoom` stops short of the output's end, so the copy fits.
1514
+ copyBytes(this.output, this.outputEnd, this.headBytes, H1_ZERO, this.headLength)
1515
+ this.outputEnd += this.headLength
1516
+ this.headMisses = 0
1517
+ this.headCopies += 1
1518
+ return this.begin(close, framing, empty)
1519
+ }
1520
+ }
1521
+ }
1522
+ const count: i32 = toI32(names.length)
1523
+ for (let k: i32 = 0; k < count; k++) {
1524
+ if (http1ServerReserved(names[k])) {
1525
+ return H1_INVALID
1526
+ }
1284
1527
  }
1285
1528
  const room: i32 = this.bodyRoom()
1529
+ const start: i32 = this.outputEnd
1530
+ const reason: string = http1ServerReason(status)
1286
1531
  const end: i32 = http1WriteResponseHead(
1287
1532
  this.output,
1288
- this.outputEnd,
1533
+ start,
1289
1534
  status,
1290
- http1ServerReason(status),
1535
+ reason,
1291
1536
  names,
1292
1537
  values,
1293
1538
  framing,
1294
1539
  connection,
1295
- this.date.current()
1540
+ date
1296
1541
  )
1297
1542
  if (end === HTTP1_REFUSED) {
1298
1543
  return H1_INVALID
1299
1544
  }
1300
- if (end < 0 || end - this.outputEnd > room) {
1545
+ if (end < 0 || end - start > room) {
1301
1546
  // The head was not written, or ate into the reserve: take it back.
1302
- if (end - this.outputEnd > this.config.outputSize - H1_CONTROL_RESERVE) {
1547
+ if (end - start > this.config.outputSize - H1_CONTROL_RESERVE) {
1303
1548
  return H1_INVALID
1304
1549
  }
1305
- if (this.outputEnd === 0) {
1550
+ if (start === 0) {
1306
1551
  return H1_INVALID
1307
1552
  }
1308
1553
  this.writeHeld = true
@@ -1312,6 +1557,21 @@ export class Http1Connection {
1312
1557
  if (interim) {
1313
1558
  return 0
1314
1559
  }
1560
+ if (this.date.formats() !== this.headOff) {
1561
+ // A head written here is a miss: the kept one did not match.
1562
+ this.headMisses += 1
1563
+ if (this.headMisses < H1_HEAD_MISSES) {
1564
+ this.keepHead(start, end, status, reason, names, values, framing, code)
1565
+ } else {
1566
+ this.headMisses = 0
1567
+ this.headOff = this.date.formats()
1568
+ }
1569
+ }
1570
+ return this.begin(close, framing, empty)
1571
+ }
1572
+
1573
+ /** The final response's head is queued: the exchange now owes its body. Answers 0. */
1574
+ private begin(close: boolean, framing: i32, empty: boolean): i32 {
1315
1575
  this.closeAfter = close
1316
1576
  this.response = H1_R_BODY
1317
1577
  this.responseFraming = framing
@@ -1320,6 +1580,102 @@ export class Http1Connection {
1320
1580
  return 0
1321
1581
  }
1322
1582
 
1583
+ /**
1584
+ * Whether the kept head is the one `respond` would write now: the same
1585
+ * status, framing and `Connection`, the same `date` not reformatted since,
1586
+ * and the program's fields the same in number and, one by one, byte for
1587
+ * byte. Its cost is a compare of the fields' bytes, which stops at the
1588
+ * first that differs.
1589
+ */
1590
+ private sameHead(status: i32, names: u8[][], values: u8[][], framing: i32, connection: i32): boolean {
1591
+ const count: i32 = toI32(names.length)
1592
+ if (
1593
+ this.headLength === 0 ||
1594
+ status !== this.headStatus ||
1595
+ framing !== this.headFraming ||
1596
+ connection !== this.headConnection ||
1597
+ count !== this.headFields ||
1598
+ toI32(values.length) !== count ||
1599
+ this.date !== this.headDate ||
1600
+ this.date.formats() !== this.headFormats
1601
+ ) {
1602
+ return false
1603
+ }
1604
+ const kept: u8[] = this.headBytes
1605
+ const limit: i32 = this.headLength
1606
+ let at: i32 = this.headFieldsAt
1607
+ const lengths: i32[] = this.headLengths
1608
+ // `count` is both arrays' length; testing each proves every access.
1609
+ for (let i: i32 = 0; i < toI32(names.length) && i < toI32(values.length) && at >= 0; i += 1) {
1610
+ // Both lengths, so that a value cannot match the kept bytes past its
1611
+ // own field and pass for the kept head without its text checks.
1612
+ const name: u8[] = names[i]
1613
+ const value: u8[] = values[i]
1614
+ if (toI32(name.length) !== lengths[2 * i] || toI32(value.length) !== lengths[2 * i + 1]) {
1615
+ return false
1616
+ }
1617
+ at = http1ServerKept(kept, at, limit, name, 58)
1618
+ at = http1ServerKept(kept, at, limit, value, 13)
1619
+ }
1620
+ return at >= 0
1621
+ }
1622
+
1623
+ /**
1624
+ * Records the final head just written at `output[start .. end)`, with what
1625
+ * it was written from, for `sameHead`. Its bytes are kept only when the
1626
+ * head before it had the same status, `Connection` and number of fields,
1627
+ * so that a program whose every head differs in those pays a few stores
1628
+ * per response and no copy; a head longer than `H1_HEAD_KEEP`, or with
1629
+ * more than `H1_HEAD_FIELDS` fields, is never kept. The framing is left
1630
+ * out of that test (`sameHead` still compares it): a body length that
1631
+ * varies would otherwise make the buffer's allocation wait for two equal
1632
+ * lengths in a row among the few heads kept each second, a moment set by
1633
+ * the clock rather than the program. The buffer is made at the first head
1634
+ * that is kept, so a connection whose heads never repeat their shape holds
1635
+ * none. `respond` stops calling it, and `sameHead`, for the
1636
+ * rest of the second once `H1_HEAD_MISSES` heads in a row are written.
1637
+ */
1638
+ private keepHead(
1639
+ start: i32,
1640
+ end: i32,
1641
+ status: i32,
1642
+ reason: string,
1643
+ names: u8[][],
1644
+ values: u8[][],
1645
+ framing: i32,
1646
+ connection: i32
1647
+ ): void {
1648
+ const n: i32 = end - start
1649
+ const fields: i32 = toI32(names.length)
1650
+ const again: boolean =
1651
+ status === this.headStatus && connection === this.headConnection && fields === this.headFields
1652
+ this.headStatus = status
1653
+ this.headFraming = framing
1654
+ this.headConnection = connection
1655
+ this.headFields = fields
1656
+ this.headLength = 0
1657
+ if (n > H1_HEAD_KEEP || fields > H1_HEAD_FIELDS) {
1658
+ return
1659
+ }
1660
+ if (!again) {
1661
+ return
1662
+ }
1663
+ if (toI32(this.headBytes.length) < H1_HEAD_KEEP) {
1664
+ this.headBytes = new Array<u8>(H1_HEAD_KEEP)
1665
+ this.headLengths = new Array<i32>(2 * H1_HEAD_FIELDS)
1666
+ }
1667
+ for (let i: i32 = 0; i < fields && i < toI32(values.length); i += 1) {
1668
+ this.headLengths[2 * i] = toI32(names[i].length)
1669
+ this.headLengths[2 * i + 1] = toI32(values[i].length)
1670
+ }
1671
+ copyBytes(this.headBytes, H1_ZERO, this.output, start, n)
1672
+ // The field lines start past "HTTP/1.1 NNN " reason CRLF.
1673
+ this.headFieldsAt = 15 + toI32(reason.length)
1674
+ this.headLength = n
1675
+ this.headDate = this.date
1676
+ this.headFormats = this.date.formats()
1677
+ }
1678
+
1323
1679
  /**
1324
1680
  * Writes `buf[off .. off + len)` of the response body, as much as the output
1325
1681
  * has room for, and answers how much: a chunk of a chunked body, or bytes
@@ -1804,12 +2160,66 @@ export class Http1Connection {
1804
2160
  }
1805
2161
 
1806
2162
  /**
1807
- * Whether `expire` closes the slot at `now`: idle, or a head past its deadline.
2163
+ * Starts the lingering close at `now` (`monotonicNanos`) when the
2164
+ * connection refused its peer (`H1_ERROR`) on a socket that still reads,
2165
+ * the refusal is sent, and the peer has not ended its stream: the carrier
2166
+ * then shuts its write side and drains rather than closing.
2167
+ *
2168
+ * @param now the current time in `monotonicNanos`, which `lingerTimeout` counts from
2169
+ * @returns true when the lingering close began here; false when the connection should simply be closed
2170
+ * @internal Called by `Http1Server.flush` in this module once a refused slot is done.
2171
+ */
2172
+ lingerStart(now: i64): boolean {
2173
+ if (
2174
+ this.lingered >= 0 ||
2175
+ this.state !== H1_S_FAILED ||
2176
+ this.fd < 0 ||
2177
+ this.inputEnded ||
2178
+ this.config.lingerBytes <= 0 ||
2179
+ !this.isDone()
2180
+ ) {
2181
+ return false
2182
+ }
2183
+ this.lingered = 0
2184
+ this.lingerSince = now
2185
+ return true
2186
+ }
2187
+
2188
+ /**
2189
+ * Whether the connection is in its lingering close: its refusal is sent and
2190
+ * its carrier drains what the peer still sends.
2191
+ *
2192
+ * @returns true from `lingerStart` until the connection is restarted or aborted
2193
+ */
2194
+ lingering(): boolean {
2195
+ return this.lingered >= 0
2196
+ }
2197
+
2198
+ /**
2199
+ * Counts `n` more bytes drained in the lingering close.
2200
+ *
2201
+ * @param n how many bytes the carrier just read and threw away
2202
+ * @returns true while the drain stays under `lingerBytes`; false once the slot should be closed
2203
+ * @internal Called by `Http1Server` in this module as it drains a refused slot.
2204
+ */
2205
+ drained(n: i32): boolean {
2206
+ this.lingered = this.lingered + n
2207
+ return this.lingered < this.config.lingerBytes
2208
+ }
2209
+
2210
+ /** Whether the lingering close has lasted longer than `lingerTimeout` at `now` (`monotonicNanos`). */
2211
+ private lingerLate(now: i64): boolean {
2212
+ return this.lingered >= 0 && now - this.lingerSince > toI64(this.config.lingerTimeout) * toI64(1000000)
2213
+ }
2214
+
2215
+ /**
2216
+ * Whether `expire` closes the slot at `now`: idle, a head past its
2217
+ * deadline, or a lingering close past `lingerTimeout`.
1808
2218
  *
1809
2219
  * @internal Called by `Http1Server.expire` and `Http1TlsServer.expire` in this module to pick the slots to close.
1810
2220
  */
1811
2221
  expired(now: i64): boolean {
1812
- return this.idle(now) || this.headLate(now)
2222
+ return this.idle(now) || this.headLate(now) || this.lingerLate(now)
1813
2223
  }
1814
2224
 
1815
2225
  /**
@@ -1834,7 +2244,12 @@ export class Http1Connection {
1834
2244
  start = this.lastActive
1835
2245
  }
1836
2246
  const head: i64 = start + toI64(this.config.headTimeout) * toI64(1000000)
1837
- return head < idle ? head : idle
2247
+ const sooner: i64 = head < idle ? head : idle
2248
+ if (this.lingered >= 0) {
2249
+ const linger: i64 = this.lingerSince + toI64(this.config.lingerTimeout) * toI64(1000000)
2250
+ return linger < sooner ? linger : sooner
2251
+ }
2252
+ return sooner
1838
2253
  }
1839
2254
  }
1840
2255
 
@@ -2127,6 +2542,10 @@ export class Http1Server {
2127
2542
  return H1_ERROR
2128
2543
  }
2129
2544
  const conn: Http1Connection = this.connections[slot]
2545
+ if (conn.lingering()) {
2546
+ // Its `H1_ERROR` was answered before the lingering close began.
2547
+ return H1_NEED_MORE
2548
+ }
2130
2549
  if (conn.writeHeld) {
2131
2550
  this.send(slot)
2132
2551
  }
@@ -2136,15 +2555,58 @@ export class Http1Server {
2136
2555
  /**
2137
2556
  * Sends what `slot`'s connection holds until the socket would block, and
2138
2557
  * answers the interest: `H1_DONE` once the connection is over and sent,
2139
- * otherwise read while it has room and write while it holds bytes. It ends
2558
+ * otherwise read while it has room and write while it holds bytes or a
2559
+ * write is held back (its `H1_WRITE` comes from `next` once the socket is
2560
+ * writable, even when this send emptied the output). It ends
2140
2561
  * the serve call, so a response written after it reads the clock anew.
2562
+ * Once a refusal (`H1_ERROR`) is sent the slot lingers: its write side is
2563
+ * shut and what the client still sends is drained, answering
2564
+ * `H1_WANT_READ` until the client's end of stream, `lingerBytes`, or
2565
+ * `expire` past `lingerTimeout`; `next` answers `H1_NEED_MORE` meanwhile.
2141
2566
  *
2142
2567
  * @param slot the slot `accept` answered
2143
2568
  * @returns the `H1_WANT_` bits to arm the slot with, or `H1_DONE` when the program should `close` it
2144
2569
  */
2145
2570
  flush(slot: i32): i32 {
2146
2571
  this.date.unhold()
2147
- return this.settle(slot)
2572
+ const wants: i32 = this.settle(slot)
2573
+ if (wants !== H1_DONE || !this.holds(slot)) {
2574
+ return wants
2575
+ }
2576
+ // A refusal is sent: shut the write side and drain what the client still
2577
+ // sends (RFC 9112 §9.6), for `lingerTimeout` and `lingerBytes` at most.
2578
+ // Closed with those bytes unread, the socket would answer them with a
2579
+ // reset that can destroy the response before the client reads it (H1-2).
2580
+ const now: i64 = monotonicNanos()
2581
+ const conn: Http1Connection = this.connections[slot]
2582
+ if (!conn.lingerStart(now) || netShutdown(this.fds[slot], H1_SHUT_WRITE) < 0) {
2583
+ return H1_DONE
2584
+ }
2585
+ const deadline: i64 = conn.expiresNoSooner(now)
2586
+ if (deadline < this.expireAfter) {
2587
+ this.expireAfter = deadline
2588
+ }
2589
+ return this.drain(slot)
2590
+ }
2591
+
2592
+ /**
2593
+ * Reads and throws away what `slot`'s lingering peer sends until the
2594
+ * socket would block, answering `H1_WANT_READ`; `H1_DONE` at its end of
2595
+ * stream, an error, or past `lingerBytes`. What it drains is not activity:
2596
+ * `lastActive` stays, and `expire` closes the slot past `lingerTimeout`.
2597
+ */
2598
+ private drain(slot: i32): i32 {
2599
+ const conn: Http1Connection = this.connections[slot]
2600
+ const fd: i32 = this.fds[slot]
2601
+ while (true) {
2602
+ const n: i32 = netRead(fd, this.scratch, H1_ZERO, toI32(this.scratch.length))
2603
+ if (n === H1_AGAIN) {
2604
+ return H1_WANT_READ
2605
+ }
2606
+ if (n <= 0 || !conn.drained(n)) {
2607
+ return H1_DONE
2608
+ }
2609
+ }
2148
2610
  }
2149
2611
 
2150
2612
  /** `flush` within a serve call: sends, answers the interest, and keeps the clock reading. */
@@ -2153,6 +2615,9 @@ export class Http1Server {
2153
2615
  return H1_DONE
2154
2616
  }
2155
2617
  const conn: Http1Connection = this.connections[slot]
2618
+ if (conn.lingering()) {
2619
+ return this.drain(slot)
2620
+ }
2156
2621
  this.send(slot)
2157
2622
  if (conn.isDone()) {
2158
2623
  return H1_DONE
@@ -2162,7 +2627,12 @@ export class Http1Server {
2162
2627
  if (conn.inputRoom() > 0) {
2163
2628
  wants = wants | H1_WANT_READ
2164
2629
  }
2165
- if (conn.wantsWrite()) {
2630
+ if (conn.wantsWrite() || conn.writeHeld) {
2631
+ // A held write's `H1_WRITE` comes only from `next`. A send here that
2632
+ // emptied the output, because the peer read between `next` and
2633
+ // `flush`, leaves no byte to wait on, and a held write reads nothing,
2634
+ // so without the write bit the slot would be armed for nothing and the
2635
+ // response would never finish. The empty socket is writable at once.
2166
2636
  wants = wants | H1_WANT_WRITE
2167
2637
  }
2168
2638
  return wants
@@ -2230,7 +2700,7 @@ export class Http1Server {
2230
2700
 
2231
2701
  /**
2232
2702
  * Closes every slot that has been idle past `idleTimeout`, or reading one
2233
- * head for longer than `headTimeout`, at `now` (`monotonicNanos`); answers how many.
2703
+ * head for longer than `headTimeout`, or lingering past `lingerTimeout`, at `now` (`monotonicNanos`); answers how many.
2234
2704
  *
2235
2705
  * @param now the current time in `monotonicNanos`, which every timeout is measured against
2236
2706
  * @returns how many slots this call closed
@@ -2546,7 +3016,7 @@ export class Http1TlsServer {
2546
3016
  * Writes what `slot`'s connection holds into TLS, as far as TLS takes it,
2547
3017
  * and sends it; shuts TLS down once the connection is over or ALPN chose
2548
3018
  * another protocol. Answers TLS's interest, with the write bit while the
2549
- * connection still holds bytes.
3019
+ * connection still holds bytes or a write is held back.
2550
3020
  *
2551
3021
  * @param slot the slot `accept` answered
2552
3022
  * @returns the TLS interest bits the slot now waits for (`H1_WANT_` values), with `TLS_RECORD_DONE` once it should be closed
@@ -2565,7 +3035,10 @@ export class Http1TlsServer {
2565
3035
  }
2566
3036
  conn.park()
2567
3037
  const wants: i32 = this.tls.interest(slot)
2568
- return conn.wantsWrite() && (wants & TLS_RECORD_DONE) === 0 ? wants | TLS_RECORD_WANT_WRITE : wants
3038
+ // A held write waits on the write bit even with nothing queued, as `Http1Server.flush` explains.
3039
+ return (conn.wantsWrite() || conn.writeHeld) && (wants & TLS_RECORD_DONE) === 0
3040
+ ? wants | TLS_RECORD_WANT_WRITE
3041
+ : wants
2569
3042
  }
2570
3043
 
2571
3044
  /**