@amritk/nish-aarch64-linux 0.37.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 (73) hide show
  1. package/INSTALL.md +28 -16
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +380 -47
  4. package/package.json +1 -1
  5. package/runtime/core/arrays.d.ts +4 -0
  6. package/runtime/core/arrays.mjs +33 -0
  7. package/runtime/core/host.d.ts +11 -0
  8. package/runtime/core/host.mjs +35 -0
  9. package/runtime/nish.d.ts +645 -66
  10. package/runtime/nish.h +101 -15
  11. package/runtime/nish.mjs +69 -6
  12. package/runtime/node.mjs +117 -0
  13. package/runtime/runtime-aes.c +12 -4
  14. package/runtime/runtime-async.c +267 -51
  15. package/runtime/runtime-checksum.c +207 -15
  16. package/runtime/runtime-cross.c +2 -1
  17. package/runtime/runtime-net.c +32 -3
  18. package/runtime/runtime-os.c +174 -27
  19. package/runtime/runtime-region.c +170 -8
  20. package/runtime/runtime-sandbox.c +377 -17
  21. package/runtime/runtime-sha256.c +11 -4
  22. package/runtime/runtime-text.c +1068 -0
  23. package/runtime/runtime-wasm.c +18 -3
  24. package/runtime/runtime.c +55 -961
  25. package/runtime/vite.mjs +48 -11
  26. package/scripts/build.sh +113 -36
  27. package/std/LICENSE-fdlibm +8 -0
  28. package/std/README.md +7 -4
  29. package/std/array.ts +266 -0
  30. package/std/compress/checksum.ts +13 -0
  31. package/std/compress/deflate.ts +0 -2
  32. package/std/crypto/p256.ts +247 -74
  33. package/std/crypto/p384.ts +3 -1
  34. package/std/crypto/pki.ts +35 -9
  35. package/std/crypto/x25519.ts +153 -64
  36. package/std/crypto/x509.ts +113 -10
  37. package/std/host/text.ts +86 -0
  38. package/std/json-tokenizer.ts +20 -0
  39. package/std/json-typed.ts +217 -8
  40. package/std/math.ts +743 -41
  41. package/std/net/dns-resolver.ts +46 -6
  42. package/std/net/dns.ts +50 -13
  43. package/std/net/fetch.ts +691 -129
  44. package/std/net/handler.ts +142 -16
  45. package/std/net/http-compress.ts +17 -9
  46. package/std/net/http-fields.ts +19 -4
  47. package/std/net/http1-codec.ts +517 -154
  48. package/std/net/http1-server.ts +508 -25
  49. package/std/net/http2-cleartext.ts +526 -0
  50. package/std/net/http2-tls.ts +48 -0
  51. package/std/net/http2.ts +84 -0
  52. package/std/net/postgres-async.ts +2223 -0
  53. package/std/net/postgres-carrier.ts +343 -10
  54. package/std/net/postgres.ts +129 -11
  55. package/std/net/prefork.ts +195 -11
  56. package/std/net/quic-datagram.ts +30 -0
  57. package/std/net/quic-listener.ts +38 -12
  58. package/std/net/quic-packet.ts +19 -6
  59. package/std/net/quic-recovery.ts +134 -19
  60. package/std/net/quic-stream.ts +174 -36
  61. package/std/net/quic.ts +418 -18
  62. package/std/net/router.ts +39 -17
  63. package/std/net/serve.ts +867 -0
  64. package/std/net/tls/codec.ts +110 -32
  65. package/std/net/tls/record-server.ts +37 -7
  66. package/std/net/tls-tcp.ts +56 -1
  67. package/std/net/tls.ts +196 -50
  68. package/std/net/websocket.ts +55 -18
  69. package/std/net/webtransport.ts +179 -1
  70. package/std/regex.ts +69 -47
  71. package/std/region.ts +62 -11
  72. package/std/secret.ts +26 -59
  73. package/std/text.ts +464 -5
@@ -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
@@ -887,9 +1106,20 @@ export class Http1Connection {
887
1106
  this.inputEnded = true
888
1107
  }
889
1108
 
1109
+ /**
1110
+ * Whether the peer's byte stream has ended (`endInput`): a request still
1111
+ * held on the connection is one its client hung up on, or half-closed.
1112
+ *
1113
+ * @returns true once the carrier read the end of the peer's stream
1114
+ */
1115
+ ended(): boolean {
1116
+ return this.inputEnded
1117
+ }
1118
+
890
1119
  /** The socket failed: nothing more is sent or read, and the connection is done. */
891
1120
  abort(): void {
892
1121
  this.state = H1_S_FAILED
1122
+ this.lingered = -1
893
1123
  this.outputStart = 0
894
1124
  this.outputEnd = 0
895
1125
  this.pongPending = false
@@ -969,7 +1199,10 @@ export class Http1Connection {
969
1199
 
970
1200
  /** The room at the end of the output, once what was sent is moved out of the way. */
971
1201
  private room(): i32 {
972
- 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
+ }
973
1206
  const output: u8[] = this.output
974
1207
  const live: i32 = this.outputEnd - this.outputStart
975
1208
  if (this.outputStart > 0) {
@@ -1249,11 +1482,6 @@ export class Http1Connection {
1249
1482
  if (status < 100 || status > 599 || status === 101) {
1250
1483
  return H1_INVALID
1251
1484
  }
1252
- for (const name of names) {
1253
- if (http1ServerReserved(name)) {
1254
- return H1_INVALID
1255
- }
1256
- }
1257
1485
  const interim: boolean = status < 200
1258
1486
  const empty: boolean = interim || status === 204 || status === 304 || this.parser.methodIs("HEAD")
1259
1487
  if (!empty && bodyLength === HTTP1_NO_BODY) {
@@ -1267,32 +1495,59 @@ export class Http1Connection {
1267
1495
  close = true
1268
1496
  }
1269
1497
  let connection: string = ""
1498
+ let code: i32 = H1_CONN_NONE
1270
1499
  if (!interim && close) {
1271
1500
  connection = "close"
1501
+ code = H1_CONN_CLOSE
1272
1502
  } else if (!interim && this.parser.minor === 0) {
1273
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
+ }
1274
1527
  }
1275
1528
  const room: i32 = this.bodyRoom()
1529
+ const start: i32 = this.outputEnd
1530
+ const reason: string = http1ServerReason(status)
1276
1531
  const end: i32 = http1WriteResponseHead(
1277
1532
  this.output,
1278
- this.outputEnd,
1533
+ start,
1279
1534
  status,
1280
- http1ServerReason(status),
1535
+ reason,
1281
1536
  names,
1282
1537
  values,
1283
1538
  framing,
1284
1539
  connection,
1285
- this.date.current()
1540
+ date
1286
1541
  )
1287
1542
  if (end === HTTP1_REFUSED) {
1288
1543
  return H1_INVALID
1289
1544
  }
1290
- if (end < 0 || end - this.outputEnd > room) {
1545
+ if (end < 0 || end - start > room) {
1291
1546
  // The head was not written, or ate into the reserve: take it back.
1292
- if (end - this.outputEnd > this.config.outputSize - H1_CONTROL_RESERVE) {
1547
+ if (end - start > this.config.outputSize - H1_CONTROL_RESERVE) {
1293
1548
  return H1_INVALID
1294
1549
  }
1295
- if (this.outputEnd === 0) {
1550
+ if (start === 0) {
1296
1551
  return H1_INVALID
1297
1552
  }
1298
1553
  this.writeHeld = true
@@ -1302,6 +1557,21 @@ export class Http1Connection {
1302
1557
  if (interim) {
1303
1558
  return 0
1304
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 {
1305
1575
  this.closeAfter = close
1306
1576
  this.response = H1_R_BODY
1307
1577
  this.responseFraming = framing
@@ -1310,6 +1580,102 @@ export class Http1Connection {
1310
1580
  return 0
1311
1581
  }
1312
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
+
1313
1679
  /**
1314
1680
  * Writes `buf[off .. off + len)` of the response body, as much as the output
1315
1681
  * has room for, and answers how much: a chunk of a chunked body, or bytes
@@ -1506,8 +1872,8 @@ export class Http1Connection {
1506
1872
  /**
1507
1873
  * The segment `respondEncoded` counts in under `enc.segmentMode`: this
1508
1874
  * connection's `mss` when the program set it, else `enc.mss` when the
1509
- * program set it to other than `HTTP_DEFAULT_MSS`, else the socket's
1510
- * (`socketMss`), else `HTTP_DEFAULT_MSS`.
1875
+ * program set it (above 0), else the socket's (`socketMss`), else
1876
+ * `HTTP_DEFAULT_MSS`.
1511
1877
  *
1512
1878
  * @param enc the compressor whose own `mss` is the fallback after this connection's
1513
1879
  * @returns the segment size in bytes that segment counting uses for this connection
@@ -1516,7 +1882,7 @@ export class Http1Connection {
1516
1882
  if (this.mss > 0) {
1517
1883
  return this.mss
1518
1884
  }
1519
- if (enc.mss > 0 && enc.mss !== HTTP_DEFAULT_MSS) {
1885
+ if (enc.mss > 0) {
1520
1886
  return enc.mss
1521
1887
  }
1522
1888
  return this.socketMss > 0 ? this.socketMss : HTTP_DEFAULT_MSS
@@ -1794,12 +2160,66 @@ export class Http1Connection {
1794
2160
  }
1795
2161
 
1796
2162
  /**
1797
- * 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`.
1798
2218
  *
1799
2219
  * @internal Called by `Http1Server.expire` and `Http1TlsServer.expire` in this module to pick the slots to close.
1800
2220
  */
1801
2221
  expired(now: i64): boolean {
1802
- return this.idle(now) || this.headLate(now)
2222
+ return this.idle(now) || this.headLate(now) || this.lingerLate(now)
1803
2223
  }
1804
2224
 
1805
2225
  /**
@@ -1824,7 +2244,12 @@ export class Http1Connection {
1824
2244
  start = this.lastActive
1825
2245
  }
1826
2246
  const head: i64 = start + toI64(this.config.headTimeout) * toI64(1000000)
1827
- 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
1828
2253
  }
1829
2254
  }
1830
2255
 
@@ -2117,6 +2542,10 @@ export class Http1Server {
2117
2542
  return H1_ERROR
2118
2543
  }
2119
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
+ }
2120
2549
  if (conn.writeHeld) {
2121
2550
  this.send(slot)
2122
2551
  }
@@ -2126,15 +2555,58 @@ export class Http1Server {
2126
2555
  /**
2127
2556
  * Sends what `slot`'s connection holds until the socket would block, and
2128
2557
  * answers the interest: `H1_DONE` once the connection is over and sent,
2129
- * 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
2130
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.
2131
2566
  *
2132
2567
  * @param slot the slot `accept` answered
2133
2568
  * @returns the `H1_WANT_` bits to arm the slot with, or `H1_DONE` when the program should `close` it
2134
2569
  */
2135
2570
  flush(slot: i32): i32 {
2136
2571
  this.date.unhold()
2137
- 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
+ }
2138
2610
  }
2139
2611
 
2140
2612
  /** `flush` within a serve call: sends, answers the interest, and keeps the clock reading. */
@@ -2143,6 +2615,9 @@ export class Http1Server {
2143
2615
  return H1_DONE
2144
2616
  }
2145
2617
  const conn: Http1Connection = this.connections[slot]
2618
+ if (conn.lingering()) {
2619
+ return this.drain(slot)
2620
+ }
2146
2621
  this.send(slot)
2147
2622
  if (conn.isDone()) {
2148
2623
  return H1_DONE
@@ -2152,7 +2627,12 @@ export class Http1Server {
2152
2627
  if (conn.inputRoom() > 0) {
2153
2628
  wants = wants | H1_WANT_READ
2154
2629
  }
2155
- 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.
2156
2636
  wants = wants | H1_WANT_WRITE
2157
2637
  }
2158
2638
  return wants
@@ -2220,7 +2700,7 @@ export class Http1Server {
2220
2700
 
2221
2701
  /**
2222
2702
  * Closes every slot that has been idle past `idleTimeout`, or reading one
2223
- * 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.
2224
2704
  *
2225
2705
  * @param now the current time in `monotonicNanos`, which every timeout is measured against
2226
2706
  * @returns how many slots this call closed
@@ -2536,7 +3016,7 @@ export class Http1TlsServer {
2536
3016
  * Writes what `slot`'s connection holds into TLS, as far as TLS takes it,
2537
3017
  * and sends it; shuts TLS down once the connection is over or ALPN chose
2538
3018
  * another protocol. Answers TLS's interest, with the write bit while the
2539
- * connection still holds bytes.
3019
+ * connection still holds bytes or a write is held back.
2540
3020
  *
2541
3021
  * @param slot the slot `accept` answered
2542
3022
  * @returns the TLS interest bits the slot now waits for (`H1_WANT_` values), with `TLS_RECORD_DONE` once it should be closed
@@ -2555,7 +3035,10 @@ export class Http1TlsServer {
2555
3035
  }
2556
3036
  conn.park()
2557
3037
  const wants: i32 = this.tls.interest(slot)
2558
- 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
2559
3042
  }
2560
3043
 
2561
3044
  /**