@amritk/nish-aarch64-linux 0.39.0 → 0.40.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 (54) hide show
  1. package/INSTALL.md +74 -129
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +112 -33
  4. package/package.json +1 -1
  5. package/runtime/nish.d.ts +21 -17
  6. package/runtime/nish.h +10 -0
  7. package/runtime/page-frame.d.ts +123 -0
  8. package/runtime/page-frame.mjs +736 -0
  9. package/runtime/page-game.d.ts +132 -0
  10. package/runtime/page-game.mjs +738 -0
  11. package/runtime/runtime-aes.c +85 -8
  12. package/runtime/runtime-bytes.c +88 -4
  13. package/runtime/runtime-net.c +32 -0
  14. package/runtime/runtime-sandbox.c +55 -28
  15. package/runtime/runtime-wasm.c +422 -0
  16. package/runtime/vite.mjs +1 -1
  17. package/scripts/build.sh +15 -0
  18. package/std/README.md +73 -87
  19. package/std/array.ts +36 -3
  20. package/std/collections.ts +51 -0
  21. package/std/crypto/hmac.ts +37 -10
  22. package/std/crypto/p256.ts +1388 -2664
  23. package/std/crypto/pki.ts +116 -4
  24. package/std/crypto/sha256.ts +34 -6
  25. package/std/crypto/x509.ts +7 -0
  26. package/std/host/game.ts +273 -0
  27. package/std/input.ts +56 -0
  28. package/std/json-tokenizer.ts +325 -112
  29. package/std/json-typed.ts +43 -8
  30. package/std/json-value.ts +144 -3
  31. package/std/json.ts +63 -8
  32. package/std/net/fetch.ts +22 -4
  33. package/std/net/http-server.ts +3382 -0
  34. package/std/net/http1-client-codec.ts +6 -2
  35. package/std/net/http1-codec.ts +137 -12
  36. package/std/net/http1-server.ts +83 -29
  37. package/std/net/http2.ts +47 -14
  38. package/std/net/http3-server.ts +29 -3
  39. package/std/net/http3.ts +180 -7
  40. package/std/net/quic-recovery.ts +240 -9
  41. package/std/net/quic-stream.ts +21 -1
  42. package/std/net/quic.ts +98 -4
  43. package/std/net/router.ts +378 -31
  44. package/std/net/serve.ts +873 -65
  45. package/std/net/tls/verify.ts +19 -1
  46. package/std/net/url.ts +83 -35
  47. package/std/net/websocket.ts +74 -1
  48. package/std/net/webtransport.ts +7 -1
  49. package/std/raster.ts +837 -0
  50. package/std/release.ts +593 -0
  51. package/std/synth.ts +143 -0
  52. package/std/threads.ts +298 -0
  53. package/std/yaml-json.ts +368 -28
  54. package/std/yaml.ts +122 -27
@@ -0,0 +1,3382 @@
1
+ /**
2
+ * `nish/net/http-server` — one handler for HTTP/1.1, HTTP/2 (over TLS and
3
+ * cleartext) and HTTP/3, with Alt-Svc advertising the HTTP/3 port.
4
+ *
5
+ * `HttpServer` is `HttpHandler`'s pull loop (`nish/net/handler`) over up to
6
+ * four listeners at once. The program builds a `Router`, configures the
7
+ * listeners, and loops on `waitSigned` (or `wait`, when every listener is
8
+ * cleartext), `ready` and `take`, switching on `r.route`; one route body
9
+ * answers every version.
10
+ *
11
+ * const server = new HttpServer(new HttpServerLimits(), router)
12
+ * server.listenHttp1(tcpFd, new Http1Config(), 256)
13
+ * server.listenHttp2Tls(tlsFd, tlsConfig, new Http2Config(), 64)
14
+ * server.listenHttp3(udpFd, quicConfig, new Http3Config(), 64, entropy)
15
+ * for (;;) {
16
+ * server.waitSigned(1000, key)
17
+ * while (server.ready()) {
18
+ * const r: HttpServerRequest = server.take()
19
+ * if (r.route === HELLO) {
20
+ * server.send(r, 200, TEXT_PLAIN, HELLO_BODY, 0, HELLO_BODY.length)
21
+ * } else {
22
+ * server.refuse(r)
23
+ * }
24
+ * }
25
+ * }
26
+ *
27
+ * **One copy in.** Every version copies the request head once into the
28
+ * request's own `head`, a buffer of `limits.maxHead` bytes made on the
29
+ * request's first use and never grown: each listen call checks that no head
30
+ * its carrier accepts can overrun it. The body is held whole, up to
31
+ * `limits.maxBody`; past it the request is answered 413 on every version.
32
+ *
33
+ * **A fixed pool.** `limits.requests` requests are shared by every listener.
34
+ * With none free, an HTTP/1.1 connection stops being read until one is, an
35
+ * HTTP/2 stream is refused with REFUSED_STREAM and an HTTP/3 one with
36
+ * H3_REQUEST_REJECTED, so the client may retry. No connection holds more
37
+ * than a quarter of the pool.
38
+ *
39
+ * **Alt-Svc.** Once an HTTP/3 listener is configured, every HTTP/1.1 and
40
+ * HTTP/2 over TLS response names its port (`h3=":443"; ma=86400`); with
41
+ * `altSvcMaxAge` 0 they say `alt-svc: clear` instead. A response whose fields
42
+ * already hold an `alt-svc` keeps the program's. An h2c response carries
43
+ * none: it reaches clients through a proxy, and would name the backend's port.
44
+ *
45
+ * **One HTTP/2 slot space.** The TLS and the cleartext HTTP/2 carriers share
46
+ * the stream tables: each listener's slots follow the other's, so every
47
+ * HTTP/2 path below names a slot of either and the carrier is looked up once,
48
+ * in the `h2Holds` family.
49
+ */
50
+
51
+ import { copyBytes } from "nish/bytes"
52
+ import { JsonWriter } from "nish/json"
53
+ import { HANDLER_ABSENT, HANDLER_DROPPED, HANDLER_MAX_WATCHED, HANDLER_SENT } from "nish/net/handler"
54
+ import { HttpFields, httpFieldBytes, httpFieldIs } from "nish/net/http-fields"
55
+ import { HTTP1_CHUNKED, HTTP1_NO_BODY, http1HexValue } from "nish/net/http1-codec"
56
+ import {
57
+ H1_AGAIN,
58
+ H1_BODY,
59
+ H1_DONE,
60
+ H1_END,
61
+ H1_ERROR,
62
+ H1_NEED_MORE,
63
+ H1_POOL_FULL,
64
+ H1_REQUEST,
65
+ H1_WANT_READ,
66
+ H1_WANT_WRITE,
67
+ H1_WRITE,
68
+ Http1Config,
69
+ Http1Connection,
70
+ Http1Server,
71
+ } from "nish/net/http1-server"
72
+ import {
73
+ H2_AGAIN,
74
+ H2_DATA,
75
+ H2_ERROR,
76
+ H2_INVALID,
77
+ H2_NEED_MORE,
78
+ H2_REQUEST,
79
+ H2_RESET,
80
+ H2_TRAILERS,
81
+ Http2Config,
82
+ Http2Connection,
83
+ } from "nish/net/http2"
84
+ import { H2_CANCEL, H2_INTERNAL_ERROR, H2_NO_ERROR, H2_REFUSED_STREAM } from "nish/net/http2-frame"
85
+ import { H2C_POOL_FULL, Http2CleartextServer } from "nish/net/http2-cleartext"
86
+ import { Http2TlsServer } from "nish/net/http2-tls"
87
+ import {
88
+ H3_AGAIN,
89
+ H3_DATA,
90
+ H3_END,
91
+ H3_ERROR,
92
+ H3_INVALID,
93
+ H3_NEED_MORE,
94
+ H3_REQUEST,
95
+ H3_RESET,
96
+ Http3Config,
97
+ Http3Connection,
98
+ } from "nish/net/http3"
99
+ import {
100
+ H3_INTERNAL_ERROR,
101
+ H3_NO_ERROR,
102
+ H3_REQUEST_CANCELLED,
103
+ H3_REQUEST_REJECTED,
104
+ } from "nish/net/http3-frame"
105
+ import { H3_SERVER_RECEIVE_BURST, Http3Server } from "nish/net/http3-server"
106
+ import { QUIC_CONN_CID_LENGTH, QuicServerConfig } from "nish/net/quic"
107
+ import { QUIC_MAX_CID_LENGTH } from "nish/net/quic-packet"
108
+ import {
109
+ ROUTER_BAD_ESCAPE,
110
+ ROUTER_METHOD_NOT_ALLOWED,
111
+ ROUTER_NO_ROOM,
112
+ Router,
113
+ routerDecode,
114
+ } from "nish/net/router"
115
+ import { TlsServerConfig } from "nish/net/tls"
116
+ import { TLS_RECORD_DONE, TLS_RECORD_SIGN } from "nish/net/tls/record-server"
117
+ import { TLS_TCP_POOL_FULL } from "nish/net/tls-tcp"
118
+ import { URL_DECODE_ALLOW_NUL, URL_DECODE_ERR_SPACE, URL_DECODE_FORM, percentDecode } from "nish/net/url"
119
+ import { netLocalPort, pollAdd, pollCreate, pollModify, pollRemove, pollWait, udpRecvFrom } from "nish:net"
120
+ import { Secret } from "nish:secret"
121
+
122
+ /** The base `digits` writes a content-length in, and the byte of its digit 0. */
123
+ const HTTP_SERVER_TEN: i32 = 10
124
+ const HTTP_SERVER_ZERO_DIGIT: i32 = 48
125
+
126
+ /** The status a body past `maxBody` is answered with. */
127
+ const HTTP_SERVER_TOO_LARGE: i32 = 413
128
+
129
+ // A request's life: free, reading its body, whole but parked behind a full
130
+ // output, queued for `take`, held by the program, streaming its response,
131
+ // and flushing the response's last bytes.
132
+ const HTTP_SERVER_FREE: i32 = 0
133
+ const HTTP_SERVER_READING: i32 = 1
134
+ const HTTP_SERVER_PARKED: i32 = 2
135
+ const HTTP_SERVER_QUEUED: i32 = 3
136
+ const HTTP_SERVER_HELD: i32 = 4
137
+ const HTTP_SERVER_STREAMING: i32 = 5
138
+ const HTTP_SERVER_FLUSHING: i32 = 6
139
+
140
+ // Which carrier a request came in on.
141
+ const HTTP_SERVER_H1: i32 = 1
142
+ const HTTP_SERVER_H2: i32 = 2
143
+ const HTTP_SERVER_H3: i32 = 3
144
+
145
+ // Poll tokens: an HTTP/1.1 slot is its own number, an HTTP/2 slot is past
146
+ // `HTTP_SERVER_H2_BASE`, and a watched descriptor is `-2 - id`. A listener's
147
+ // token, less -100, is also its entry in `restUntil`.
148
+ const HTTP_SERVER_H1_LISTENER: i32 = -100
149
+ const HTTP_SERVER_H2_LISTENER: i32 = -101
150
+ const HTTP_SERVER_H3_SOCKET: i32 = -102
151
+ const HTTP_SERVER_H2C_LISTENER: i32 = -103
152
+ const HTTP_SERVER_H2_BASE: i32 = 1048576
153
+
154
+ const HTTP_SERVER_READ_BITS: i32 = 5
155
+ const HTTP_SERVER_ZERO: i32 = 0
156
+ const HTTP_SERVER_ACCEPT_NONE: i32 = -11
157
+ const HTTP_SERVER_ACCEPT_ABORTED: i32 = -103
158
+ // How long a listener rests after an accept failed for want of a resource.
159
+ const HTTP_SERVER_ACCEPT_REST: i64 = 100000000
160
+ // How often the timeouts are looked at.
161
+ const HTTP_SERVER_SWEEP: i64 = 1000000000
162
+ const HTTP_SERVER_NANOS_PER_MS: i64 = 1000000
163
+ // The method, version and line ends `Http1Server` allows beside its target and header caps.
164
+ const HTTP_SERVER_H1_LINE_OVERHEAD: i64 = 44
165
+ // The most `Http3Server.receive` bursts one turn takes.
166
+ const HTTP_SERVER_H3_ROUNDS: i32 = 64
167
+ const HTTP_SERVER_TOOK_ONE: i32 = 256
168
+ const HTTP_SERVER_TOOK_THREE: i32 = 768
169
+ const HTTP_SERVER_MAX_REQUESTS: i32 = 65536
170
+ const HTTP_SERVER_MAX_BODY: i32 = 1073741824
171
+ const HTTP_SERVER_MAX_HEAD: i32 = 1048576
172
+ // A body's small tier (`T` is the lesser of this and `maxBody`), and its first array.
173
+ const HTTP_SERVER_BODY_TIER: i32 = 65536
174
+ const HTTP_SERVER_BODY_FIRST: i32 = 64
175
+ /** The largest datagram (a GRO receive included) the drain reads, as `Http3Server.receive` reads them. */
176
+ const HTTP_SERVER_UDP_SIZE: i32 = 65536
177
+ /** A sender's address in `nish:net`'s form. */
178
+ const HTTP_SERVER_UDP_ADDRESS: i32 = 18
179
+
180
+ /** The caps an `HttpServer` holds itself to; every listener's carrier is checked against them. */
181
+ export class HttpServerLimits {
182
+ /** The most requests held at once, across every connection and version. 1 to 65536. */
183
+ requests: i32 = 1024
184
+ /** The largest request body, in bytes; past it a request is answered 413. 0 to 2^30. */
185
+ maxBody: i32 = 1048576
186
+ /** The largest request head (method, target and fields), in bytes. 256 to 2^20. */
187
+ maxHead: i32 = 32768
188
+ /** The most fields a request may carry. 1 to 1024. */
189
+ maxFields: i32 = 100
190
+ /** The most fields a response may carry, Alt-Svc and content-length included. 2 to 256. */
191
+ maxResponseFields: i32 = 32
192
+ /** Milliseconds from a request's head to the end of its body. */
193
+ bodyTimeout: i32 = 30000
194
+ /** Milliseconds an HTTP/2 connection (over TLS or h2c) with no open stream is kept. */
195
+ idleTimeout: i32 = 60000
196
+ /** Milliseconds a cleartext HTTP/2 connection (`listenH2c`) has to send its 24-byte preface; after it, `idleTimeout` applies. */
197
+ prefaceTimeout: i32 = 10000
198
+ /** Seconds a client may remember the Alt-Svc advertisement; 0 sends `alt-svc: clear`. */
199
+ altSvcMaxAge: i32 = 86400
200
+ /** The port Alt-Svc names; 0 names the HTTP/3 socket's own. */
201
+ altSvcPort: i32 = 0
202
+ /** The most readiness events one `wait` takes. */
203
+ maxEvents: i32 = 256
204
+ /** Bytes in the JSON scratch buffer. At least 256. */
205
+ jsonBytes: i32 = 65536
206
+ }
207
+
208
+ /**
209
+ * One request, whole, from any version: its head copied out of the carrier
210
+ * and its body. Every position is an offset into `head` or `body`, which are
211
+ * the request's own and stay valid until it is answered.
212
+ */
213
+ export class HttpServerRequest {
214
+ /** The method, the target and the header section (field names lowercased); on HTTP/2 and 3, `:authority` is the field `host`. */
215
+ head: u8[]
216
+ /**
217
+ * Four per field, into `head`: name start and end, value start and end.
218
+ * @internal Filled by `HttpServer` in this module when it copies the head, and read by `header`, `valueStart` and `valueEnd`.
219
+ */
220
+ spans: i32[]
221
+ /**
222
+ * The route parameters as `[start, end)` pairs into `head`, in the pattern's order.
223
+ * @internal Filled by `HttpServer` in this module from `Router.match`; programs read them through `paramStart`, `param` and the rest.
224
+ */
225
+ params: i32[]
226
+ /** The body, `body[0 .. bodyLength)`. */
227
+ body: u8[]
228
+ /**
229
+ * What the carrier had no room for yet: `pending[pendingStart .. pendingEnd)`.
230
+ * @internal Written and flushed by `HttpServer` in this module while it streams the response.
231
+ */
232
+ pending: u8[]
233
+ /**
234
+ * When the head was read (`monotonicNanos`); `bodyTimeout` runs from here.
235
+ * @internal Stamped and checked by `HttpServer` in this module.
236
+ */
237
+ since: i64 = 0
238
+ /**
239
+ * The HTTP/2 or HTTP/3 stream the request came on; 0 on HTTP/1.1.
240
+ * @internal Read by `HttpServer` in this module to answer on the stream.
241
+ */
242
+ stream: i64 = 0
243
+ /** The index `Router.add` answered for the route, or a negative `ROUTER_*` code. */
244
+ route: i32 = 0
245
+ /** The HTTP version it came in on: 1, 2 or 3. */
246
+ version: i32 = 1
247
+ /**
248
+ * How many parameter pairs `params` holds.
249
+ * @internal Set by `HttpServer` in this module after routing; the param accessors check `k` against it.
250
+ */
251
+ paramCount: i32 = 0
252
+ /** Where the method starts in `head`; the method is `head[methodStart .. methodEnd)`. */
253
+ methodStart: i32 = 0
254
+ /** Where the method ends in `head`, one past its last byte. */
255
+ methodEnd: i32 = 0
256
+ /** Where the request target (path and query) starts in `head`; the target is `head[targetStart .. targetEnd)`. */
257
+ targetStart: i32 = 0
258
+ /** Where the request target ends in `head`, one past its last byte. */
259
+ targetEnd: i32 = 0
260
+ /**
261
+ * Where the path ends: the target's first `?`, or its end.
262
+ * @internal Set by `HttpServer` in this module when it copies the head, and read by `pathIs` and `queryIndex`.
263
+ */
264
+ pathEnd: i32 = 0
265
+ /**
266
+ * How many fields `spans` describes.
267
+ * @internal Set by `HttpServer` in this module when it copies the head, and read by `header`.
268
+ */
269
+ headerCount: i32 = 0
270
+ /** How many bytes of `body` are the request's body, 0 for none; read the body as `body[0 .. bodyLength)`. */
271
+ bodyLength: i32 = 0
272
+ /** The connection's slot in its carrier. */
273
+ slot: i32 = 0
274
+ /**
275
+ * The slot's generation when this request was read.
276
+ * @internal Read by `HttpServer` in this module, which drops a reply to a slot that has since closed and been reused.
277
+ */
278
+ gen: i32 = 0
279
+ /** Its index in the server's pool. */
280
+ index: i32 = 0
281
+ /**
282
+ * Which carrier it came on, one of the module's private `HTTP_SERVER_H*` kinds.
283
+ * @internal Read by `HttpServer` in this module to answer through that carrier.
284
+ */
285
+ kind: i32 = 0
286
+ /**
287
+ * Where the request is in its life, one of the module's private `HTTP_SERVER_*` states.
288
+ * @internal Moved by `HttpServer` in this module from free through reading, queued, held and streaming, and back.
289
+ */
290
+ state: i32 = 0
291
+ /**
292
+ * Its entry in its connection's stream table; -1 on HTTP/1.1.
293
+ * @internal Kept by `HttpServer` in this module, which frees the entry when the request goes back.
294
+ */
295
+ entry: i32 = -1
296
+ /**
297
+ * The response body bytes the declared length still allows, or -1 for an unknown length.
298
+ * @internal Counted by `HttpServer` in this module on HTTP/2 and 3, whose carriers do not count them.
299
+ */
300
+ left: i32 = -1
301
+ /**
302
+ * Where the unsent bytes in `pending` start.
303
+ * @internal Advanced by `HttpServer` in this module as the carrier takes pending bytes.
304
+ */
305
+ pendingStart: i32 = 0
306
+ /**
307
+ * Where the unsent bytes in `pending` end.
308
+ * @internal Advanced by `HttpServer` in this module as `write` keeps what the carrier had no room for.
309
+ */
310
+ pendingEnd: i32 = 0
311
+ /** The span `queryIndex` found, raw. */
312
+ queryValueStart: i32 = 0
313
+ /** Where the raw value `queryIndex` found ends in `head`, one past its last byte; it starts at `queryValueStart`. */
314
+ queryValueEnd: i32 = 0
315
+ /** Whether it came over TLS or QUIC: true on HTTP/2 over TLS and on HTTP/3. */
316
+ secure: boolean = false
317
+ /**
318
+ * Whether the peer reset the stream or stopped reading it (HTTP/2 and 3).
319
+ * @internal Set by `HttpServer` in this module; such a request is answered `HANDLER_DROPPED`.
320
+ */
321
+ hung: boolean = false
322
+ /**
323
+ * Whether the response head ended the stream (HEAD, 204, 304, an empty body), so body bytes are dropped.
324
+ * @internal Set and read by `HttpServer` in this module on HTTP/2 and 3.
325
+ */
326
+ quiet: boolean = false
327
+ /**
328
+ * Whether the response's stream is ended on our side.
329
+ * @internal Set and read by `HttpServer` in this module on HTTP/2 and 3.
330
+ */
331
+ ended: boolean = false
332
+
333
+ /**
334
+ * An empty request for the server's pool; its buffers are made on its first use.
335
+ * @param index its place in the server's pool, which the free list and the queue name it by
336
+ */
337
+ constructor(index: i32) {
338
+ this.index = index
339
+ this.head = []
340
+ this.spans = []
341
+ this.params = []
342
+ this.body = []
343
+ this.pending = []
344
+ }
345
+
346
+ /**
347
+ * Whether the method is exactly `method` (methods are case-sensitive, RFC 9110 §9.1).
348
+ * @param method the method name to compare with, such as `"GET"`
349
+ * @returns true when the request's method is byte for byte `method`
350
+ */
351
+ methodIs(method: string): boolean {
352
+ return httpServerSpanIs(this.head, this.methodStart, this.methodEnd, method)
353
+ }
354
+
355
+ /**
356
+ * Whether the path, the target up to its `?`, is exactly `path`.
357
+ * @param path the raw path to compare with, still percent-encoded as it came on the wire
358
+ * @returns true when the target's path, without its query, is byte for byte `path`
359
+ */
360
+ pathIs(path: string): boolean {
361
+ return httpServerSpanIs(this.head, this.targetStart, this.pathEnd, path)
362
+ }
363
+
364
+ /**
365
+ * Where parameter `k` starts in `head`. Panics on a parameter the route does not have.
366
+ * @param k the parameter's position in the route pattern, from 0
367
+ * @returns the byte offset in `head` of the parameter's first raw byte
368
+ */
369
+ paramStart(k: i32): i32 {
370
+ this.checkParam(k)
371
+ return this.params[2 * k]
372
+ }
373
+
374
+ /**
375
+ * Where parameter `k` ends in `head`.
376
+ * @param k the parameter's position in the route pattern, from 0
377
+ * @returns the byte offset in `head` just past the parameter's last raw byte
378
+ */
379
+ paramEnd(k: i32): i32 {
380
+ this.checkParam(k)
381
+ return this.params[2 * k + 1]
382
+ }
383
+
384
+ /**
385
+ * Whether parameter `k`, raw, is exactly `text`.
386
+ * @param k the parameter's position in the route pattern, from 0
387
+ * @param text the value to compare with, as it would appear still percent-encoded
388
+ * @returns true when the raw parameter bytes are exactly `text`
389
+ */
390
+ paramIs(k: i32, text: string): boolean {
391
+ this.checkParam(k)
392
+ return httpServerSpanIs(this.head, this.params[2 * k], this.params[2 * k + 1], text)
393
+ }
394
+
395
+ /**
396
+ * Parameter `k` percent-decoded into `out` from 0 (`routerDecode`): its
397
+ * length, `ROUTER_BAD_ESCAPE` for a malformed escape, or `ROUTER_NO_ROOM`
398
+ * when `out` is too short. Nothing is written on a code.
399
+ * @param k the parameter's position in the route pattern, from 0
400
+ * @param out where the decoded bytes go, from index 0; the caller's buffer
401
+ * @returns how many decoded bytes were written, or a negative `ROUTER_*` code
402
+ */
403
+ param(k: i32, out: u8[]): i32 {
404
+ this.checkParam(k)
405
+ return routerDecode(this.head, this.params[2 * k], this.params[2 * k + 1], out)
406
+ }
407
+
408
+ /**
409
+ * Parameter `k` read as a decimal number that is not negative and fits an `i32`, or -1.
410
+ * @param k the parameter's position in the route pattern, from 0
411
+ * @returns the number the parameter's digits spell, or -1 when it is empty, holds a non-digit or overflows
412
+ */
413
+ paramDecimal(k: i32): i32 {
414
+ this.checkParam(k)
415
+ return httpServerDecimal(this.head, this.params[2 * k], this.params[2 * k + 1])
416
+ }
417
+
418
+ private checkParam(k: i32): void {
419
+ if (k < 0 || k >= this.paramCount) {
420
+ panic(`HttpServerRequest.param: the route has ${this.paramCount} parameter(s), not one at ${k}`)
421
+ }
422
+ }
423
+
424
+ /**
425
+ * The first query parameter named `name`, its value decoded into `out` from
426
+ * 0 — `+` as a space and `%XX` as its byte, the form encoding
427
+ * (application/x-www-form-urlencoded) — and its length; a name is compared
428
+ * decoded too. `HANDLER_ABSENT` when no parameter has the name,
429
+ * `ROUTER_BAD_ESCAPE` for a malformed escape in its value, `ROUTER_NO_ROOM`
430
+ * when `out` is too short. A name with no `=` has an empty value.
431
+ * @param name the parameter name to look for, compared with each name after decoding
432
+ * @param out where the decoded value goes, from index 0; the caller's buffer
433
+ * @returns how many decoded bytes were written, or `HANDLER_ABSENT` or a negative `ROUTER_*` code
434
+ */
435
+ query(name: string, out: u8[]): i32 {
436
+ const at: i32 = this.queryIndex(name)
437
+ if (at < 0) {
438
+ return HANDLER_ABSENT
439
+ }
440
+ return httpServerFormDecode(this.head, this.queryValueStart, this.queryValueEnd, out)
441
+ }
442
+
443
+ /**
444
+ * Whether the query holds a parameter named `name`.
445
+ * @param name the parameter name to look for, compared with each name after decoding
446
+ * @returns true when some pair in the query has that name, even with an empty value
447
+ */
448
+ hasQuery(name: string): boolean {
449
+ return this.queryIndex(name) >= 0
450
+ }
451
+
452
+ /**
453
+ * Finds the first parameter named `name`: where its pair starts, or -1; its raw value goes to `queryValue...`.
454
+ * @param name the parameter name to look for, compared with each name after decoding
455
+ * @returns the byte offset in `head` where the matching `name=value` pair starts, or -1 when none matches
456
+ */
457
+ queryIndex(name: string): i32 {
458
+ let at: i32 = this.pathEnd + 1
459
+ const end: i32 = this.targetEnd
460
+ while (at < end) {
461
+ let pairEnd: i32 = at
462
+ while (pairEnd < end && toI32(this.head[pairEnd]) !== 38) {
463
+ pairEnd += 1
464
+ }
465
+ let keyEnd: i32 = at
466
+ while (keyEnd < pairEnd && toI32(this.head[keyEnd]) !== 61) {
467
+ keyEnd += 1
468
+ }
469
+ if (httpServerFormIs(this.head, at, keyEnd, name)) {
470
+ this.queryValueStart = keyEnd < pairEnd ? keyEnd + 1 : pairEnd
471
+ this.queryValueEnd = pairEnd
472
+ return at
473
+ }
474
+ at = pairEnd + 1
475
+ }
476
+ return -1
477
+ }
478
+
479
+ /**
480
+ * The index of the first field named `name`, which is lowercase, or `HANDLER_ABSENT`.
481
+ * @param name the field name in lowercase, since the parser lowercased every name it kept
482
+ * @returns the field's index for `valueStart` and `valueEnd`, or `HANDLER_ABSENT` when no field has the name
483
+ */
484
+ header(name: string): i32 {
485
+ for (let i: i32 = 0; i < this.headerCount; i++) {
486
+ if (httpServerSpanIs(this.head, this.spans[4 * i], this.spans[4 * i + 1], name)) {
487
+ return i
488
+ }
489
+ }
490
+ return HANDLER_ABSENT
491
+ }
492
+
493
+ /**
494
+ * Where field `i`'s value starts in `head`.
495
+ * @param i a field index, as `header` answered it
496
+ * @returns the byte offset in `head` of the value's first byte
497
+ */
498
+ valueStart(i: i32): i32 {
499
+ return this.spans[4 * i + 2]
500
+ }
501
+
502
+ /**
503
+ * Where field `i`'s value ends in `head`.
504
+ * @param i a field index, as `header` answered it
505
+ * @returns the byte offset in `head` just past the value's last byte
506
+ */
507
+ valueEnd(i: i32): i32 {
508
+ return this.spans[4 * i + 3]
509
+ }
510
+
511
+ /**
512
+ * Whether the first field named `name` (lowercase) has exactly the value `value`.
513
+ * @param name the field name in lowercase
514
+ * @param value the value to compare with, byte for byte and case-sensitive
515
+ * @returns true when the field is present and its first occurrence has exactly that value
516
+ */
517
+ headerIs(name: string, value: string): boolean {
518
+ const i: i32 = this.header(name)
519
+ return i >= 0 && httpServerSpanIs(this.head, this.spans[4 * i + 2], this.spans[4 * i + 3], value)
520
+ }
521
+ }
522
+ /** Appends `bytes[start .. end)` to an `Allow` value, after a `, ` if it is not the first. */
523
+ const httpServerAllowAppend = (value: u8[], bytes: u8[], start: i32, end: i32): void => {
524
+ if (value.length > 0) {
525
+ value.push(toU8(44))
526
+ value.push(toU8(32))
527
+ }
528
+ for (let k: i32 = start; k < end; k++) {
529
+ if (k >= 0 && k < toI32(bytes.length)) {
530
+ value.push(bytes[k])
531
+ }
532
+ }
533
+ }
534
+
535
+ /**
536
+ * The size a `pending` buffer of `have` bytes grows to for `need`:
537
+ * `min(2^30, max(need, 2 × have))`, in `i64` so the doubling cannot wrap.
538
+ * The caller has refused a `need` past 2^30.
539
+ */
540
+ const httpServerPendingSize = (have: i32, need: i64): i32 => {
541
+ const doubled: i64 = toI64(have) * toI64(2)
542
+ const size: i64 = need > doubled ? need : doubled
543
+ return size > toI64(HTTP_SERVER_MAX_BODY) ? HTTP_SERVER_MAX_BODY : toI32(size)
544
+ }
545
+
546
+ /** Whether `bytes[start .. end)` is exactly `text`. */
547
+ const httpServerSpanIs = (bytes: u8[], start: i32, end: i32, text: string): boolean => {
548
+ const n: i32 = toI32(text.length)
549
+ if (end - start !== n || start < 0 || end > toI32(bytes.length)) {
550
+ return false
551
+ }
552
+ for (let k: i32 = 0; k < n; k++) {
553
+ if (toI32(bytes[start + k]) !== toI32(text.charCodeAt(k))) {
554
+ return false
555
+ }
556
+ }
557
+ return true
558
+ }
559
+
560
+ /** `bytes[start .. end)` as a decimal number that is not negative and fits an `i32`, or -1. */
561
+ const httpServerDecimal = (bytes: u8[], start: i32, end: i32): i32 => {
562
+ if (start < 0 || end <= start || end - start > 10 || end > toI32(bytes.length)) {
563
+ return -1
564
+ }
565
+ let n: i64 = 0
566
+ for (let k: i32 = start; k < end && k < toI32(bytes.length); k++) {
567
+ const digit: i32 = toI32(bytes[k]) - 48
568
+ if (digit < 0 || digit > 9) {
569
+ return -1
570
+ }
571
+ n = n * toI64(10) + toI64(digit)
572
+ }
573
+ return n > toI64(2147483647) ? -1 : toI32(n)
574
+ }
575
+
576
+ /**
577
+ * The byte the form encoding spells at `bytes[at ..)`, before `end`, and how
578
+ * many bytes it took, packed as `byte | taken << 8`; -1 for a malformed escape.
579
+ */
580
+ const httpServerFormByte = (bytes: u8[], at: i32, end: i32): i32 => {
581
+ const c: i32 = toI32(bytes[at])
582
+ if (c === 43) {
583
+ return 32 | HTTP_SERVER_TOOK_ONE
584
+ }
585
+ if (c !== 37) {
586
+ return c | HTTP_SERVER_TOOK_ONE
587
+ }
588
+ if (at + 2 >= end) {
589
+ return -1
590
+ }
591
+ const hi: i32 = http1HexValue(toI32(bytes[at + 1]))
592
+ const lo: i32 = http1HexValue(toI32(bytes[at + 2]))
593
+ if (hi < 0 || lo < 0) {
594
+ return -1
595
+ }
596
+ return (hi * 16 + lo) | HTTP_SERVER_TOOK_THREE
597
+ }
598
+
599
+ /** Whether `bytes[start .. end)`, form-decoded, is exactly `name`; a malformed escape matches nothing. */
600
+ const httpServerFormIs = (bytes: u8[], start: i32, end: i32, name: string): boolean => {
601
+ const n: i32 = toI32(name.length)
602
+ let at: i32 = start
603
+ let k: i32 = 0
604
+ while (at < end) {
605
+ const packed: i32 = httpServerFormByte(bytes, at, end)
606
+ if (packed < 0 || k >= n || (packed & 255) !== toI32(name.charCodeAt(k))) {
607
+ return false
608
+ }
609
+ at += packed >> 8
610
+ k += 1
611
+ }
612
+ return k === n
613
+ }
614
+
615
+ /**
616
+ * `bytes[start .. end)` form-decoded into `out` from 0: its length,
617
+ * `ROUTER_BAD_ESCAPE`, or `ROUTER_NO_ROOM`. `%00` decodes like any byte, as a
618
+ * route parameter's does.
619
+ */
620
+ const httpServerFormDecode = (bytes: u8[], start: i32, end: i32, out: u8[]): i32 => {
621
+ const length: i32 = percentDecode(
622
+ bytes,
623
+ start,
624
+ end - start,
625
+ out,
626
+ HTTP_SERVER_ZERO,
627
+ URL_DECODE_FORM | URL_DECODE_ALLOW_NUL
628
+ )
629
+ if (length === URL_DECODE_ERR_SPACE) {
630
+ return ROUTER_NO_ROOM
631
+ }
632
+ return length < 0 ? ROUTER_BAD_ESCAPE : length
633
+ }
634
+
635
+ /** Panics unless `limits.<name>`, `value`, is within `low` to `high`. */
636
+ const httpServerLimit = (name: string, value: i32, low: i32, high: i32): void => {
637
+ if (value < low || value > high) {
638
+ panic(`HttpServer: limits.${name} ${value} is outside ${low} to ${high}`)
639
+ }
640
+ }
641
+
642
+ /**
643
+ * One handler for HTTP/1.1, HTTP/2 over TLS and HTTP/3: configure up to one
644
+ * listener of each kind, then loop on `waitSigned` (or `wait`), `ready` and
645
+ * `take`, answering each request with `send`, `json` and `sendJson`,
646
+ * `problem`, `refuse`, or `start`, `write` and `end`.
647
+ */
648
+ export class HttpServer {
649
+ private router: Router
650
+ /** Every request of the pool, made up front, and the indices of the free ones. */
651
+ private requests: HttpServerRequest[]
652
+ private free: i32[]
653
+ /** Whole requests waiting for `take`, a ring of `queue.length` with `queueCount` from `queueStart`. */
654
+ private queue: i32[]
655
+ /** `pollWait`'s output. */
656
+ private readyFds: i32[]
657
+ /** Per watched id: whether its descriptor was ready in the last turn. */
658
+ private watchedFired: boolean[]
659
+ /** `json` and `problem` write here. */
660
+ scratch: u8[]
661
+ /**
662
+ * The JSON writer over `scratch`.
663
+ * @internal Read only by this class; programs get it from `json`.
664
+ */
665
+ writer: JsonWriter
666
+ /** `refuse`'s scratch for `Router.match`. */
667
+ private probe: i32[]
668
+ /** One field for `send`; two for a 405. */
669
+ private typeName: u8[][]
670
+ private typeValue: u8[][]
671
+ private allowNames: u8[][]
672
+ private allowValues: u8[][]
673
+ /** Each `Allow` value made, by the bit mask of the methods it lists: made once a mask and kept. */
674
+ private allowMasks: i64[]
675
+ private allowBytes: u8[][]
676
+ private jsonType: u8[]
677
+ private problemType: u8[]
678
+ private noFields: u8[][]
679
+ /** The response field lists `outFields` builds, by length, made once each and reused. */
680
+ private outNamesBy: u8[][][]
681
+ private outValuesBy: u8[][][]
682
+ /** A content-length value's digits, one buffer per digit count. */
683
+ private digitBufs: u8[][]
684
+ private altSvcName: u8[]
685
+ private contentLengthName: u8[]
686
+ /** The Alt-Svc value, set by `listenHttp3`; null without an HTTP/3 listener. */
687
+ private altSvc: u8[] | null = null
688
+ /** `alt-svc` alone, and its value once there is one: the fields of an HTTP/2 over TLS answer the server gives itself. */
689
+ private altNames: u8[][]
690
+ private altValues: u8[][]
691
+ private bodyTimeout: i64 = 0
692
+ private idleTimeout: i64 = 0
693
+ /** When the current turn's sockets were ready (`monotonicNanos`): a head read in it is stamped with this. */
694
+ private turnAt: i64 = 0
695
+ /** When `wait` next looks for timeouts. */
696
+ private sweepAt: i64 = 0
697
+
698
+ // HTTP/1.1: the carrier, its listener, and per slot its generation, its request (-1 for none) and whether it is open.
699
+ private h1: Http1Server | null = null
700
+ /** Per listener (`-100 - token`): when its rest for want of descriptors ends, 0 while it is not resting. */
701
+ private restUntil: i64[]
702
+ private h1Gen: i32[]
703
+ private h1Current: i32[]
704
+ private h1Open: boolean[]
705
+ /** Slots that stopped reading for want of a free request, `starved`, and whether each is in it. */
706
+ private starved: i32[]
707
+ private h1Starved: boolean[]
708
+ /**
709
+ * Per slot: 0 while no `drive` of it runs, 1 while one does, 2 once a call
710
+ * inside it (an answer screened while it reads) asked for another pass.
711
+ * The nested call only marks it, so the depth stays one however many
712
+ * screened requests one write pipelines.
713
+ */
714
+ private h1Driving: i32[]
715
+
716
+ /** The response fields `start` hands the carrier, set for each response. */
717
+ private outNames: u8[][]
718
+ private outValues: u8[][]
719
+ /** `host`, the field an HTTP/2 or HTTP/3 `:authority` becomes. */
720
+ private hostName: u8[]
721
+
722
+ // HTTP/2: the two carriers, and per slot of either a stream table of
723
+ // `perConnection2` entries. TLS slot `s` is `h2TlsBase + s`, h2c slot `s`
724
+ // is `h2cBase + s`; `h2Clear` says which carrier a slot is on.
725
+ private h2: Http2TlsServer | null = null
726
+ private h2c: Http2CleartextServer | null = null
727
+ private h2TlsBase: i32 = 0
728
+ private h2cBase: i32 = 0
729
+ private h2Clear: boolean[]
730
+ private h2Gen: i32[]
731
+ private h2Open: boolean[]
732
+ /** When a connection last had no stream open, 0 while it has one. */
733
+ private h2IdleSince: i64[]
734
+ /** Per entry: its stream, and its request, -1 for a free entry. */
735
+ private h2Streams: i32[]
736
+ private h2Reqs: i32[]
737
+ private h2Count: i32[]
738
+ private rnd: u8[]
739
+ private keyBuf: u8[]
740
+
741
+ // HTTP/3: the carrier, and per slot a stream table of `perConnection3` entries.
742
+ private h3: Http3Server | null = null
743
+ /** What the drain reads datagrams into, made when it begins: a datagram, its sender and its GRO segment size. */
744
+ private h3Rx: u8[]
745
+ private h3From: u8[]
746
+ private h3Meta: i32[]
747
+ private h3Gen: i32[]
748
+ private h3Streams: i64[]
749
+ private h3Reqs: i32[]
750
+ private h3Count: i32[]
751
+ private queueStart: i32 = 0
752
+ private queueCount: i32 = 0
753
+ private maxBody: i32 = 0
754
+ private maxHead: i32 = 0
755
+ private maxFields: i32 = 0
756
+ private maxResponseFields: i32 = 0
757
+ private altSvcMaxAge: i32 = 0
758
+ private altSvcPort: i32 = 0
759
+ /** The readiness loop's descriptor, from `pollCreate`. */
760
+ private loop: i32 = 0
761
+ private h1Fd: i32 = -1
762
+ private h1OutputSize: i32 = 0
763
+ /** Where `feedStarved` takes the next slot of `starved`; the slots before it are spent. */
764
+ private starvedHead: i32 = 0
765
+ /** Where `fromFields` writes next in a request's head. */
766
+ private headAt: i32 = 0
767
+ private h2Fd: i32 = -1
768
+ private perConnection2: i32 = 1
769
+ /** The cleartext HTTP/2 listener, -1 until `listenH2c`. */
770
+ private h2cFd: i32 = -1
771
+ private prefaceTimeout: i32 = 0
772
+ private perConnection3: i32 = 1
773
+ /** The HTTP/3 listener's UDP socket, or -1. */
774
+ private h3Fd: i32 = -1
775
+ /** Set by `drain`: accept nothing more and close each connection once it is idle. */
776
+ private draining: boolean = false
777
+ /** Whether `json` gave out the writer for a value `sendJson` has not yet sent. */
778
+ private jsonBegun: boolean = false
779
+ private h3Readable: boolean = false
780
+
781
+ /**
782
+ * A server routing through `router`, held to `limits`. It has no listener
783
+ * yet: add them with `listenHttp1`, `listenHttp2Tls` and `listenHttp3`.
784
+ * Panics on a limit outside its range.
785
+ * @param limits the caps and timeouts, read once here
786
+ * @param router the routes, which the server keeps and consults at each request head
787
+ */
788
+ constructor(limits: HttpServerLimits, router: Router) {
789
+ httpServerLimit("requests", limits.requests, 1, HTTP_SERVER_MAX_REQUESTS)
790
+ httpServerLimit("maxBody", limits.maxBody, 0, HTTP_SERVER_MAX_BODY)
791
+ httpServerLimit("maxHead", limits.maxHead, 256, HTTP_SERVER_MAX_HEAD)
792
+ httpServerLimit("maxFields", limits.maxFields, 1, 1024)
793
+ httpServerLimit("maxResponseFields", limits.maxResponseFields, 2, 256)
794
+ httpServerLimit("bodyTimeout", limits.bodyTimeout, 1, 2147483647)
795
+ httpServerLimit("idleTimeout", limits.idleTimeout, 1, 2147483647)
796
+ httpServerLimit("prefaceTimeout", limits.prefaceTimeout, 1, 2147483647)
797
+ httpServerLimit("altSvcMaxAge", limits.altSvcMaxAge, 0, 2147483647)
798
+ httpServerLimit("altSvcPort", limits.altSvcPort, 0, 65535)
799
+ httpServerLimit("maxEvents", limits.maxEvents, 1, 65536)
800
+ httpServerLimit("jsonBytes", limits.jsonBytes, 256, HTTP_SERVER_MAX_BODY)
801
+ this.router = router
802
+ this.maxBody = limits.maxBody
803
+ this.maxHead = limits.maxHead
804
+ this.maxFields = limits.maxFields
805
+ this.maxResponseFields = limits.maxResponseFields
806
+ this.altSvcMaxAge = limits.altSvcMaxAge
807
+ this.altSvcPort = limits.altSvcPort
808
+ this.bodyTimeout = toI64(limits.bodyTimeout) * HTTP_SERVER_NANOS_PER_MS
809
+ this.idleTimeout = toI64(limits.idleTimeout) * HTTP_SERVER_NANOS_PER_MS
810
+ this.prefaceTimeout = limits.prefaceTimeout
811
+ this.requests = []
812
+ this.free = []
813
+ for (let k: i32 = 0; k < limits.requests; k++) {
814
+ this.requests.push(new HttpServerRequest(k))
815
+ this.free.push(limits.requests - 1 - k)
816
+ }
817
+ this.queue = new Array<i32>(limits.requests)
818
+ this.readyFds = new Array<i32>(2 * limits.maxEvents)
819
+ this.watchedFired = new Array<boolean>(HANDLER_MAX_WATCHED)
820
+ this.scratch = new Array<u8>(limits.jsonBytes)
821
+ this.writer = new JsonWriter(this.scratch, HTTP_SERVER_ZERO)
822
+ this.probe = new Array<i32>(2 * router.maxParams + 2)
823
+ this.jsonType = httpFieldBytes("application/json")
824
+ this.problemType = httpFieldBytes("application/problem+json")
825
+ const contentType: u8[] = httpFieldBytes("content-type")
826
+ this.typeName = [contentType]
827
+ this.typeValue = [this.jsonType]
828
+ this.allowNames = [contentType, httpFieldBytes("allow")]
829
+ // The `Allow` value, `allowValues[1]`, is set for each 405.
830
+ this.allowValues = [this.problemType, this.problemType]
831
+ this.allowMasks = []
832
+ this.allowBytes = []
833
+ this.noFields = []
834
+ this.h3Rx = []
835
+ this.h3From = new Array<u8>(HTTP_SERVER_UDP_ADDRESS)
836
+ this.h3Meta = [HTTP_SERVER_ZERO, HTTP_SERVER_ZERO]
837
+ this.outNamesBy = []
838
+ this.outValuesBy = []
839
+ this.digitBufs = []
840
+ for (let d: i32 = 0; d <= 10; d++) {
841
+ this.digitBufs.push(new Array<u8>(d))
842
+ }
843
+ this.altSvcName = httpFieldBytes("alt-svc")
844
+ this.altNames = [this.altSvcName]
845
+ this.altValues = [this.altSvcName]
846
+ if (this.altSvcMaxAge === 0) {
847
+ this.altSvc = httpFieldBytes("clear")
848
+ this.altValues[0] = httpFieldBytes("clear")
849
+ }
850
+ this.contentLengthName = httpFieldBytes("content-length")
851
+ this.hostName = httpFieldBytes("host")
852
+ this.outNames = []
853
+ this.outValues = []
854
+ this.h1Gen = []
855
+ this.h1Current = []
856
+ this.h1Open = []
857
+ this.starved = []
858
+ this.h1Starved = []
859
+ this.h1Driving = []
860
+ this.restUntil = new Array<i64>(4)
861
+ this.h2Clear = []
862
+ this.h2Gen = []
863
+ this.h2Open = []
864
+ this.h2IdleSince = []
865
+ this.h2Streams = []
866
+ this.h2Reqs = []
867
+ this.h2Count = []
868
+ this.rnd = new Array<u8>(32)
869
+ this.keyBuf = new Array<u8>(32)
870
+ this.h3Gen = []
871
+ this.h3Streams = []
872
+ this.h3Reqs = []
873
+ this.h3Count = []
874
+ this.loop = pollCreate()
875
+ if (this.loop < 0) {
876
+ panic(`HttpServer: pollCreate failed: ${this.loop}`)
877
+ }
878
+ }
879
+
880
+ // ---- Listeners ------------------------------------------------------------------
881
+
882
+ /**
883
+ * Serves HTTP/1.1 on `fd`, a listening TCP socket the program made, with up
884
+ * to `slots` connections. Panics on a second HTTP/1.1 listener, or when
885
+ * `config` would let in a head past `limits.maxHead` (its `maxTarget`, its
886
+ * `maxHeaderBytes` and 44 bytes of request line) or more fields than
887
+ * `limits.maxFields`. `config.maxBody` is set to `limits.maxBody`.
888
+ * @param fd the listening socket's descriptor, still the program's to close
889
+ * @param config the carrier's caps and timeouts, kept by the carrier
890
+ * @param slots the most connections held at once
891
+ */
892
+ listenHttp1(fd: i32, config: Http1Config, slots: i32): void {
893
+ if (this.h1Fd >= 0) {
894
+ panic("HttpServer.listenHttp1: an HTTP/1.1 listener is already configured")
895
+ }
896
+ const head: i64 = toI64(config.maxTarget) + toI64(config.maxHeaderBytes) + HTTP_SERVER_H1_LINE_OVERHEAD
897
+ if (head > toI64(this.maxHead)) {
898
+ panic(
899
+ `HttpServer.listenHttp1: maxTarget ${config.maxTarget} + maxHeaderBytes ${config.maxHeaderBytes} + 44 is more than limits.maxHead ${this.maxHead}`
900
+ )
901
+ }
902
+ if (config.maxHeaders > this.maxFields) {
903
+ panic(
904
+ `HttpServer.listenHttp1: maxHeaders ${config.maxHeaders} is more than limits.maxFields ${this.maxFields}`
905
+ )
906
+ }
907
+ if (slots < 1) {
908
+ panic(`HttpServer.listenHttp1: slots ${slots} is below 1`)
909
+ }
910
+ config.maxBody = this.maxBody
911
+ this.h1 = new Http1Server(config, fd, slots)
912
+ this.h1Fd = fd
913
+ this.h1OutputSize = config.outputSize
914
+ this.h1Gen = new Array<i32>(slots)
915
+ this.h1Current = new Array<i32>(slots)
916
+ this.h1Open = new Array<boolean>(slots)
917
+ this.h1Starved = new Array<boolean>(slots)
918
+ this.h1Driving = new Array<i32>(slots)
919
+ for (let s: i32 = 0; s < slots; s++) {
920
+ this.h1Current[s] = -1
921
+ }
922
+ pollAdd(this.loop, fd, H1_WANT_READ, HTTP_SERVER_H1_LISTENER)
923
+ }
924
+
925
+ /**
926
+ * Serves cleartext HTTP/2 (h2c, prior knowledge: no Upgrade from
927
+ * HTTP/1.1) on `fd`, a listening TCP socket the program made, with up to
928
+ * `slots` connections. Meant for a server behind a TLS-terminating proxy
929
+ * or on a trusted network: nothing on it is encrypted. A connection that
930
+ * has not sent its 24-byte preface within `limits.prefaceTimeout` is
931
+ * closed, and one with no open stream after it within `limits.idleTimeout`.
932
+ * Its responses carry no Alt-Svc, and its requests say `secure` false.
933
+ * Each connection holds at most `config.maxStreams` requests and a quarter
934
+ * of `limits.requests`, as on `listenHttp2Tls`. Panics on a second h2c
935
+ * listener, a `maxHeaderListSize` past `limits.maxHead`, or
936
+ * `enableConnectProtocol`. `wait` serves it: it reads no key.
937
+ * @param fd the listening socket's descriptor, still the program's to close
938
+ * @param config the carrier's caps
939
+ * @param slots the most connections held at once
940
+ */
941
+ listenH2c(fd: i32, config: Http2Config, slots: i32): void {
942
+ if (this.h2cFd >= 0) {
943
+ panic("HttpServer.listenH2c: an h2c listener is already configured")
944
+ }
945
+ this.checkHttp2("listenH2c", config, slots)
946
+ this.h2cBase = this.h2Grow(slots, this.perOf(config))
947
+ for (let v: i32 = this.h2cBase; v < this.h2cBase + slots; v++) {
948
+ this.h2Clear[v] = true
949
+ }
950
+ this.h2c = new Http2CleartextServer(config, fd, slots, this.prefaceTimeout)
951
+ this.h2cFd = fd
952
+ pollAdd(this.loop, fd, H1_WANT_READ, HTTP_SERVER_H2C_LISTENER)
953
+ }
954
+
955
+ /** The checks every HTTP/2 listener's configuration passes. */
956
+ private checkHttp2(name: string, config: Http2Config, slots: i32): void {
957
+ if (config.maxHeaderListSize > this.maxHead) {
958
+ panic(
959
+ `HttpServer.${name}: maxHeaderListSize ${config.maxHeaderListSize} is more than limits.maxHead ${this.maxHead}`
960
+ )
961
+ }
962
+ if (config.enableConnectProtocol) {
963
+ panic(`HttpServer.${name}: enableConnectProtocol is not served; extended CONNECT is answered 501`)
964
+ }
965
+ if (slots < 1) {
966
+ panic(`HttpServer.${name}: slots ${slots} is below 1`)
967
+ }
968
+ }
969
+
970
+ /**
971
+ * Serves HTTP/2 over TLS (ALPN `h2`) on `fd`, a listening TCP socket the
972
+ * program made, with up to `slots` connections. Each connection holds at
973
+ * most `config.maxStreams` requests and a quarter of `limits.requests`; a
974
+ * stream past that is refused with REFUSED_STREAM. Panics on a second
975
+ * listener of this kind, a `maxHeaderListSize` past `limits.maxHead`, or
976
+ * `enableConnectProtocol`. Serve it with `waitSigned`.
977
+ * @param fd the listening socket's descriptor, still the program's to close
978
+ * @param tls the certificate chain and TLS settings
979
+ * @param config the carrier's caps
980
+ * @param slots the most connections held at once
981
+ */
982
+ listenHttp2Tls(fd: i32, tls: TlsServerConfig, config: Http2Config, slots: i32): void {
983
+ if (this.h2Fd >= 0) {
984
+ panic("HttpServer.listenHttp2Tls: an HTTP/2 over TLS listener is already configured")
985
+ }
986
+ this.checkHttp2("listenHttp2Tls", config, slots)
987
+ this.h2TlsBase = this.h2Grow(slots, this.perOf(config))
988
+ this.h2 = new Http2TlsServer(tls, config, fd, slots)
989
+ this.h2Fd = fd
990
+ pollAdd(this.loop, fd, H1_WANT_READ, HTTP_SERVER_H2_LISTENER)
991
+ }
992
+
993
+ /** The stream-table entries an HTTP/2 connection under `config` gets: its `maxStreams`, at most a quarter of the pool, at least 1. */
994
+ private perOf(config: Http2Config): i32 {
995
+ let per: i32 = toI32(this.requests.length) / 4
996
+ if (config.maxStreams < per) {
997
+ per = config.maxStreams
998
+ }
999
+ return per < 1 ? 1 : per
1000
+ }
1001
+
1002
+ /**
1003
+ * Adds `slots` HTTP/2 slots after those there are, each table at least
1004
+ * `per` entries, and answers the first new slot. The tables share one
1005
+ * width, the widest asked for, so a wider listener moves every entry,
1006
+ * and every request's `entry`, to the new width.
1007
+ */
1008
+ private h2Grow(slots: i32, per: i32): i32 {
1009
+ const base: i32 = toI32(this.h2Open.length)
1010
+ const was: i32 = this.perConnection2
1011
+ const width: i32 = per > was ? per : was
1012
+ const streams: i32[] = new Array<i32>((base + slots) * width)
1013
+ const reqs: i32[] = new Array<i32>((base + slots) * width)
1014
+ for (let e: i32 = 0; e < toI32(reqs.length); e++) {
1015
+ reqs[e] = -1
1016
+ }
1017
+ for (let v: i32 = 0; v < base; v++) {
1018
+ for (let i: i32 = 0; i < was; i++) {
1019
+ streams[v * width + i] = this.h2Streams[v * was + i]
1020
+ reqs[v * width + i] = this.h2Reqs[v * was + i]
1021
+ }
1022
+ }
1023
+ if (width !== was) {
1024
+ for (let k: i32 = 0; k < toI32(this.requests.length); k++) {
1025
+ const r: HttpServerRequest = this.requests[k]
1026
+ if (r.kind === HTTP_SERVER_H2 && r.entry >= 0) {
1027
+ r.entry = (r.entry / was) * width + (r.entry % was)
1028
+ }
1029
+ }
1030
+ }
1031
+ this.h2Streams = streams
1032
+ this.h2Reqs = reqs
1033
+ this.perConnection2 = width
1034
+ for (let v: i32 = 0; v < slots; v++) {
1035
+ this.h2Gen.push(HTTP_SERVER_ZERO)
1036
+ this.h2Open.push(false)
1037
+ this.h2IdleSince.push(toI64(HTTP_SERVER_ZERO))
1038
+ this.h2Count.push(HTTP_SERVER_ZERO)
1039
+ this.h2Clear.push(false)
1040
+ }
1041
+ return base
1042
+ }
1043
+
1044
+ /**
1045
+ * Serves HTTP/3 on `fd`, a bound UDP socket the program made, with up to
1046
+ * `slots` QUIC connections, and from then on names its port in an Alt-Svc
1047
+ * field on every HTTP/1.1 and HTTP/2 response. Each connection holds at most
1048
+ * `quic.maxStreamsBidi` requests and a quarter of `limits.requests`; a
1049
+ * stream past that is rejected with H3_REQUEST_REJECTED. Panics on a second
1050
+ * HTTP/3 listener, a `maxFieldSectionSize` past `limits.maxHead`, or
1051
+ * `webtransportSessions` above 0. Serve it with `waitSigned`.
1052
+ * @param fd the UDP socket's descriptor, still the program's to close
1053
+ * @param quic the QUIC and TLS settings
1054
+ * @param config the HTTP/3 caps
1055
+ * @param slots the most connections held at once
1056
+ * @param entropy random bytes for the listener's own secrets, as `Http3Server` takes them
1057
+ */
1058
+ listenHttp3(fd: i32, quic: QuicServerConfig, config: Http3Config, slots: i32, entropy: u8[]): void {
1059
+ if (this.h3 !== null) {
1060
+ panic("HttpServer.listenHttp3: an HTTP/3 listener is already configured")
1061
+ }
1062
+ if (config.maxFieldSectionSize > this.maxHead) {
1063
+ panic(
1064
+ `HttpServer.listenHttp3: maxFieldSectionSize ${config.maxFieldSectionSize} is more than limits.maxHead ${this.maxHead}`
1065
+ )
1066
+ }
1067
+ if (config.webtransportSessions > 0) {
1068
+ panic("HttpServer.listenHttp3: webtransportSessions is not served")
1069
+ }
1070
+ if (slots < 1) {
1071
+ panic(`HttpServer.listenHttp3: slots ${slots} is below 1`)
1072
+ }
1073
+ let per: i64 = toI64(toI32(this.requests.length) / 4)
1074
+ if (quic.maxStreamsBidi < per) {
1075
+ per = quic.maxStreamsBidi
1076
+ }
1077
+ this.perConnection3 = per < toI64(1) ? 1 : toI32(per)
1078
+ this.h3 = new Http3Server(quic, config, fd, slots, entropy)
1079
+ this.h3Fd = fd
1080
+ this.h3Gen = new Array<i32>(slots)
1081
+ this.h3Count = new Array<i32>(slots)
1082
+ this.h3Streams = new Array<i64>(slots * this.perConnection3)
1083
+ this.h3Reqs = new Array<i32>(slots * this.perConnection3)
1084
+ for (let k: i32 = 0; k < toI32(this.h3Reqs.length); k++) {
1085
+ this.h3Reqs[k] = -1
1086
+ }
1087
+ if (this.altSvcMaxAge > 0) {
1088
+ const port: i32 = this.altSvcPort > 0 ? this.altSvcPort : netLocalPort(fd)
1089
+ this.setAltSvc(httpFieldBytes(`h3=":${port}"; ma=${this.altSvcMaxAge}`))
1090
+ }
1091
+ pollAdd(this.loop, fd, H1_WANT_READ, HTTP_SERVER_H3_SOCKET)
1092
+ }
1093
+
1094
+ /** Sets the `alt-svc` value every HTTP/1.1 and HTTP/2 over TLS answer carries. */
1095
+ private setAltSvc(value: u8[]): void {
1096
+ this.altSvc = value
1097
+ this.altValues[0] = value
1098
+ }
1099
+
1100
+ // ---- The loop -------------------------------------------------------------------
1101
+
1102
+ /**
1103
+ * Adds `fd` to the descriptors `wait` and `waitSigned` block on, as `id`:
1104
+ * `fired(id)` then says whether it was readable in the last turn. For a
1105
+ * program's own descriptors, such as `signalFd()` for a graceful stop.
1106
+ * Panics on an id outside 0 to `HANDLER_MAX_WATCHED - 1`.
1107
+ * @param fd the program's descriptor to watch for reading; it stays the program's to read and close
1108
+ * @param id the name `fired` asks about it by, from 0 to `HANDLER_MAX_WATCHED - 1`
1109
+ */
1110
+ watch(fd: i32, id: i32): void {
1111
+ if (id < 0 || id >= HANDLER_MAX_WATCHED) {
1112
+ panic(`HttpServer.watch: id ${id} is outside 0 to ${HANDLER_MAX_WATCHED - 1}`)
1113
+ }
1114
+ pollAdd(this.loop, fd, H1_WANT_READ, -2 - id)
1115
+ }
1116
+
1117
+ /**
1118
+ * Whether watched descriptor `id` was ready in the last turn.
1119
+ * @param id the name the descriptor was given to `watch`
1120
+ * @returns true when it was readable in the last turn; false for an id outside the range
1121
+ */
1122
+ fired(id: i32): boolean {
1123
+ return id >= 0 && id < HANDLER_MAX_WATCHED && this.watchedFired[id]
1124
+ }
1125
+
1126
+ /**
1127
+ * One turn of the loop for a server with no TLS or QUIC listener: as
1128
+ * `waitSigned`, with no key. It serves HTTP/1.1 and h2c (`listenH2c`).
1129
+ * Panics when an HTTP/2 over TLS or HTTP/3 listener is configured, since a
1130
+ * handshake there needs the key.
1131
+ * @param timeoutMs the longest to block, in milliseconds, or -1 to block until something is ready
1132
+ * @returns how many whole requests are queued for `take` after this turn
1133
+ */
1134
+ wait(timeoutMs: i32): i32 {
1135
+ if (this.h2Fd >= 0 || this.h3 !== null) {
1136
+ panic("HttpServer.wait: a TLS or QUIC listener needs the certificate's key; call waitSigned")
1137
+ }
1138
+ return this.turnWith(timeoutMs, null)
1139
+ }
1140
+
1141
+ /**
1142
+ * One turn of the loop: waits up to `timeoutMs` (-1 for no limit) for a
1143
+ * socket to be ready, accepts, reads and writes what is, signs each TLS and
1144
+ * QUIC handshake with `key`, closes what is past its timeouts, and answers
1145
+ * how many whole requests are waiting for `take`.
1146
+ * @param timeoutMs the longest to block, in milliseconds, or -1 to block until something is ready
1147
+ * @param key the certificate's P-256 private key; borrowed for the call, still the caller's to wipe
1148
+ * @returns how many whole requests are queued for `take` after this turn
1149
+ */
1150
+ waitSigned(timeoutMs: i32, key: Secret<u8[]>): i32 {
1151
+ return this.turnWith(timeoutMs, key)
1152
+ }
1153
+
1154
+ /** `waitSigned`'s turn, with no key under `wait`, which serves no listener that reads one. */
1155
+ private turnWith(timeoutMs: i32, key: Secret<u8[]> | null): i32 {
1156
+ for (let id: i32 = 0; id < HANDLER_MAX_WATCHED; id++) {
1157
+ this.watchedFired[id] = false
1158
+ }
1159
+ // A starved slot driven here may read a head, so it reads the clock of now.
1160
+ this.turnAt = monotonicNanos()
1161
+ this.feedStarved()
1162
+ let now: i64 = monotonicNanos()
1163
+ let timeout: i32 = this.queueCount > 0 ? 0 : timeoutMs
1164
+ timeout = this.restListener(this.h1Fd, HTTP_SERVER_H1_LISTENER, now, timeout)
1165
+ timeout = this.restListener(this.h2Fd, HTTP_SERVER_H2_LISTENER, now, timeout)
1166
+ timeout = this.restListener(this.h2cFd, HTTP_SERVER_H2C_LISTENER, now, timeout)
1167
+ const h3: Http3Server | null = this.h3
1168
+ if (h3 !== null) {
1169
+ h3.flush(now / HTTP_SERVER_NANOS_PER_MS)
1170
+ const due: i32 = h3.timeout(now / HTTP_SERVER_NANOS_PER_MS)
1171
+ if (due >= 0 && (timeout < 0 || due < timeout)) {
1172
+ timeout = due
1173
+ }
1174
+ }
1175
+ timeout = this.sweepCap(now, timeout)
1176
+ const n: i32 = pollWait(this.loop, this.readyFds, timeout)
1177
+ now = monotonicNanos()
1178
+ this.turnAt = now
1179
+ this.h3Readable = false
1180
+ for (let k: i32 = 0; k < n; k++) {
1181
+ const token: i32 = this.readyFds[2 * k]
1182
+ const events: i32 = this.readyFds[2 * k + 1]
1183
+ if (token === HTTP_SERVER_H1_LISTENER) {
1184
+ this.acceptHttp1()
1185
+ } else if (token === HTTP_SERVER_H2_LISTENER) {
1186
+ this.acceptHttp2()
1187
+ } else if (token === HTTP_SERVER_H2C_LISTENER) {
1188
+ this.acceptH2c()
1189
+ } else if (token === HTTP_SERVER_H3_SOCKET) {
1190
+ this.h3Readable = true
1191
+ } else if (token <= -2 && token > HTTP_SERVER_H1_LISTENER) {
1192
+ const id: i32 = -2 - token
1193
+ if (id < HANDLER_MAX_WATCHED) {
1194
+ this.watchedFired[id] = true
1195
+ }
1196
+ } else if (token >= HTTP_SERVER_H2_BASE) {
1197
+ this.h2Serve(token - HTTP_SERVER_H2_BASE, events, key)
1198
+ } else if (token >= 0) {
1199
+ this.h1Serve(token, events)
1200
+ }
1201
+ }
1202
+ if (h3 !== null && key !== null) {
1203
+ this.h3Turn(h3, now, key)
1204
+ }
1205
+ const h1: Http1Server | null = this.h1
1206
+ if (h1 !== null && h1.expire(now) > 0) {
1207
+ this.h1Sweep(h1)
1208
+ }
1209
+ this.feedStarved()
1210
+ if (now >= this.sweepAt) {
1211
+ this.sweepAt = now + HTTP_SERVER_SWEEP
1212
+ this.expireAll(now)
1213
+ }
1214
+ return this.queueCount
1215
+ }
1216
+
1217
+ /**
1218
+ * `timeout` shortened to wake by the next sweep while any connection is
1219
+ * open, so that `bodyTimeout`, `idleTimeout`, `prefaceTimeout` and the
1220
+ * HTTP/1.1 carrier's own clocks are enforced on a quiet server under
1221
+ * `wait(-1)` too, at most one sweep late.
1222
+ */
1223
+ private sweepCap(now: i64, timeout: i32): i32 {
1224
+ if (this.connections() === 0) {
1225
+ return timeout
1226
+ }
1227
+ const left: i64 = this.sweepAt - now
1228
+ const cap: i32 = left <= 0 ? HTTP_SERVER_ZERO : toI32(left / HTTP_SERVER_NANOS_PER_MS) + 1
1229
+ return timeout < 0 || cap < timeout ? cap : timeout
1230
+ }
1231
+
1232
+ /**
1233
+ * Puts a listener rested for want of descriptors back once its rest is
1234
+ * over, and answers `timeout` shortened to wake for that.
1235
+ */
1236
+ private restListener(fd: i32, token: i32, now: i64, timeout: i32): i32 {
1237
+ const until: i64 = this.restUntil[HTTP_SERVER_H1_LISTENER - token]
1238
+ if (until === 0 || fd < 0) {
1239
+ return timeout
1240
+ }
1241
+ if (now >= until) {
1242
+ this.restUntil[HTTP_SERVER_H1_LISTENER - token] = 0
1243
+ if (!this.draining) {
1244
+ pollAdd(this.loop, fd, H1_WANT_READ, token)
1245
+ }
1246
+ return timeout
1247
+ }
1248
+ if (this.draining) {
1249
+ return timeout
1250
+ }
1251
+ const rest: i32 = toI32((until - now) / HTTP_SERVER_NANOS_PER_MS) + 1
1252
+ return timeout < 0 || rest < timeout ? rest : timeout
1253
+ }
1254
+
1255
+ /**
1256
+ * Begins a graceful stop: the server accepts no more connections, closes
1257
+ * each idle HTTP/1.1 connection now and each other one once its request is
1258
+ * answered, and sends GOAWAY on each HTTP/2 and HTTP/3 connection, which
1259
+ * then closes once its streams are done. A request already read is still
1260
+ * handed over and answered. The listeners are the program's to close.
1261
+ */
1262
+ drain(): void {
1263
+ if (this.draining) {
1264
+ return
1265
+ }
1266
+ this.draining = true
1267
+ this.unlisten(this.h1Fd, HTTP_SERVER_H1_LISTENER)
1268
+ this.unlisten(this.h2Fd, HTTP_SERVER_H2_LISTENER)
1269
+ this.unlisten(this.h2cFd, HTTP_SERVER_H2C_LISTENER)
1270
+ const h1: Http1Server | null = this.h1
1271
+ if (h1 !== null) {
1272
+ for (let s: i32 = 0; s < toI32(this.h1Open.length); s++) {
1273
+ if (this.h1Open[s] && h1.holds(s)) {
1274
+ const conn: Http1Connection = h1.connection(s)
1275
+ if (this.h1Current[s] === -1 && !conn.wantsWrite()) {
1276
+ this.h1Close(h1, s)
1277
+ } else {
1278
+ conn.closeAfter = true
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ for (let v: i32 = 0; v < toI32(this.h2Open.length); v++) {
1284
+ if (this.h2Open[v] && this.h2Holds(v)) {
1285
+ if (this.h2Clear[v] && !this.h2cOf().prefaced(v - this.h2cBase)) {
1286
+ // No preface yet, so no connection to say GOAWAY on.
1287
+ this.h2Close(v)
1288
+ } else {
1289
+ this.h2Conn(v).goaway()
1290
+ this.h2Settle(v)
1291
+ }
1292
+ }
1293
+ }
1294
+ const h3: Http3Server | null = this.h3
1295
+ if (h3 !== null) {
1296
+ for (let s: i32 = 0; s < h3.size(); s++) {
1297
+ if (h3.holds(s)) {
1298
+ h3.connection(s).goaway()
1299
+ h3.touch(s)
1300
+ }
1301
+ }
1302
+ }
1303
+ }
1304
+
1305
+ /** Takes listener `fd` out of the loop, unless it is not there: never configured, or resting. */
1306
+ private unlisten(fd: i32, token: i32): void {
1307
+ if (fd >= 0 && this.restUntil[HTTP_SERVER_H1_LISTENER - token] === 0) {
1308
+ pollRemove(this.loop, fd)
1309
+ }
1310
+ }
1311
+
1312
+ /**
1313
+ * How many connections are open, of every version.
1314
+ * @returns the connections the carriers hold, which falls to 0 after `drain` as they finish
1315
+ */
1316
+ connections(): i32 {
1317
+ let n: i32 = 0
1318
+ const h1: Http1Server | null = this.h1
1319
+ if (h1 !== null) {
1320
+ n += h1.busy()
1321
+ }
1322
+ const h2: Http2TlsServer | null = this.h2
1323
+ if (h2 !== null) {
1324
+ n += h2.busy()
1325
+ }
1326
+ const h2c: Http2CleartextServer | null = this.h2c
1327
+ if (h2c !== null) {
1328
+ n += h2c.busy()
1329
+ }
1330
+ const h3: Http3Server | null = this.h3
1331
+ if (h3 !== null) {
1332
+ n += h3.busy()
1333
+ }
1334
+ return n
1335
+ }
1336
+
1337
+ // ---- HTTP/1.1 -------------------------------------------------------------------
1338
+
1339
+ /** Takes every waiting HTTP/1.1 connection. */
1340
+ private acceptHttp1(): void {
1341
+ const h1: Http1Server | null = this.h1
1342
+ if (h1 === null || this.draining) {
1343
+ return
1344
+ }
1345
+ let slot: i32 = h1.accept()
1346
+ while (slot >= 0 || slot === H1_POOL_FULL || slot === HTTP_SERVER_ACCEPT_ABORTED) {
1347
+ if (slot >= 0) {
1348
+ this.h1Open[slot] = true
1349
+ this.h1Current[slot] = -1
1350
+ pollAdd(this.loop, h1.fd(slot), H1_WANT_READ, slot)
1351
+ }
1352
+ slot = h1.accept()
1353
+ }
1354
+ if (slot !== HTTP_SERVER_ACCEPT_NONE) {
1355
+ // Out of descriptors or memory: the connection stays in the backlog
1356
+ // and the listener stays readable, so rest it rather than spin.
1357
+ this.rest(this.h1Fd, HTTP_SERVER_H1_LISTENER)
1358
+ }
1359
+ }
1360
+
1361
+ /** A ready HTTP/1.1 socket: read or written, then driven. */
1362
+ private h1Serve(slot: i32, events: i32): void {
1363
+ const h1: Http1Server | null = this.h1
1364
+ if (h1 === null || !h1.holds(slot)) {
1365
+ return
1366
+ }
1367
+ if ((events & HTTP_SERVER_READ_BITS) !== 0) {
1368
+ h1.readable(slot)
1369
+ } else {
1370
+ h1.writable(slot)
1371
+ }
1372
+ this.drive(h1, slot)
1373
+ }
1374
+
1375
+ /**
1376
+ * Turns `slot`'s events into requests until it needs more input, then
1377
+ * settles it. A head with no free request left waits: the slot stops
1378
+ * reading and goes on `starved` until a request is handed back.
1379
+ */
1380
+ private drive(h1: Http1Server, slot: i32): void {
1381
+ if (this.h1Driving[slot] !== 0) {
1382
+ this.h1Driving[slot] = 2
1383
+ return
1384
+ }
1385
+ this.h1Driving[slot] = 1
1386
+ this.drivePass(h1, slot)
1387
+ while (this.h1Driving[slot] === 2 && this.h1Open[slot]) {
1388
+ this.h1Driving[slot] = 1
1389
+ this.drivePass(h1, slot)
1390
+ }
1391
+ this.h1Driving[slot] = 0
1392
+ }
1393
+
1394
+ /** One pass of `drive`: the slot's events until it needs more input, then `settle`. */
1395
+ private drivePass(h1: Http1Server, slot: i32): void {
1396
+ const conn: Http1Connection = h1.connection(slot)
1397
+ let event: i32 = H1_NEED_MORE
1398
+ if (!this.starve(slot) && !this.unended(slot)) {
1399
+ event = h1.next(slot)
1400
+ while (event !== H1_NEED_MORE && event !== H1_ERROR) {
1401
+ if (event === H1_REQUEST) {
1402
+ this.begin(slot, conn)
1403
+ } else if (event === H1_BODY) {
1404
+ this.gather(slot, conn)
1405
+ } else if (event === H1_END) {
1406
+ this.whole(slot, conn)
1407
+ } else if (event === H1_WRITE) {
1408
+ this.resume(slot, conn)
1409
+ }
1410
+ if (this.starve(slot) || this.unended(slot)) {
1411
+ break
1412
+ }
1413
+ event = h1.next(slot)
1414
+ }
1415
+ }
1416
+ if (event === H1_ERROR) {
1417
+ // The carrier has written its refusal and ends the connection; a
1418
+ // request it was reading is nobody's.
1419
+ this.releaseReading(slot)
1420
+ }
1421
+ this.settle(h1, slot, conn)
1422
+ }
1423
+
1424
+ /**
1425
+ * Whether `slot`'s response is under way with every byte handed over but
1426
+ * not yet ended. The carrier finishes a `Content-Length` response once its
1427
+ * last byte is written and would read the next request on the next `next`,
1428
+ * so the slot is not asked until the program's `end`: until then the
1429
+ * response is the program's, and a draining connection stays open for it.
1430
+ */
1431
+ private unended(slot: i32): boolean {
1432
+ const at: i32 = this.h1Current[slot]
1433
+ if (at < 0) {
1434
+ return false
1435
+ }
1436
+ const r: HttpServerRequest = this.requests[at]
1437
+ return r.state === HTTP_SERVER_STREAMING && r.pendingEnd === r.pendingStart
1438
+ }
1439
+
1440
+ /** Whether `slot` must wait for a free request before it reads a head: it then joins `starved`. */
1441
+ private starve(slot: i32): boolean {
1442
+ if (this.h1Current[slot] !== -1 || toI32(this.free.length) > 0) {
1443
+ return false
1444
+ }
1445
+ if (!this.h1Starved[slot]) {
1446
+ this.h1Starved[slot] = true
1447
+ this.starved.push(slot)
1448
+ }
1449
+ return true
1450
+ }
1451
+
1452
+ /** Drives the starved slots again while requests are free. */
1453
+ private feedStarved(): void {
1454
+ const h1: Http1Server | null = this.h1
1455
+ if (h1 === null) {
1456
+ return
1457
+ }
1458
+ while (this.starvedHead < toI32(this.starved.length) && toI32(this.free.length) > 0) {
1459
+ const slot: i32 = this.starved[this.starvedHead]
1460
+ this.starvedHead += 1
1461
+ this.h1Starved[slot] = false
1462
+ if (this.h1Open[slot] && h1.holds(slot)) {
1463
+ this.drive(h1, slot)
1464
+ }
1465
+ }
1466
+ // Drop the spent slots once they are half the list, so each is moved O(1) times.
1467
+ const spent: i32 = this.starvedHead
1468
+ const length: i32 = toI32(this.starved.length)
1469
+ if (spent > 0 && spent * 2 >= length) {
1470
+ for (let k: i32 = spent; k < length; k++) {
1471
+ this.starved[k - spent] = this.starved[k]
1472
+ }
1473
+ for (let k: i32 = 0; k < spent; k++) {
1474
+ this.starved.pop()
1475
+ }
1476
+ this.starvedHead = 0
1477
+ }
1478
+ }
1479
+
1480
+ /** Sends what `slot` holds and re-arms it, or closes it once it is over; enqueues a parked request once there is room. */
1481
+ private settle(h1: Http1Server, slot: i32, conn: Http1Connection): void {
1482
+ let wants: i32 = h1.flush(slot)
1483
+ if ((wants & H1_DONE) !== 0) {
1484
+ this.h1Close(h1, slot)
1485
+ return
1486
+ }
1487
+ if (this.draining && this.h1Current[slot] === -1 && !conn.wantsWrite()) {
1488
+ this.h1Close(h1, slot)
1489
+ return
1490
+ }
1491
+ if (this.h1Starved[slot]) {
1492
+ wants = wants & ~H1_WANT_READ
1493
+ }
1494
+ if (h1.rearm(slot, wants)) {
1495
+ pollModify(this.loop, h1.fd(slot), wants & (H1_WANT_READ | H1_WANT_WRITE), slot)
1496
+ }
1497
+ const at: i32 = this.h1Current[slot]
1498
+ if (at >= 0 && this.requests[at].state === HTTP_SERVER_PARKED && this.roomy(conn)) {
1499
+ this.h1Ready(this.requests[at])
1500
+ }
1501
+ }
1502
+
1503
+ /** Whether `conn`'s output holds at most half its size unsent, so a response head fits behind it. */
1504
+ private roomy(conn: Http1Connection): boolean {
1505
+ return (conn.outputEnd - conn.outputStart) * 2 <= this.h1OutputSize
1506
+ }
1507
+
1508
+ /** A head: a free request, the head copied into it, and its route. */
1509
+ private begin(slot: i32, conn: Http1Connection): void {
1510
+ if (this.draining) {
1511
+ // A head read during the drain is the connection's last.
1512
+ conn.closeAfter = true
1513
+ }
1514
+ const r: HttpServerRequest = this.requests[this.obtain()]
1515
+ const p = conn.parser
1516
+ copyBytes(r.head, HTTP_SERVER_ZERO, p.head, HTTP_SERVER_ZERO, p.headLength)
1517
+ const spanCount: i32 = 4 * p.headerCount
1518
+ for (let k: i32 = 0; k < spanCount; k++) {
1519
+ r.spans[k] = p.spans[k]
1520
+ }
1521
+ r.headerCount = p.headerCount
1522
+ r.methodStart = p.methodStart
1523
+ r.methodEnd = p.methodEnd
1524
+ r.targetStart = p.targetStart
1525
+ r.targetEnd = p.targetEnd
1526
+ r.kind = HTTP_SERVER_H1
1527
+ r.version = 1
1528
+ r.secure = false
1529
+ r.slot = slot
1530
+ r.gen = this.h1Gen[slot]
1531
+ if (r.methodIs("CONNECT")) {
1532
+ // Its 501 ends the connection: the client may already be sending what
1533
+ // it meant for a tunnel.
1534
+ conn.closeAfter = true
1535
+ }
1536
+ this.admit(r)
1537
+ this.h1Current[slot] = r.index
1538
+ }
1539
+
1540
+ /** Body bytes: appended to the request's body, which the carrier's cap bounds. */
1541
+ private gather(slot: i32, conn: Http1Connection): void {
1542
+ const at: i32 = this.h1Current[slot]
1543
+ if (at >= 0) {
1544
+ this.append(this.requests[at], conn.data, conn.dataStart, conn.dataLength)
1545
+ }
1546
+ }
1547
+
1548
+ /** The request is whole: queued for `take`, or parked while the response before it is still mostly unsent. */
1549
+ private whole(slot: i32, conn: Http1Connection): void {
1550
+ const at: i32 = this.h1Current[slot]
1551
+ if (at < 0) {
1552
+ return
1553
+ }
1554
+ const r: HttpServerRequest = this.requests[at]
1555
+ if (this.roomy(conn)) {
1556
+ this.h1Ready(r)
1557
+ } else {
1558
+ r.state = HTTP_SERVER_PARKED
1559
+ }
1560
+ }
1561
+
1562
+ /** A whole HTTP/1.1 request with room for its answer: answered at once when `h1Screen` says so, else queued for `take`. */
1563
+ private h1Ready(r: HttpServerRequest): void {
1564
+ const status: i32 = this.h1Screen(r)
1565
+ if (status === 0) {
1566
+ this.enqueue(r)
1567
+ return
1568
+ }
1569
+ r.state = HTTP_SERVER_HELD
1570
+ this.empty(r, status)
1571
+ }
1572
+
1573
+ /** The status an HTTP/1.1 request is answered with at once, or 0 to serve it: 501 for CONNECT and 204 for `OPTIONS *`, as `screen` answers them on HTTP/2 and HTTP/3. */
1574
+ private h1Screen(r: HttpServerRequest): i32 {
1575
+ if (r.methodIs("CONNECT")) {
1576
+ return 501
1577
+ }
1578
+ if (r.targetEnd - r.targetStart === 1 && toI32(r.head[r.targetStart]) === 42 && r.methodIs("OPTIONS")) {
1579
+ return 204
1580
+ }
1581
+ return 0
1582
+ }
1583
+
1584
+ /** `H1_WRITE`: the carrier has room again for the response under way. */
1585
+ private resume(slot: i32, conn: Http1Connection): void {
1586
+ const at: i32 = this.h1Current[slot]
1587
+ if (at < 0) {
1588
+ return
1589
+ }
1590
+ const r: HttpServerRequest = this.requests[at]
1591
+ if (r.state !== HTTP_SERVER_STREAMING && r.state !== HTTP_SERVER_FLUSHING) {
1592
+ return
1593
+ }
1594
+ this.pushH1(r, conn)
1595
+ if (r.state === HTTP_SERVER_FLUSHING) {
1596
+ this.finishH1(r, conn)
1597
+ }
1598
+ }
1599
+
1600
+ /** Hands the carrier as much of `r`'s pending bytes as it takes. */
1601
+ private pushH1(r: HttpServerRequest, conn: Http1Connection): void {
1602
+ const left: i32 = r.pendingEnd - r.pendingStart
1603
+ if (left === 0) {
1604
+ return
1605
+ }
1606
+ const taken: i32 = conn.write(r.pending, r.pendingStart, left)
1607
+ if (taken > 0) {
1608
+ this.taken(r, taken)
1609
+ }
1610
+ }
1611
+
1612
+ /** Ends `r`'s response once nothing is pending, and hands `r` back; otherwise leaves it flushing. */
1613
+ private finishH1(r: HttpServerRequest, conn: Http1Connection): void {
1614
+ r.state = HTTP_SERVER_FLUSHING
1615
+ if (r.pendingEnd > r.pendingStart) {
1616
+ return
1617
+ }
1618
+ // `H1_AGAIN`: no room for the last chunk yet; `H1_WRITE` comes back here.
1619
+ if (conn.end() === H1_AGAIN) {
1620
+ return
1621
+ }
1622
+ this.h1Current[r.slot] = -1
1623
+ this.release(r)
1624
+ }
1625
+
1626
+ /** Hands back the request `slot` was reading when the carrier refused it. */
1627
+ private releaseReading(slot: i32): void {
1628
+ const at: i32 = this.h1Current[slot]
1629
+ if (at >= 0 && this.requests[at].state === HTTP_SERVER_READING) {
1630
+ this.h1Current[slot] = -1
1631
+ this.release(this.requests[at])
1632
+ }
1633
+ }
1634
+
1635
+ /**
1636
+ * Closes `slot` and bumps its generation, so any answer still owed for it is
1637
+ * dropped. A request the server alone holds goes back now; one queued or
1638
+ * taken goes back when `ready` passes it or the program answers it.
1639
+ */
1640
+ private h1Close(h1: Http1Server, slot: i32): void {
1641
+ h1.close(slot)
1642
+ this.h1Forget(slot)
1643
+ }
1644
+
1645
+ /** The bookkeeping of a slot the carrier has closed. */
1646
+ private h1Forget(slot: i32): void {
1647
+ this.h1Open[slot] = false
1648
+ this.h1Gen[slot] = this.h1Gen[slot] + 1
1649
+ const at: i32 = this.h1Current[slot]
1650
+ this.h1Current[slot] = -1
1651
+ if (at >= 0) {
1652
+ this.drop(this.requests[at])
1653
+ }
1654
+ }
1655
+
1656
+ /** Every slot the carrier's `expire` closed. */
1657
+ private h1Sweep(h1: Http1Server): void {
1658
+ for (let s: i32 = 0; s < toI32(this.h1Open.length); s++) {
1659
+ if (this.h1Open[s] && !h1.holds(s)) {
1660
+ this.h1Forget(s)
1661
+ }
1662
+ }
1663
+ }
1664
+
1665
+ // ---- The pool -------------------------------------------------------------------
1666
+
1667
+ /** The index of a free request, its buffers made at their caps on first use; -1 when none is free. */
1668
+ private obtain(): i32 {
1669
+ const count: i32 = toI32(this.free.length)
1670
+ if (count === 0) {
1671
+ return -1
1672
+ }
1673
+ const at: i32 = this.free[count - 1]
1674
+ this.free.pop()
1675
+ const r: HttpServerRequest = this.requests[at]
1676
+ if (toI32(r.head.length) === 0) {
1677
+ r.head = new Array<u8>(this.maxHead)
1678
+ r.spans = new Array<i32>(4 * this.maxFields)
1679
+ r.params = new Array<i32>(2 * this.router.maxParams + 2)
1680
+ }
1681
+ return at
1682
+ }
1683
+
1684
+ /** A head is in `r`: its path's end found, its reading state set and its route matched. */
1685
+ private admit(r: HttpServerRequest): void {
1686
+ let pathEnd: i32 = r.targetStart
1687
+ while (pathEnd < r.targetEnd && toI32(r.head[pathEnd]) !== 63) {
1688
+ pathEnd += 1
1689
+ }
1690
+ r.pathEnd = pathEnd
1691
+ r.bodyLength = 0
1692
+ r.since = this.turnAt
1693
+ r.state = HTTP_SERVER_READING
1694
+ r.pendingStart = 0
1695
+ r.pendingEnd = 0
1696
+ r.hung = false
1697
+ r.quiet = r.methodIs("HEAD")
1698
+ r.left = -1
1699
+ r.ended = false
1700
+ this.route(r)
1701
+ const declared: i32 = this.declared(r)
1702
+ if (declared > toI32(r.body.length)) {
1703
+ this.growBody(r, declared)
1704
+ }
1705
+ }
1706
+
1707
+ /**
1708
+ * Routes `r` through the router. A HEAD that only a GET route matches takes
1709
+ * that route, since a GET resource answers HEAD (RFC 9110 §9.3.2) and no
1710
+ * body is sent for it.
1711
+ */
1712
+ private route(r: HttpServerRequest): void {
1713
+ const params: i32[] = r.params
1714
+ let route: i32 = this.router.match(
1715
+ r.head,
1716
+ r.methodStart,
1717
+ r.methodEnd,
1718
+ r.head,
1719
+ r.targetStart,
1720
+ r.targetEnd,
1721
+ params
1722
+ )
1723
+ if (route === ROUTER_METHOD_NOT_ALLOWED && r.quiet) {
1724
+ const get: i32 = this.router.methodIndex("GET")
1725
+ if (get >= 0) {
1726
+ const viaGet: i32 = this.router.match(
1727
+ this.router.methodBytes,
1728
+ this.router.methodStart[get],
1729
+ this.router.methodEnd[get],
1730
+ r.head,
1731
+ r.targetStart,
1732
+ r.targetEnd,
1733
+ params
1734
+ )
1735
+ if (viaGet >= 0) {
1736
+ route = viaGet
1737
+ }
1738
+ }
1739
+ }
1740
+ r.route = route
1741
+ r.paramCount = route >= 0 ? this.router.paramCount(route) : 0
1742
+ }
1743
+
1744
+ /** Appends `buf[start .. start + n)` to `r`'s body; the caller has kept it within `maxBody`. */
1745
+ private append(r: HttpServerRequest, buf: u8[], start: i32, n: i32): void {
1746
+ const need: i32 = r.bodyLength + n
1747
+ if (toI32(r.body.length) < need) {
1748
+ this.growBody(r, need)
1749
+ }
1750
+ copyBytes(r.body, r.bodyLength, buf, start, n)
1751
+ r.bodyLength = need
1752
+ }
1753
+
1754
+ /**
1755
+ * Grows `r`'s body to hold `need` bytes, in the two tiers of
1756
+ * docs/http-one-handler.md §6. With `T = min(65536, maxBody)`, a body that
1757
+ * fits in `T` grows to `min(T, max(need, 2 × current))`, from 64; one
1758
+ * past `T` is replaced once by an array of exactly `maxBody`, which never
1759
+ * grows again. An entry so holds less than `maxBody + 3 × T` in body
1760
+ * arrays, the abandoned ones included.
1761
+ */
1762
+ private growBody(r: HttpServerRequest, need: i32): void {
1763
+ const have: i32 = toI32(r.body.length)
1764
+ const tier: i32 = this.maxBody < HTTP_SERVER_BODY_TIER ? this.maxBody : HTTP_SERVER_BODY_TIER
1765
+ let size: i32 = this.maxBody
1766
+ if (need <= tier) {
1767
+ size = have < HTTP_SERVER_BODY_FIRST ? HTTP_SERVER_BODY_FIRST : have * 2
1768
+ if (size < need) {
1769
+ size = need
1770
+ }
1771
+ if (size > tier) {
1772
+ size = tier
1773
+ }
1774
+ }
1775
+ const grown: u8[] = new Array<u8>(size)
1776
+ copyBytes(grown, HTTP_SERVER_ZERO, r.body, HTTP_SERVER_ZERO, r.bodyLength)
1777
+ r.body = grown
1778
+ }
1779
+
1780
+ /**
1781
+ * The `content-length` `r` declared, or -1 for none: its body array is
1782
+ * grown toward it in one step rather than many, to the length itself up to
1783
+ * 64 KiB and to `maxBody` past that. The carrier has
1784
+ * checked the value's syntax and refused one past `maxBody`.
1785
+ */
1786
+ private declared(r: HttpServerRequest): i32 {
1787
+ const i: i32 = r.header("content-length")
1788
+ if (i < 0) {
1789
+ return -1
1790
+ }
1791
+ let n: i32 = 0
1792
+ for (let k: i32 = r.valueStart(i); k < r.valueEnd(i); k++) {
1793
+ const d: i32 = toI32(r.head[k]) - HTTP_SERVER_ZERO_DIGIT
1794
+ if (d < 0 || d > 9 || n > (this.maxBody - d) / HTTP_SERVER_TEN) {
1795
+ return -1
1796
+ }
1797
+ n = n * HTTP_SERVER_TEN + d
1798
+ }
1799
+ return n
1800
+ }
1801
+
1802
+ /** Queues `r` for `take`. The ring holds every request, so it never fills. */
1803
+ private enqueue(r: HttpServerRequest): void {
1804
+ r.state = HTTP_SERVER_QUEUED
1805
+ const size: i32 = toI32(this.queue.length)
1806
+ this.queue[(this.queueStart + this.queueCount) % size] = r.index
1807
+ this.queueCount += 1
1808
+ }
1809
+
1810
+ /** Hands `r` back to the pool, and frees its HTTP/2 or HTTP/3 stream entry. */
1811
+ private release(r: HttpServerRequest): void {
1812
+ if (r.state === HTTP_SERVER_FREE) {
1813
+ return
1814
+ }
1815
+ this.unlink(r)
1816
+ r.state = HTTP_SERVER_FREE
1817
+ this.free.push(r.index)
1818
+ }
1819
+
1820
+ /**
1821
+ * Marks `r` hung up, its connection or stream gone, and hands it back unless
1822
+ * it is queued or the program's to answer.
1823
+ */
1824
+ private drop(r: HttpServerRequest): void {
1825
+ r.hung = true
1826
+ if (
1827
+ r.state === HTTP_SERVER_READING ||
1828
+ r.state === HTTP_SERVER_PARKED ||
1829
+ r.state === HTTP_SERVER_FLUSHING
1830
+ ) {
1831
+ this.release(r)
1832
+ }
1833
+ }
1834
+
1835
+ /** `n` of `r`'s pending bytes were taken. */
1836
+ private taken(r: HttpServerRequest, n: i32): void {
1837
+ r.pendingStart += n
1838
+ if (r.pendingStart === r.pendingEnd) {
1839
+ r.pendingStart = 0
1840
+ r.pendingEnd = 0
1841
+ }
1842
+ }
1843
+
1844
+ /**
1845
+ * Appends bytes to `r`'s pending buffer, grown to
1846
+ * `min(2^30, max(needed, 2 × current))`; `write` has refused a remainder
1847
+ * past 2^30.
1848
+ */
1849
+ private keep(r: HttpServerRequest, buf: u8[], off: i32, len: i32): void {
1850
+ const live: i32 = r.pendingEnd - r.pendingStart
1851
+ if (toI32(r.pending.length) - r.pendingEnd < len) {
1852
+ const need: i64 = toI64(live) + toI64(len)
1853
+ const target: u8[] =
1854
+ toI64(r.pending.length) < need
1855
+ ? new Array<u8>(httpServerPendingSize(toI32(r.pending.length), need))
1856
+ : r.pending
1857
+ copyBytes(target, HTTP_SERVER_ZERO, r.pending, r.pendingStart, live)
1858
+ r.pending = target
1859
+ r.pendingStart = 0
1860
+ r.pendingEnd = live
1861
+ }
1862
+ copyBytes(r.pending, r.pendingEnd, buf, off, len)
1863
+ r.pendingEnd += len
1864
+ }
1865
+
1866
+ // ---- Requests -------------------------------------------------------------------
1867
+
1868
+ /**
1869
+ * Whether a whole request is waiting for `take`. Requests whose connection
1870
+ * or stream closed while queued are handed back here.
1871
+ * @returns true when `take` will give out a request whose connection is still open
1872
+ */
1873
+ ready(): boolean {
1874
+ while (this.queueCount > 0) {
1875
+ const r: HttpServerRequest = this.requests[this.queue[this.queueStart]]
1876
+ if (this.live(r)) {
1877
+ return true
1878
+ }
1879
+ this.queueStart = (this.queueStart + 1) % toI32(this.queue.length)
1880
+ this.queueCount -= 1
1881
+ this.release(r)
1882
+ }
1883
+ return false
1884
+ }
1885
+
1886
+ /**
1887
+ * The next whole request, of any version, which the program now owes an
1888
+ * answer. Panics when none is `ready`.
1889
+ * @returns the oldest queued request, the program's until it answers it
1890
+ */
1891
+ take(): HttpServerRequest {
1892
+ if (!this.ready()) {
1893
+ panic("HttpServer.take: no request is ready")
1894
+ }
1895
+ const r: HttpServerRequest = this.requests[this.queue[this.queueStart]]
1896
+ this.queueStart = (this.queueStart + 1) % toI32(this.queue.length)
1897
+ this.queueCount -= 1
1898
+ r.state = HTTP_SERVER_HELD
1899
+ return r
1900
+ }
1901
+
1902
+ /**
1903
+ * Whether the client of `r` has hung up: its connection is closed or
1904
+ * reused, its HTTP/2 or HTTP/3 stream was reset, or, on HTTP/1.1 and
1905
+ * HTTP/2, the peer ended its byte stream while `r` is held. On HTTP/2 that
1906
+ * is the connection's end of input, an end of file or a read error, so it
1907
+ * includes a client that half-closed TCP after sending its request and
1908
+ * may still read an answer: `send` then says which. Panics on another
1909
+ * server's request.
1910
+ * @param r a request `take` handed over
1911
+ * @returns true once nobody is left to read `r`'s answer
1912
+ */
1913
+ hungUp(r: HttpServerRequest): boolean {
1914
+ this.own(r, "hungUp")
1915
+ if (!this.live(r)) {
1916
+ return true
1917
+ }
1918
+ if (r.kind === HTTP_SERVER_H2) {
1919
+ return this.h2Conn(r.slot).inputEnded
1920
+ }
1921
+ const h1: Http1Server | null = this.h1
1922
+ return r.kind === HTTP_SERVER_H1 && h1 !== null && h1.connection(r.slot).ended()
1923
+ }
1924
+
1925
+ /** Panics, naming `who`, unless `r` is one of this server's own requests. */
1926
+ private own(r: HttpServerRequest, who: string): void {
1927
+ const index: i32 = r.index
1928
+ if (index < 0 || index >= toI32(this.requests.length) || this.requests[index] !== r) {
1929
+ panic(`HttpServer.${who}: the request is another server's`)
1930
+ }
1931
+ }
1932
+
1933
+ /** Whether `r`'s connection is the one it was read on, still open, and its stream not reset. */
1934
+ private live(r: HttpServerRequest): boolean {
1935
+ if (r.kind === HTTP_SERVER_H1) {
1936
+ const h1: Http1Server | null = this.h1
1937
+ return h1 !== null && h1.holds(r.slot) && this.h1Gen[r.slot] === r.gen
1938
+ }
1939
+ if (r.hung) {
1940
+ return false
1941
+ }
1942
+ if (r.kind === HTTP_SERVER_H2) {
1943
+ return this.h2Holds(r.slot) && this.h2Gen[r.slot] === r.gen
1944
+ }
1945
+ const h3: Http3Server | null = this.h3
1946
+ return h3 !== null && h3.holds(r.slot) && h3.connection(r.slot).generation === r.gen
1947
+ }
1948
+
1949
+ /** Frees the HTTP/2 or HTTP/3 stream entry `r` holds, if it still holds it. */
1950
+ private unlink(r: HttpServerRequest): void {
1951
+ const e: i32 = r.entry
1952
+ r.entry = -1
1953
+ if (e < 0) {
1954
+ return
1955
+ }
1956
+ if (r.kind === HTTP_SERVER_H2) {
1957
+ if (this.h2Reqs[e] === r.index && this.h2Gen[r.slot] === r.gen) {
1958
+ this.h2Reqs[e] = -1
1959
+ this.h2Count[r.slot] = this.h2Count[r.slot] - 1
1960
+ if (this.h2Count[r.slot] === 0) {
1961
+ this.h2IdleSince[r.slot] = this.turnAt
1962
+ }
1963
+ }
1964
+ } else if (r.kind === HTTP_SERVER_H3) {
1965
+ if (this.h3Reqs[e] === r.index && this.h3Gen[r.slot] === r.gen) {
1966
+ this.h3Reqs[e] = -1
1967
+ this.h3Count[r.slot] = this.h3Count[r.slot] - 1
1968
+ }
1969
+ }
1970
+ }
1971
+
1972
+ // ---- Answers --------------------------------------------------------------------
1973
+
1974
+ /**
1975
+ * Starts `r`'s response: `status` (200 to 599), the fields `names[k]`:
1976
+ * `values[k]`, and a body of `bodyLength` bytes or `HTTP1_CHUNKED` for one
1977
+ * of unknown length; then `write` the body and `end`. On HTTP/2 and HTTP/3
1978
+ * the field names must be lowercase, and a `content-length` is added for a
1979
+ * known length the fields do not give; on HTTP/1.1 and HTTP/2 the Alt-Svc
1980
+ * field is added when an HTTP/3 listener is set and the fields have none.
1981
+ * Panics on another server's request, a request not taken or already
1982
+ * answered, a status outside the range, a body length below
1983
+ * `HTTP1_CHUNKED`, or fields the carrier refuses.
1984
+ * @param r a request taken and not yet answered
1985
+ * @param status the response status, from 200 to 599
1986
+ * @param names the field names, as bytes, beside `values`
1987
+ * @param values each field's value, `values[k]` for `names[k]`
1988
+ * @param bodyLength how many body bytes will follow, or `HTTP1_CHUNKED` for a body of unknown length
1989
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or
1990
+ * stream closed first, or the head could not be sent (too many fields, or
1991
+ * no room) and the request was aborted for it
1992
+ */
1993
+ start(r: HttpServerRequest, status: i32, names: u8[][], values: u8[][], bodyLength: i32): i32 {
1994
+ this.own(r, "start")
1995
+ if (r.state !== HTTP_SERVER_HELD) {
1996
+ panic(`HttpServer.start: the request is not one taken and unanswered (state ${r.state})`)
1997
+ }
1998
+ if (status < 200 || status > 599) {
1999
+ panic(`HttpServer.start: status ${status} is outside 200 to 599`)
2000
+ }
2001
+ if (bodyLength < HTTP1_CHUNKED) {
2002
+ panic(`HttpServer.start: body length ${bodyLength}`)
2003
+ }
2004
+ if (toI32(names.length) !== toI32(values.length)) {
2005
+ panic(`HttpServer.start: ${names.length} name(s) beside ${values.length} value(s)`)
2006
+ }
2007
+ r.state = HTTP_SERVER_STREAMING
2008
+ if (!this.live(r)) {
2009
+ return HANDLER_DROPPED
2010
+ }
2011
+ const noBody: boolean = status === 204 || status === 304
2012
+ r.quiet = r.quiet || noBody
2013
+ r.left = noBody ? 0 : bodyLength
2014
+ if (!this.outFields(r, names, values, bodyLength)) {
2015
+ this.abort(r)
2016
+ return HANDLER_DROPPED
2017
+ }
2018
+ if (r.kind === HTTP_SERVER_H1) {
2019
+ const conn: Http1Connection = this.h1Of().connection(r.slot)
2020
+ const sent: i32 = conn.respond(
2021
+ status,
2022
+ this.outNames,
2023
+ this.outValues,
2024
+ noBody ? HTTP1_NO_BODY : bodyLength
2025
+ )
2026
+ if (sent === H1_AGAIN) {
2027
+ // The output still holds more of the response before this one than a
2028
+ // head can fit behind: ending the connection is the one answer left.
2029
+ this.abort(r)
2030
+ return HANDLER_DROPPED
2031
+ }
2032
+ if (sent !== 0) {
2033
+ panic(
2034
+ `HttpServer.start: the carrier refused the head (${sent}): a reserved field, or a name or value that is not a token or field text`
2035
+ )
2036
+ }
2037
+ return HANDLER_SENT
2038
+ }
2039
+ const endNow: boolean = r.quiet || bodyLength === 0
2040
+ let sent: i32 = 0
2041
+ if (r.kind === HTTP_SERVER_H2) {
2042
+ sent = this.h2Conn(r.slot).respond(toI32(r.stream), status, this.outNames, this.outValues, endNow)
2043
+ if (sent === H2_INVALID) {
2044
+ panic(
2045
+ "HttpServer.start: the HTTP/2 carrier refused the head: a name that is not a lowercase token, a reserved field, or a value that is not field text"
2046
+ )
2047
+ }
2048
+ } else {
2049
+ sent = this.h3Of().connection(r.slot).respond(r.stream, status, this.outNames, this.outValues, endNow)
2050
+ if (sent === H3_INVALID) {
2051
+ panic(
2052
+ "HttpServer.start: the HTTP/3 carrier refused the head: a name that is not a lowercase token, a reserved field, or a value that is not field text"
2053
+ )
2054
+ }
2055
+ }
2056
+ if (sent !== 0) {
2057
+ // Closed under it, out of room, or a head past the peer's limit.
2058
+ this.abort(r)
2059
+ return HANDLER_DROPPED
2060
+ }
2061
+ r.ended = endNow
2062
+ this.nudge(r)
2063
+ return HANDLER_SENT
2064
+ }
2065
+
2066
+ /**
2067
+ * Gathers the response's fields into `outNames` and `outValues`: the
2068
+ * program's, then Alt-Svc and content-length where they are owed and the
2069
+ * program gave none. False when that is more than `maxResponseFields`.
2070
+ */
2071
+ private outFields(r: HttpServerRequest, names: u8[][], values: u8[][], bodyLength: i32): boolean {
2072
+ const given: i32 = toI32(names.length)
2073
+ const altSvc: u8[] | null = this.altSvc
2074
+ // Never on HTTP/3, which it names, nor h2c, whose clients reach it
2075
+ // through a proxy that answers on another port.
2076
+ const addAlt: boolean =
2077
+ altSvc !== null &&
2078
+ r.kind !== HTTP_SERVER_H3 &&
2079
+ (r.kind !== HTTP_SERVER_H2 || r.secure) &&
2080
+ !this.hasField(names, this.altSvcName)
2081
+ const addLength: boolean =
2082
+ r.kind !== HTTP_SERVER_H1 &&
2083
+ !r.quiet &&
2084
+ bodyLength >= 0 &&
2085
+ !this.hasField(names, this.contentLengthName)
2086
+ const count: i32 = given + (addAlt ? 1 : 0) + (addLength ? 1 : 0)
2087
+ if (count > this.maxResponseFields) {
2088
+ return false
2089
+ }
2090
+ if (count === given) {
2091
+ this.outNames = names
2092
+ this.outValues = values
2093
+ return true
2094
+ }
2095
+ while (toI32(this.outNamesBy.length) <= count) {
2096
+ const size: i32 = toI32(this.outNamesBy.length)
2097
+ const n: u8[][] = []
2098
+ const v: u8[][] = []
2099
+ for (let k: i32 = 0; k < size; k++) {
2100
+ n.push(this.altSvcName)
2101
+ v.push(this.altSvcName)
2102
+ }
2103
+ this.outNamesBy.push(n)
2104
+ this.outValuesBy.push(v)
2105
+ }
2106
+ const outN: u8[][] = this.outNamesBy[count]
2107
+ const outV: u8[][] = this.outValuesBy[count]
2108
+ for (let k: i32 = 0; k < given; k++) {
2109
+ if (
2110
+ k < toI32(outN.length) &&
2111
+ k < toI32(outV.length) &&
2112
+ k < toI32(names.length) &&
2113
+ k < toI32(values.length)
2114
+ ) {
2115
+ outN[k] = names[k]
2116
+ outV[k] = values[k]
2117
+ }
2118
+ }
2119
+ let at: i32 = given
2120
+ if (altSvc !== null && addAlt) {
2121
+ outN[at] = this.altSvcName
2122
+ outV[at] = altSvc
2123
+ at += 1
2124
+ }
2125
+ if (addLength) {
2126
+ outN[at] = this.contentLengthName
2127
+ outV[at] = this.digits(bodyLength)
2128
+ }
2129
+ this.outNames = outN
2130
+ this.outValues = outV
2131
+ return true
2132
+ }
2133
+
2134
+ /** Whether `names` holds `name`, in any case. */
2135
+ private hasField(names: u8[][], name: u8[]): boolean {
2136
+ for (let k: i32 = 0; k < toI32(names.length); k++) {
2137
+ const have: u8[] = names[k]
2138
+ if (toI32(have.length) === toI32(name.length)) {
2139
+ let same: boolean = true
2140
+ for (let i: i32 = 0; i < toI32(name.length) && i < toI32(have.length) && same; i++) {
2141
+ let c: i32 = toI32(have[i])
2142
+ if (c >= 65 && c <= 90) {
2143
+ c += 32
2144
+ }
2145
+ same = c === toI32(name[i])
2146
+ }
2147
+ if (same) {
2148
+ return true
2149
+ }
2150
+ }
2151
+ }
2152
+ return false
2153
+ }
2154
+
2155
+ /** `n` in decimal, in the shared buffer for its digit count: valid until the next call. */
2156
+ private digits(n: i32): u8[] {
2157
+ let count: i32 = 1
2158
+ let rest: i32 = n
2159
+ while (rest >= HTTP_SERVER_TEN) {
2160
+ rest = (rest - (rest % HTTP_SERVER_TEN)) / HTTP_SERVER_TEN
2161
+ count += 1
2162
+ }
2163
+ const out: u8[] = this.digitBufs[count]
2164
+ rest = n
2165
+ for (let k: i32 = count - 1; k >= 0 && k < toI32(out.length); k--) {
2166
+ const digit: i32 = rest % HTTP_SERVER_TEN
2167
+ out[k] = toU8(HTTP_SERVER_ZERO_DIGIT + digit)
2168
+ rest = (rest - digit) / HTTP_SERVER_TEN
2169
+ }
2170
+ return out
2171
+ }
2172
+
2173
+ /**
2174
+ * Gives up on `r`'s response: on HTTP/1.1 its connection is closed, on
2175
+ * HTTP/2 and HTTP/3 its stream is reset. The program still `end`s it.
2176
+ */
2177
+ private abort(r: HttpServerRequest): void {
2178
+ r.hung = true
2179
+ if (r.kind === HTTP_SERVER_H1) {
2180
+ const h1: Http1Server = this.h1Of()
2181
+ if (this.live(r)) {
2182
+ this.h1Close(h1, r.slot)
2183
+ }
2184
+ return
2185
+ }
2186
+ if (r.kind === HTTP_SERVER_H2) {
2187
+ if (this.h2Holds(r.slot) && this.h2Gen[r.slot] === r.gen) {
2188
+ if (this.h2Conn(r.slot).reset(toI32(r.stream), H2_INTERNAL_ERROR) === H2_AGAIN) {
2189
+ // No room even for the reset: the connection is past saving.
2190
+ this.h2Close(r.slot)
2191
+ return
2192
+ }
2193
+ this.h2Settle(r.slot)
2194
+ }
2195
+ return
2196
+ }
2197
+ const h3: Http3Server = this.h3Of()
2198
+ if (h3.holds(r.slot) && h3.connection(r.slot).generation === r.gen) {
2199
+ h3.connection(r.slot).reset(r.stream, H3_INTERNAL_ERROR)
2200
+ h3.touch(r.slot)
2201
+ }
2202
+ }
2203
+
2204
+ /**
2205
+ * Writes `buf[off .. off + len)` of `r`'s body. What the carrier has no room
2206
+ * for is copied and sent as room comes, so `buf` is the caller's again on
2207
+ * return. Body bytes of a HEAD, 204 or 304 response are dropped. Panics
2208
+ * on another server's request, when the response is not started, on a window outside `buf`, or on more
2209
+ * bytes than the declared length leaves.
2210
+ * @param r a request whose response `start` began
2211
+ * @param buf the bytes to send from; the caller's again on return
2212
+ * @param off where in `buf` the body bytes start
2213
+ * @param len how many bytes to send
2214
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first
2215
+ */
2216
+ write(r: HttpServerRequest, buf: u8[], off: i32, len: i32): i32 {
2217
+ this.own(r, "write")
2218
+ if (r.state !== HTTP_SERVER_STREAMING) {
2219
+ panic(`HttpServer.write: the response is not started (state ${r.state})`)
2220
+ }
2221
+ if (off < 0 || len < 0 || off > toI32(buf.length) - len) {
2222
+ panic(`HttpServer.write: the window ${off} + ${len} is outside its ${buf.length} bytes`)
2223
+ }
2224
+ if (r.left >= 0 && !r.quiet && len > r.left) {
2225
+ panic(
2226
+ `HttpServer.write: ${len} byte(s) is more than the ${r.left} the length the response declared leaves`
2227
+ )
2228
+ }
2229
+ if (!this.live(r)) {
2230
+ return HANDLER_DROPPED
2231
+ }
2232
+ if (r.quiet || len === 0) {
2233
+ return HANDLER_SENT
2234
+ }
2235
+ if (toI64(r.pendingEnd - r.pendingStart) + toI64(len) > toI64(HTTP_SERVER_MAX_BODY)) {
2236
+ // A remainder past 2^30, the longest array the runtime grows to:
2237
+ // nothing of it is written, and the response is cut.
2238
+ this.abort(r)
2239
+ return HANDLER_DROPPED
2240
+ }
2241
+ if (r.left >= 0) {
2242
+ r.left -= len
2243
+ }
2244
+ let taken: i32 = 0
2245
+ if (r.pendingEnd === r.pendingStart) {
2246
+ taken = this.carry(r, buf, off, len, false)
2247
+ if (taken < 0) {
2248
+ this.abort(r)
2249
+ return HANDLER_DROPPED
2250
+ }
2251
+ }
2252
+ if (taken < len) {
2253
+ this.keep(r, buf, off + taken, len - taken)
2254
+ }
2255
+ this.nudge(r)
2256
+ return HANDLER_SENT
2257
+ }
2258
+
2259
+ /**
2260
+ * Hands `buf[off .. off + len)` to `r`'s carrier, with `last` ending the
2261
+ * stream on HTTP/2 and HTTP/3: the bytes it took, 0 for none yet, or -1
2262
+ * when the connection or stream is gone.
2263
+ */
2264
+ private carry(r: HttpServerRequest, buf: u8[], off: i32, len: i32, last: boolean): i32 {
2265
+ if (r.kind === HTTP_SERVER_H1) {
2266
+ const taken: i32 = this.h1Of().connection(r.slot).write(buf, off, len)
2267
+ if (taken === H1_AGAIN) {
2268
+ return 0
2269
+ }
2270
+ if (taken < 0) {
2271
+ panic(
2272
+ `HttpServer.write: the carrier refused the body (${taken}): more than the length the response declared`
2273
+ )
2274
+ }
2275
+ return taken
2276
+ }
2277
+ let taken: i32 = 0
2278
+ if (r.kind === HTTP_SERVER_H2) {
2279
+ taken = this.h2Conn(r.slot).writeData(toI32(r.stream), buf, off, len, last)
2280
+ if (taken === H2_AGAIN) {
2281
+ return 0
2282
+ }
2283
+ } else {
2284
+ taken = this.h3Of().connection(r.slot).writeData(r.stream, buf, off, len, last)
2285
+ if (taken === H3_AGAIN) {
2286
+ return 0
2287
+ }
2288
+ }
2289
+ return taken < 0 ? -1 : taken
2290
+ }
2291
+
2292
+ /** After the program wrote to `r`: what the carrier holds is sent now on HTTP/1.1 and HTTP/2, and by the turn's flush on HTTP/3. */
2293
+ private nudge(r: HttpServerRequest): void {
2294
+ if (r.kind === HTTP_SERVER_H1) {
2295
+ this.drive(this.h1Of(), r.slot)
2296
+ } else if (r.kind === HTTP_SERVER_H2) {
2297
+ if (this.h2Holds(r.slot)) {
2298
+ this.h2Settle(r.slot)
2299
+ }
2300
+ } else {
2301
+ const h3: Http3Server = this.h3Of()
2302
+ if (h3.holds(r.slot)) {
2303
+ h3.touch(r.slot)
2304
+ }
2305
+ }
2306
+ }
2307
+
2308
+ /**
2309
+ * Ends `r`'s response. `r` is the server's again: it goes back once the
2310
+ * carrier has taken every byte. Panics on another server's request, when the
2311
+ * response is not started, or its body is short of the declared length.
2312
+ * @param r a request whose response `start` began; the server's again after this call
2313
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first
2314
+ */
2315
+ end(r: HttpServerRequest): i32 {
2316
+ this.own(r, "end")
2317
+ if (r.state !== HTTP_SERVER_STREAMING) {
2318
+ panic(`HttpServer.end: the response is not started (state ${r.state})`)
2319
+ }
2320
+ if (!this.live(r)) {
2321
+ this.release(r)
2322
+ return HANDLER_DROPPED
2323
+ }
2324
+ if (r.left > 0 && !r.quiet) {
2325
+ panic(`HttpServer.end: the body is ${r.left} byte(s) short of the length the response declared`)
2326
+ }
2327
+ if (r.kind === HTTP_SERVER_H1) {
2328
+ this.finishH1(r, this.h1Of().connection(r.slot))
2329
+ this.drive(this.h1Of(), r.slot)
2330
+ return HANDLER_SENT
2331
+ }
2332
+ r.state = HTTP_SERVER_FLUSHING
2333
+ this.push(r)
2334
+ this.nudge(r)
2335
+ return HANDLER_SENT
2336
+ }
2337
+
2338
+ /**
2339
+ * Hands an HTTP/2 or HTTP/3 stream's pending bytes to the carrier and, once
2340
+ * a flushing response has none left, ends the stream and hands `r` back.
2341
+ */
2342
+ private push(r: HttpServerRequest): void {
2343
+ if (r.state !== HTTP_SERVER_STREAMING && r.state !== HTTP_SERVER_FLUSHING) {
2344
+ return
2345
+ }
2346
+ if (!this.live(r)) {
2347
+ this.drop(r)
2348
+ return
2349
+ }
2350
+ const left: i32 = r.pendingEnd - r.pendingStart
2351
+ if (left > 0) {
2352
+ const last: boolean = r.state === HTTP_SERVER_FLUSHING
2353
+ const taken: i32 = this.carry(r, r.pending, r.pendingStart, left, last)
2354
+ if (taken < 0) {
2355
+ this.drop(r)
2356
+ return
2357
+ }
2358
+ this.taken(r, taken)
2359
+ if (last && taken === left) {
2360
+ r.ended = true
2361
+ }
2362
+ }
2363
+ if (r.state !== HTTP_SERVER_FLUSHING || r.pendingEnd > r.pendingStart) {
2364
+ return
2365
+ }
2366
+ if (!r.ended) {
2367
+ const done: i32 = this.carryEnd(r)
2368
+ if (done === 0) {
2369
+ return // no room for the end yet: the next push sends it
2370
+ }
2371
+ if (done < 0) {
2372
+ r.hung = true
2373
+ }
2374
+ r.ended = true
2375
+ }
2376
+ this.release(r)
2377
+ }
2378
+
2379
+ /**
2380
+ * Ends `r`'s HTTP/2 or HTTP/3 stream with an empty DATA frame: 1 when it is
2381
+ * sent, 0 when the carrier has no room yet, -1 when the stream is gone.
2382
+ * `carry` cannot say this, since the frame is taken as 0 bytes either way.
2383
+ */
2384
+ private carryEnd(r: HttpServerRequest): i32 {
2385
+ let done: i32 = 0
2386
+ if (r.kind === HTTP_SERVER_H2) {
2387
+ done = this.h2Conn(r.slot).writeData(
2388
+ toI32(r.stream),
2389
+ r.pending,
2390
+ HTTP_SERVER_ZERO,
2391
+ HTTP_SERVER_ZERO,
2392
+ true
2393
+ )
2394
+ if (done === H2_AGAIN) {
2395
+ return 0
2396
+ }
2397
+ } else {
2398
+ done = this.h3Of()
2399
+ .connection(r.slot)
2400
+ .writeData(r.stream, r.pending, HTTP_SERVER_ZERO, HTTP_SERVER_ZERO, true)
2401
+ if (done === H3_AGAIN) {
2402
+ return 0
2403
+ }
2404
+ }
2405
+ return done < 0 ? -1 : 1
2406
+ }
2407
+
2408
+ /**
2409
+ * Answers `r` with `status`, a `Content-Type` of `contentType` and the body `body[off .. off + len)`, in one call.
2410
+ * @param r a request taken and not yet answered; the server's again after this call
2411
+ * @param status the response status, from 200 to 599
2412
+ * @param contentType the `Content-Type` value, as bytes
2413
+ * @param body the buffer holding the body; the caller's again on return
2414
+ * @param off where in `body` the body bytes start
2415
+ * @param len how many body bytes to send
2416
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first, or the head could not be sent
2417
+ */
2418
+ send(r: HttpServerRequest, status: i32, contentType: u8[], body: u8[], off: i32, len: i32): i32 {
2419
+ this.typeValue[0] = contentType
2420
+ return this.sendFields(r, status, this.typeName, this.typeValue, body, off, len)
2421
+ }
2422
+
2423
+ /**
2424
+ * Answers `r` with `status`, the fields `names[k]`: `values[k]` and the body `body[off .. off + len)`, in one call.
2425
+ * @param r a request taken and not yet answered; the server's again after this call
2426
+ * @param status the response status, from 200 to 599
2427
+ * @param names the field names, as bytes, beside `values`
2428
+ * @param values each field's value, `values[k]` for `names[k]`
2429
+ * @param body the buffer holding the body; the caller's again on return
2430
+ * @param off where in `body` the body bytes start
2431
+ * @param len how many body bytes to send
2432
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first, or the head could not be sent
2433
+ */
2434
+ sendFields(
2435
+ r: HttpServerRequest,
2436
+ status: i32,
2437
+ names: u8[][],
2438
+ values: u8[][],
2439
+ body: u8[],
2440
+ off: i32,
2441
+ len: i32
2442
+ ): i32 {
2443
+ const started: i32 = this.start(r, status, names, values, len)
2444
+ if (started === HANDLER_DROPPED) {
2445
+ this.release(r)
2446
+ return HANDLER_DROPPED
2447
+ }
2448
+ if (len > 0 && status !== 204 && status !== 304) {
2449
+ this.write(r, body, off, len)
2450
+ }
2451
+ return this.end(r)
2452
+ }
2453
+
2454
+ /**
2455
+ * Answers `r` with `status` and no body.
2456
+ * @param r a request taken and not yet answered; the server's again after this call
2457
+ * @param status the response status, from 200 to 599
2458
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first, or the head could not be sent
2459
+ */
2460
+ empty(r: HttpServerRequest, status: i32): i32 {
2461
+ return this.sendFields(
2462
+ r,
2463
+ status,
2464
+ this.noFields,
2465
+ this.noFields,
2466
+ this.scratch,
2467
+ HTTP_SERVER_ZERO,
2468
+ HTTP_SERVER_ZERO
2469
+ )
2470
+ }
2471
+
2472
+ /**
2473
+ * The JSON writer, reset onto the server's scratch buffer: write one value
2474
+ * with it, then `sendJson`. One JSON body at a time, since every request
2475
+ * shares the buffer.
2476
+ * @returns the server's own writer, empty, valid until the next `json`, `sendJson` or `problem`
2477
+ */
2478
+ json(): JsonWriter {
2479
+ this.writer.reset(this.scratch, HTTP_SERVER_ZERO)
2480
+ this.jsonBegun = true
2481
+ return this.writer
2482
+ }
2483
+
2484
+ /**
2485
+ * Answers `r` with `status` and the value `json`'s writer holds, as
2486
+ * `application/json`. A value the writer refused or did not finish is
2487
+ * answered as a 500 problem instead. Panics when no value was begun with `json`.
2488
+ * @param r a request taken and not yet answered; the server's again after this call
2489
+ * @param status the response status for a value that fit, from 200 to 599
2490
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first, or the head could not be sent
2491
+ */
2492
+ sendJson(r: HttpServerRequest, status: i32): i32 {
2493
+ if (!this.jsonBegun) {
2494
+ panic("HttpServer.sendJson: no value was begun with json()")
2495
+ }
2496
+ this.jsonBegun = false
2497
+ if (!this.writer.complete()) {
2498
+ return this.problem(r, toI32(500), "Internal Server Error", "the response did not fit its buffer")
2499
+ }
2500
+ return this.send(r, status, this.jsonType, this.scratch, HTTP_SERVER_ZERO, this.writer.end)
2501
+ }
2502
+
2503
+ /**
2504
+ * Answers `r` with an RFC 9457 problem: `application/problem+json` with
2505
+ * `type` `about:blank`, `title`, `status` and, when not empty, `detail`.
2506
+ * Nothing of the request is echoed.
2507
+ * @param r a request taken and not yet answered; the server's again after this call
2508
+ * @param status the response status, from 200 to 599, also written into the object
2509
+ * @param title the status's reason phrase, or empty to leave it out
2510
+ * @param detail a sentence for a person about this occurrence, or empty to leave it out
2511
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first, or the head could not be sent
2512
+ */
2513
+ problem(r: HttpServerRequest, status: i32, title: string, detail: string): i32 {
2514
+ const length: i32 = this.writeProblem(status, title, detail)
2515
+ return this.send(r, status, this.problemType, this.scratch, HTTP_SERVER_ZERO, length)
2516
+ }
2517
+
2518
+ /** Writes a problem object into the scratch buffer and answers its length, dropping the detail and then the title until it fits. */
2519
+ private writeProblem(status: i32, title: string, detail: string): i32 {
2520
+ let length: i32 = this.writeProblemObject(status, title, detail)
2521
+ if (length < 0) {
2522
+ length = this.writeProblemObject(status, title, "")
2523
+ }
2524
+ if (length < 0) {
2525
+ length = this.writeProblemObject(status, "", "")
2526
+ }
2527
+ this.jsonBegun = false
2528
+ return length
2529
+ }
2530
+
2531
+ /** `writeProblem`'s one try: the object's length, or -1 when it did not fit. */
2532
+ private writeProblemObject(status: i32, title: string, detail: string): i32 {
2533
+ const w: JsonWriter = this.json()
2534
+ w.beginObject()
2535
+ w.key("type")
2536
+ w.string("about:blank")
2537
+ if (toI32(title.length) > 0) {
2538
+ w.key("title")
2539
+ w.string(title)
2540
+ }
2541
+ w.key("status")
2542
+ w.i32(status)
2543
+ if (toI32(detail.length) > 0) {
2544
+ w.key("detail")
2545
+ w.string(detail)
2546
+ }
2547
+ w.endObject()
2548
+ return w.complete() ? w.end : -1
2549
+ }
2550
+
2551
+ /**
2552
+ * Answers a request the router refused, by its `route`: 405 with an `Allow`
2553
+ * field naming the methods the path has, and 404 for anything else.
2554
+ * @param r a request whose `route` is negative, taken and not yet answered; the server's again after this call
2555
+ * @returns `HANDLER_SENT`, or `HANDLER_DROPPED` when the connection or stream closed first, or the head could not be sent
2556
+ */
2557
+ refuse(r: HttpServerRequest): i32 {
2558
+ if (r.route === ROUTER_METHOD_NOT_ALLOWED) {
2559
+ const length: i32 = this.writeProblem(toI32(405), "Method Not Allowed", "")
2560
+ this.allowValues[1] = this.allowFor(r)
2561
+ return this.sendFields(
2562
+ r,
2563
+ toI32(405),
2564
+ this.allowNames,
2565
+ this.allowValues,
2566
+ this.scratch,
2567
+ HTTP_SERVER_ZERO,
2568
+ length
2569
+ )
2570
+ }
2571
+ return this.problem(r, toI32(404), "Not Found", "")
2572
+ }
2573
+
2574
+ /** The `Allow` value for `r`'s path: each method a route of it takes, and HEAD wherever GET is. Made once for each set of methods. */
2575
+ private allowFor(r: HttpServerRequest): u8[] {
2576
+ const router: Router = this.router
2577
+ const methods: i32 = toI32(router.methodStart.length)
2578
+ let mask: i64 = 0
2579
+ for (let m: i32 = 0; m < methods; m++) {
2580
+ const route: i32 = router.match(
2581
+ router.methodBytes,
2582
+ router.methodStart[m],
2583
+ router.methodEnd[m],
2584
+ r.head,
2585
+ r.targetStart,
2586
+ r.targetEnd,
2587
+ this.probe
2588
+ )
2589
+ if (route >= 0) {
2590
+ mask = mask | (toI64(1) << toI64(m))
2591
+ }
2592
+ }
2593
+ for (let k: i32 = 0; k < toI32(this.allowMasks.length); k++) {
2594
+ if (this.allowMasks[k] === mask) {
2595
+ return this.allowBytes[k]
2596
+ }
2597
+ }
2598
+ let get: boolean = false
2599
+ let head: boolean = false
2600
+ const value: u8[] = []
2601
+ for (let m: i32 = 0; m < methods; m++) {
2602
+ if ((mask & (toI64(1) << toI64(m))) !== toI64(0)) {
2603
+ const start: i32 = router.methodStart[m]
2604
+ const end: i32 = router.methodEnd[m]
2605
+ get = get || httpServerSpanIs(router.methodBytes, start, end, "GET")
2606
+ head = head || httpServerSpanIs(router.methodBytes, start, end, "HEAD")
2607
+ httpServerAllowAppend(value, router.methodBytes, start, end)
2608
+ }
2609
+ }
2610
+ if (get && !head) {
2611
+ const name: u8[] = httpFieldBytes("HEAD")
2612
+ httpServerAllowAppend(value, name, HTTP_SERVER_ZERO, toI32(name.length))
2613
+ }
2614
+ this.allowMasks.push(mask)
2615
+ this.allowBytes.push(value)
2616
+ return value
2617
+ }
2618
+
2619
+ /** The HTTP/1.1 carrier, for a request read on it. */
2620
+ private h1Of(): Http1Server {
2621
+ const h1: Http1Server | null = this.h1
2622
+ if (h1 === null) {
2623
+ panic("HttpServer: no HTTP/1.1 listener")
2624
+ }
2625
+ return h1
2626
+ }
2627
+
2628
+ /** The HTTP/2 over TLS carrier, for a slot on it. */
2629
+ private h2Of(): Http2TlsServer {
2630
+ const h2: Http2TlsServer | null = this.h2
2631
+ if (h2 === null) {
2632
+ panic("HttpServer: no HTTP/2 over TLS listener")
2633
+ }
2634
+ return h2
2635
+ }
2636
+
2637
+ /** The h2c carrier, for a slot on it. */
2638
+ private h2cOf(): Http2CleartextServer {
2639
+ const h2c: Http2CleartextServer | null = this.h2c
2640
+ if (h2c === null) {
2641
+ panic("HttpServer: no h2c listener")
2642
+ }
2643
+ return h2c
2644
+ }
2645
+
2646
+ /** The HTTP/3 carrier, for a request read on it. */
2647
+ private h3Of(): Http3Server {
2648
+ const h3: Http3Server | null = this.h3
2649
+ if (h3 === null) {
2650
+ panic("HttpServer: no HTTP/3 listener")
2651
+ }
2652
+ return h3
2653
+ }
2654
+
2655
+ // ---- HTTP/2 and HTTP/3 heads ----------------------------------------------------
2656
+
2657
+ /**
2658
+ * The status a stream's head is answered with at once, or 0 to serve it:
2659
+ * 501 for CONNECT, 204 for `OPTIONS *`, 431 for a head past `maxFields` or
2660
+ * `maxHead`, and 413 for a declared length past `maxBody`.
2661
+ */
2662
+ private screen(f: HttpFields): i32 {
2663
+ if (f.isConnect()) {
2664
+ return 501
2665
+ }
2666
+ const pathLength: i32 = toI32(f.path.length)
2667
+ if (pathLength === 1 && toI32(f.path[0]) === 42 && httpFieldIs(f.method, "OPTIONS")) {
2668
+ return 204
2669
+ }
2670
+ // Counts what `fromFields` lays out: `:authority`, when present, as a
2671
+ // `host` field in place of every `host` field the head carries.
2672
+ const authority: boolean = toI32(f.authority.length) > 0
2673
+ let fields: i32 = authority ? 1 : 0
2674
+ let bytes: i32 = toI32(f.method.length) + pathLength + 4 + toI32(f.authority.length)
2675
+ for (let k: i32 = 0; k < toI32(f.names.length); k++) {
2676
+ if (!authority || !httpFieldIs(f.names[k], "host")) {
2677
+ fields += 1
2678
+ bytes += toI32(f.names[k].length) + toI32(f.values[k].length)
2679
+ }
2680
+ }
2681
+ if (fields > this.maxFields || bytes > this.maxHead) {
2682
+ return 431
2683
+ }
2684
+ if (f.contentLength > toI64(this.maxBody)) {
2685
+ return HTTP_SERVER_TOO_LARGE
2686
+ }
2687
+ return 0
2688
+ }
2689
+
2690
+ /**
2691
+ * Lays a screened head out in `r` as HTTP/1.1's reads: the method, the
2692
+ * path as the target, and the fields, with `:authority` given as `host`
2693
+ * in place of any `host` field.
2694
+ */
2695
+ private fromFields(r: HttpServerRequest, f: HttpFields): void {
2696
+ this.headAt = 0
2697
+ r.methodStart = 0
2698
+ this.put(r, f.method)
2699
+ r.methodEnd = this.headAt
2700
+ r.targetStart = this.headAt
2701
+ this.put(r, f.path)
2702
+ r.targetEnd = this.headAt
2703
+ let n: i32 = 0
2704
+ const authority: boolean = toI32(f.authority.length) > 0
2705
+ if (authority) {
2706
+ this.putField(r, n, this.hostName, f.authority)
2707
+ n += 1
2708
+ }
2709
+ for (let k: i32 = 0; k < toI32(f.names.length); k++) {
2710
+ const name: u8[] = f.names[k]
2711
+ if (!authority || !httpFieldIs(name, "host")) {
2712
+ this.putField(r, n, name, f.values[k])
2713
+ n += 1
2714
+ }
2715
+ }
2716
+ r.headerCount = n
2717
+ }
2718
+
2719
+ /** Copies `bytes` into `r`'s head at `headAt`. */
2720
+ private put(r: HttpServerRequest, bytes: u8[]): void {
2721
+ const n: i32 = toI32(bytes.length)
2722
+ copyBytes(r.head, this.headAt, bytes, HTTP_SERVER_ZERO, n)
2723
+ this.headAt += n
2724
+ }
2725
+
2726
+ /** Copies field `n`, `name`: `value`, into `r`'s head and spans. */
2727
+ private putField(r: HttpServerRequest, n: i32, name: u8[], value: u8[]): void {
2728
+ r.spans[4 * n] = this.headAt
2729
+ this.put(r, name)
2730
+ r.spans[4 * n + 1] = this.headAt
2731
+ r.spans[4 * n + 2] = this.headAt
2732
+ this.put(r, value)
2733
+ r.spans[4 * n + 3] = this.headAt
2734
+ }
2735
+
2736
+ // ---- HTTP/2 ---------------------------------------------------------------------
2737
+
2738
+ /** Takes every waiting HTTP/2 over TLS connection, each with fresh randomness. */
2739
+ private acceptHttp2(): void {
2740
+ const h2: Http2TlsServer | null = this.h2
2741
+ if (h2 === null || this.draining) {
2742
+ return
2743
+ }
2744
+ while (true) {
2745
+ crypto.getRandomValues(this.rnd)
2746
+ crypto.getRandomValues(this.keyBuf)
2747
+ const slot: i32 = h2.accept(this.rnd, this.keyBuf)
2748
+ if (slot >= 0) {
2749
+ this.h2Opened(this.h2TlsBase + slot, h2.fd(slot))
2750
+ } else if (slot === HTTP_SERVER_ACCEPT_NONE) {
2751
+ return
2752
+ } else if (slot !== TLS_TCP_POOL_FULL && slot !== HTTP_SERVER_ACCEPT_ABORTED) {
2753
+ // Out of descriptors or memory: rest the listener, as `acceptHttp1` does.
2754
+ this.rest(this.h2Fd, HTTP_SERVER_H2_LISTENER)
2755
+ return
2756
+ }
2757
+ }
2758
+ }
2759
+
2760
+ /** Takes every waiting h2c connection. */
2761
+ private acceptH2c(): void {
2762
+ const h2c: Http2CleartextServer | null = this.h2c
2763
+ if (h2c === null || this.draining) {
2764
+ return
2765
+ }
2766
+ let slot: i32 = h2c.accept()
2767
+ while (slot >= 0 || slot === H2C_POOL_FULL || slot === HTTP_SERVER_ACCEPT_ABORTED) {
2768
+ if (slot >= 0) {
2769
+ this.h2Opened(this.h2cBase + slot, h2c.fd(slot))
2770
+ }
2771
+ slot = h2c.accept()
2772
+ }
2773
+ if (slot !== HTTP_SERVER_ACCEPT_NONE) {
2774
+ this.rest(this.h2cFd, HTTP_SERVER_H2C_LISTENER)
2775
+ }
2776
+ }
2777
+
2778
+ /**
2779
+ * Out of descriptors or memory: the connection stays in the backlog and
2780
+ * the listener stays readable, so it leaves the loop for a while rather
2781
+ * than spin.
2782
+ */
2783
+ private rest(fd: i32, token: i32): void {
2784
+ pollRemove(this.loop, fd)
2785
+ this.restUntil[HTTP_SERVER_H1_LISTENER - token] = monotonicNanos() + HTTP_SERVER_ACCEPT_REST
2786
+ }
2787
+
2788
+ /** HTTP/2 slot `v`, just accepted on socket `fd`: an empty stream table, idle, and in the loop. */
2789
+ private h2Opened(v: i32, fd: i32): void {
2790
+ this.h2Open[v] = true
2791
+ this.h2Count[v] = 0
2792
+ this.h2IdleSince[v] = this.turnAt
2793
+ const base: i32 = v * this.perConnection2
2794
+ for (let e: i32 = base; e < base + this.perConnection2; e++) {
2795
+ this.h2Reqs[e] = -1
2796
+ }
2797
+ pollAdd(this.loop, fd, H1_WANT_READ, HTTP_SERVER_H2_BASE + v)
2798
+ }
2799
+
2800
+ /** Whether HTTP/2 slot `v`'s carrier holds a connection there. */
2801
+ private h2Holds(v: i32): boolean {
2802
+ if (this.h2Clear[v]) {
2803
+ const h2c: Http2CleartextServer | null = this.h2c
2804
+ return h2c !== null && h2c.holds(v - this.h2cBase)
2805
+ }
2806
+ const h2: Http2TlsServer | null = this.h2
2807
+ return h2 !== null && h2.holds(v - this.h2TlsBase)
2808
+ }
2809
+
2810
+ /** HTTP/2 slot `v`'s connection. */
2811
+ private h2Conn(v: i32): Http2Connection {
2812
+ if (this.h2Clear[v]) {
2813
+ return this.h2cOf().connection(v - this.h2cBase)
2814
+ }
2815
+ return this.h2Of().connection(v - this.h2TlsBase)
2816
+ }
2817
+
2818
+ /** HTTP/2 slot `v`'s next event, as its carrier's `next` answers. */
2819
+ private h2Next(v: i32): i32 {
2820
+ if (this.h2Clear[v]) {
2821
+ return this.h2cOf().next(v - this.h2cBase)
2822
+ }
2823
+ return this.h2Of().next(v - this.h2TlsBase)
2824
+ }
2825
+
2826
+ /** Sends what HTTP/2 slot `v` holds: its interest, with `TLS_RECORD_DONE` (`H2C_DONE`) once it is over. */
2827
+ private h2Flush(v: i32): i32 {
2828
+ if (this.h2Clear[v]) {
2829
+ return this.h2cOf().flush(v - this.h2cBase)
2830
+ }
2831
+ return this.h2Of().flush(v - this.h2TlsBase)
2832
+ }
2833
+
2834
+ /** HTTP/2 slot `v`'s socket. */
2835
+ private h2FdOf(v: i32): i32 {
2836
+ if (this.h2Clear[v]) {
2837
+ return this.h2cOf().fd(v - this.h2cBase)
2838
+ }
2839
+ return this.h2Of().fd(v - this.h2TlsBase)
2840
+ }
2841
+
2842
+ /**
2843
+ * A ready HTTP/2 socket: read or written, a TLS handshake signed, its
2844
+ * events served, then settled. A TLS slot is never ready under `wait`,
2845
+ * which panics with a TLS listener, so `key` is null only for h2c.
2846
+ */
2847
+ private h2Serve(v: i32, events: i32, key: Secret<u8[]> | null): void {
2848
+ if (v < 0 || v >= toI32(this.h2Open.length) || !this.h2Open[v]) {
2849
+ return
2850
+ }
2851
+ if (!this.h2Holds(v)) {
2852
+ this.h2Forget(v)
2853
+ return
2854
+ }
2855
+ const read: boolean = (events & HTTP_SERVER_READ_BITS) !== 0
2856
+ if (this.h2Clear[v]) {
2857
+ const h2c: Http2CleartextServer = this.h2cOf()
2858
+ const slot: i32 = v - this.h2cBase
2859
+ if (read) {
2860
+ h2c.readable(slot)
2861
+ } else {
2862
+ h2c.writable(slot)
2863
+ }
2864
+ } else if (key !== null) {
2865
+ const h2: Http2TlsServer = this.h2Of()
2866
+ const slot: i32 = v - this.h2TlsBase
2867
+ let wants: i32 = read ? h2.readable(slot) : h2.writable(slot)
2868
+ for (let turn: i32 = 0; turn < 4 && h2.holds(slot) && (wants & TLS_RECORD_SIGN) !== 0; turn++) {
2869
+ wants = h2.signP256(slot, key)
2870
+ }
2871
+ }
2872
+ if (this.h2Holds(v)) {
2873
+ const conn: Http2Connection = this.h2Conn(v)
2874
+ let event: i32 = this.h2Next(v)
2875
+ while (event !== H2_NEED_MORE && event !== H2_ERROR) {
2876
+ this.h2Event(v, conn, event)
2877
+ event = this.h2Next(v)
2878
+ }
2879
+ }
2880
+ this.h2Settle(v)
2881
+ }
2882
+
2883
+ /** One HTTP/2 event of `slot`'s connection. */
2884
+ private h2Event(slot: i32, conn: Http2Connection, event: i32): void {
2885
+ const id: i32 = conn.stream
2886
+ if (event === H2_REQUEST) {
2887
+ const f: HttpFields = conn.fields
2888
+ const status: i32 = this.screen(f)
2889
+ if (status > 0) {
2890
+ this.h2Direct(slot, conn, id, status, conn.endStream)
2891
+ return
2892
+ }
2893
+ const e: i32 = this.h2Entry(slot)
2894
+ const at: i32 = e >= 0 ? this.obtain() : -1
2895
+ if (at < 0) {
2896
+ conn.reset(id, H2_REFUSED_STREAM)
2897
+ return
2898
+ }
2899
+ const r: HttpServerRequest = this.requests[at]
2900
+ this.fromFields(r, f)
2901
+ r.kind = HTTP_SERVER_H2
2902
+ r.version = 2
2903
+ r.secure = !this.h2Clear[slot]
2904
+ r.stream = toI64(id)
2905
+ r.slot = slot
2906
+ r.gen = this.h2Gen[slot]
2907
+ r.entry = e
2908
+ this.h2Streams[e] = id
2909
+ this.h2Reqs[e] = at
2910
+ this.h2Count[slot] = this.h2Count[slot] + 1
2911
+ this.h2IdleSince[slot] = 0
2912
+ this.admit(r)
2913
+ if (conn.endStream) {
2914
+ this.enqueue(r)
2915
+ }
2916
+ return
2917
+ }
2918
+ const at: i32 = this.h2Find(slot, id)
2919
+ if (at < 0) {
2920
+ return
2921
+ }
2922
+ const r: HttpServerRequest = this.requests[at]
2923
+ if (event === H2_DATA) {
2924
+ if (r.state !== HTTP_SERVER_READING) {
2925
+ return
2926
+ }
2927
+ if (r.bodyLength + conn.dataLength > this.maxBody) {
2928
+ this.release(r)
2929
+ this.h2Direct(slot, conn, id, HTTP_SERVER_TOO_LARGE, conn.endStream)
2930
+ return
2931
+ }
2932
+ this.append(r, conn.data, conn.dataStart, conn.dataLength)
2933
+ if (conn.endStream) {
2934
+ this.enqueue(r)
2935
+ }
2936
+ } else if (event === H2_TRAILERS) {
2937
+ if (r.state === HTTP_SERVER_READING) {
2938
+ this.enqueue(r)
2939
+ }
2940
+ } else if (event === H2_RESET) {
2941
+ // A request still read, or flushed after its answer, is the server's
2942
+ // alone; one queued or the program's goes back when it is answered.
2943
+ this.drop(r)
2944
+ this.unlink(r)
2945
+ }
2946
+ }
2947
+
2948
+ /**
2949
+ * Answers stream `id` with `status` and no body, then resets it with
2950
+ * NO_ERROR when the client is still sending (RFC 9113 §8.1); with
2951
+ * INTERNAL_ERROR when there is no room for the answer. Over TLS it
2952
+ * carries `alt-svc` like every other answer; over h2c it carries none.
2953
+ */
2954
+ private h2Direct(slot: i32, conn: Http2Connection, id: i32, status: i32, ended: boolean): void {
2955
+ const alt: boolean = this.altSvc !== null && !this.h2Clear[slot]
2956
+ const names: u8[][] = alt ? this.altNames : this.noFields
2957
+ const values: u8[][] = alt ? this.altValues : this.noFields
2958
+ if (conn.respond(id, status, names, values, true) !== 0) {
2959
+ conn.reset(id, H2_INTERNAL_ERROR)
2960
+ } else if (!ended) {
2961
+ conn.reset(id, H2_NO_ERROR)
2962
+ }
2963
+ }
2964
+
2965
+ /** A free entry of `slot`'s stream table, or -1 when it is full. */
2966
+ private h2Entry(slot: i32): i32 {
2967
+ const base: i32 = slot * this.perConnection2
2968
+ for (let e: i32 = base; e < base + this.perConnection2; e++) {
2969
+ if (this.h2Reqs[e] === -1) {
2970
+ return e
2971
+ }
2972
+ }
2973
+ return -1
2974
+ }
2975
+
2976
+ /** The request `slot` holds for stream `id`, or -1. */
2977
+ private h2Find(slot: i32, id: i32): i32 {
2978
+ const base: i32 = slot * this.perConnection2
2979
+ for (let e: i32 = base; e < base + this.perConnection2; e++) {
2980
+ if (this.h2Reqs[e] >= 0 && this.h2Streams[e] === id) {
2981
+ return this.h2Reqs[e]
2982
+ }
2983
+ }
2984
+ return -1
2985
+ }
2986
+
2987
+ /**
2988
+ * Sends what `slot` holds, pushing each response's pending bytes while a
2989
+ * pass moves any, then re-arms it, or closes it once it is over.
2990
+ */
2991
+ private h2Settle(slot: i32): void {
2992
+ if (!this.h2Holds(slot)) {
2993
+ if (this.h2Open[slot]) {
2994
+ this.h2Forget(slot)
2995
+ }
2996
+ return
2997
+ }
2998
+ let wants: i32 = this.h2Flush(slot)
2999
+ for (let pass: i32 = 0; pass < 4096 && this.h2Holds(slot) && this.h2PushAll(slot); pass++) {
3000
+ wants = this.h2Flush(slot)
3001
+ }
3002
+ if (!this.h2Holds(slot)) {
3003
+ this.h2Forget(slot)
3004
+ return
3005
+ }
3006
+ if ((wants & TLS_RECORD_DONE) !== 0) {
3007
+ this.h2Close(slot)
3008
+ return
3009
+ }
3010
+ pollModify(
3011
+ this.loop,
3012
+ this.h2FdOf(slot),
3013
+ wants & (H1_WANT_READ | H1_WANT_WRITE),
3014
+ HTTP_SERVER_H2_BASE + slot
3015
+ )
3016
+ }
3017
+
3018
+ /** Pushes every response `slot` is sending: whether any moved a byte or ended. */
3019
+ private h2PushAll(slot: i32): boolean {
3020
+ let moved: boolean = false
3021
+ const base: i32 = slot * this.perConnection2
3022
+ for (let e: i32 = base; e < base + this.perConnection2; e++) {
3023
+ const at: i32 = this.h2Reqs[e]
3024
+ if (at >= 0 && this.moves(this.requests[at])) {
3025
+ moved = true
3026
+ }
3027
+ }
3028
+ return moved
3029
+ }
3030
+
3031
+ /** Pushes `r` if it is sending: whether that moved a byte or handed it back. */
3032
+ private moves(r: HttpServerRequest): boolean {
3033
+ if (r.state !== HTTP_SERVER_STREAMING && r.state !== HTTP_SERVER_FLUSHING) {
3034
+ return false
3035
+ }
3036
+ const before: i32 = r.pendingEnd - r.pendingStart
3037
+ this.push(r)
3038
+ return r.state === HTTP_SERVER_FREE || r.pendingEnd - r.pendingStart < before
3039
+ }
3040
+
3041
+ /** Closes `slot` and forgets it. */
3042
+ private h2Close(slot: i32): void {
3043
+ if (this.h2Clear[slot]) {
3044
+ this.h2cOf().close(slot - this.h2cBase)
3045
+ } else {
3046
+ this.h2Of().close(slot - this.h2TlsBase)
3047
+ }
3048
+ this.h2Forget(slot)
3049
+ }
3050
+
3051
+ /**
3052
+ * The bookkeeping of a slot the carrier has closed: its generation moves
3053
+ * on, so what is owed for it is dropped, and the requests only the server
3054
+ * held go back.
3055
+ */
3056
+ private h2Forget(slot: i32): void {
3057
+ this.h2Open[slot] = false
3058
+ this.h2Gen[slot] = this.h2Gen[slot] + 1
3059
+ this.h2Count[slot] = 0
3060
+ const base: i32 = slot * this.perConnection2
3061
+ for (let e: i32 = base; e < base + this.perConnection2; e++) {
3062
+ const at: i32 = this.h2Reqs[e]
3063
+ this.h2Reqs[e] = -1
3064
+ if (at >= 0) {
3065
+ const r: HttpServerRequest = this.requests[at]
3066
+ r.entry = -1
3067
+ this.drop(r)
3068
+ }
3069
+ }
3070
+ }
3071
+
3072
+ // ---- HTTP/3 ---------------------------------------------------------------------
3073
+
3074
+ /** One turn of the HTTP/3 carrier: datagrams read, timers run, each connection with news served, and the output sent. */
3075
+ private h3Turn(h3: Http3Server, now: i64, key: Secret<u8[]>): void {
3076
+ const ms: i64 = now / HTTP_SERVER_NANOS_PER_MS
3077
+ h3.clock(now / toI64(1000))
3078
+ if (this.h3Readable) {
3079
+ let round: i32 = 0
3080
+ while (
3081
+ round < HTTP_SERVER_H3_ROUNDS &&
3082
+ (this.draining ? this.h3Drained(h3, ms, key) : h3.receive(ms, key)) > 0
3083
+ ) {
3084
+ round += 1
3085
+ }
3086
+ }
3087
+ h3.tick(ms)
3088
+ let slot: i32 = h3.ready()
3089
+ while (slot >= 0) {
3090
+ this.h3Serve(h3, slot)
3091
+ slot = h3.ready()
3092
+ }
3093
+ h3.flush(ms)
3094
+ }
3095
+
3096
+ /**
3097
+ * `receive` for a draining server: the same reads, but only a datagram a
3098
+ * connection already owns goes on, so the drain starts no connection. An
3099
+ * Initial for a new one, and anything else no connection owns, is dropped.
3100
+ */
3101
+ private h3Drained(h3: Http3Server, ms: i64, key: Secret<u8[]>): i32 {
3102
+ if (toI32(this.h3Rx.length) === 0) {
3103
+ this.h3Rx = new Array<u8>(HTTP_SERVER_UDP_SIZE)
3104
+ }
3105
+ const rx: u8[] = this.h3Rx
3106
+ let count: i32 = 0
3107
+ for (let burst: i32 = 0; burst < H3_SERVER_RECEIVE_BURST; burst++) {
3108
+ const n: i32 = udpRecvFrom(
3109
+ this.h3Fd,
3110
+ rx,
3111
+ HTTP_SERVER_ZERO,
3112
+ HTTP_SERVER_UDP_SIZE,
3113
+ this.h3From,
3114
+ this.h3Meta
3115
+ )
3116
+ if (n < 0) {
3117
+ return count
3118
+ }
3119
+ const segment: i32 = this.h3Meta[0] > 0 ? this.h3Meta[0] : n
3120
+ let at: i32 = 0
3121
+ while (at < n) {
3122
+ const length: i32 = n - at < segment ? n - at : segment
3123
+ if (this.h3Owned(h3, rx, at, length)) {
3124
+ h3.datagram(rx, at, length, this.h3From, ms, key)
3125
+ }
3126
+ count += 1
3127
+ at += length
3128
+ }
3129
+ }
3130
+ return count
3131
+ }
3132
+
3133
+ /** Whether a connection of `h3` owns the datagram `buf[at .. at + len)`, by its first packet's Destination Connection ID, read as `Http3Server.datagram` reads it. */
3134
+ private h3Owned(h3: Http3Server, buf: u8[], at: i32, len: i32): boolean {
3135
+ if (len < 1) {
3136
+ return false
3137
+ }
3138
+ let dcidAt: i32 = at + 1
3139
+ let dcidLength: i32 = QUIC_CONN_CID_LENGTH
3140
+ if ((toI32(buf[at]) & 0x80) !== 0) {
3141
+ if (len < 6) {
3142
+ return false
3143
+ }
3144
+ dcidLength = toI32(buf[at + 5])
3145
+ dcidAt = at + 6
3146
+ }
3147
+ if (dcidLength > QUIC_MAX_CID_LENGTH || dcidAt + dcidLength > at + len) {
3148
+ return false
3149
+ }
3150
+ return h3.index.find(buf, dcidAt, dcidLength) >= 0
3151
+ }
3152
+
3153
+ /** Serves `slot`'s HTTP/3 events, then pushes its responses. */
3154
+ private h3Serve(h3: Http3Server, slot: i32): void {
3155
+ const conn: Http3Connection = h3.connection(slot)
3156
+ if (this.h3Gen[slot] !== conn.generation) {
3157
+ this.h3Clear(slot, conn.generation)
3158
+ }
3159
+ let event: i32 = conn.next()
3160
+ while (event !== H3_NEED_MORE && event !== H3_ERROR) {
3161
+ this.h3Event(slot, conn, event)
3162
+ event = conn.next()
3163
+ }
3164
+ if (event === H3_ERROR || !h3.holds(slot)) {
3165
+ this.h3Clear(slot, conn.generation)
3166
+ return
3167
+ }
3168
+ const base: i32 = slot * this.perConnection3
3169
+ for (let e: i32 = base; e < base + this.perConnection3; e++) {
3170
+ const at: i32 = this.h3Reqs[e]
3171
+ if (at >= 0) {
3172
+ this.moves(this.requests[at])
3173
+ }
3174
+ }
3175
+ }
3176
+
3177
+ /** One HTTP/3 event of `slot`'s connection. */
3178
+ private h3Event(slot: i32, conn: Http3Connection, event: i32): void {
3179
+ const id: i64 = conn.stream
3180
+ if (event === H3_REQUEST) {
3181
+ const f: HttpFields = conn.fields
3182
+ const status: i32 = this.screen(f)
3183
+ if (status > 0) {
3184
+ this.h3Direct(conn, id, status)
3185
+ return
3186
+ }
3187
+ const e: i32 = this.h3Entry(slot)
3188
+ const at: i32 = e >= 0 ? this.obtain() : -1
3189
+ if (at < 0) {
3190
+ conn.reset(id, H3_REQUEST_REJECTED)
3191
+ return
3192
+ }
3193
+ const r: HttpServerRequest = this.requests[at]
3194
+ this.fromFields(r, f)
3195
+ r.kind = HTTP_SERVER_H3
3196
+ r.version = 3
3197
+ r.secure = true
3198
+ r.stream = id
3199
+ r.slot = slot
3200
+ r.gen = conn.generation
3201
+ r.entry = e
3202
+ this.h3Streams[e] = id
3203
+ this.h3Reqs[e] = at
3204
+ this.h3Count[slot] = this.h3Count[slot] + 1
3205
+ this.admit(r)
3206
+ return
3207
+ }
3208
+ const at: i32 = this.h3Find(slot, id)
3209
+ if (at < 0) {
3210
+ return
3211
+ }
3212
+ const r: HttpServerRequest = this.requests[at]
3213
+ if (event === H3_DATA) {
3214
+ if (r.state !== HTTP_SERVER_READING) {
3215
+ return
3216
+ }
3217
+ if (r.bodyLength + conn.dataLength > this.maxBody) {
3218
+ this.release(r)
3219
+ this.h3Direct(conn, id, HTTP_SERVER_TOO_LARGE)
3220
+ return
3221
+ }
3222
+ this.append(r, conn.data, conn.dataStart, conn.dataLength)
3223
+ } else if (event === H3_END) {
3224
+ if (r.state === HTTP_SERVER_READING) {
3225
+ this.enqueue(r)
3226
+ }
3227
+ } else if (event === H3_RESET) {
3228
+ // A request still read, or flushed after its answer, is the server's
3229
+ // alone; one queued or the program's goes back when it is answered.
3230
+ this.drop(r)
3231
+ this.unlink(r)
3232
+ }
3233
+ }
3234
+
3235
+ /**
3236
+ * Answers stream `id` with `status` and no body and stops reading the
3237
+ * rest of its request (RFC 9114 §4.1.1); resets it when there is no room
3238
+ * for the answer.
3239
+ */
3240
+ private h3Direct(conn: Http3Connection, id: i64, status: i32): void {
3241
+ if (conn.respond(id, status, this.noFields, this.noFields, true) !== 0) {
3242
+ conn.reset(id, H3_INTERNAL_ERROR)
3243
+ } else {
3244
+ conn.discardRequest(id, H3_NO_ERROR)
3245
+ }
3246
+ }
3247
+
3248
+ /** A free entry of `slot`'s stream table, or -1 when it is full. */
3249
+ private h3Entry(slot: i32): i32 {
3250
+ const base: i32 = slot * this.perConnection3
3251
+ for (let e: i32 = base; e < base + this.perConnection3; e++) {
3252
+ if (this.h3Reqs[e] === -1) {
3253
+ return e
3254
+ }
3255
+ }
3256
+ return -1
3257
+ }
3258
+
3259
+ /** The request `slot` holds for stream `id`, or -1. */
3260
+ private h3Find(slot: i32, id: i64): i32 {
3261
+ const base: i32 = slot * this.perConnection3
3262
+ for (let e: i32 = base; e < base + this.perConnection3; e++) {
3263
+ if (this.h3Reqs[e] >= 0 && this.h3Streams[e] === id) {
3264
+ return this.h3Reqs[e]
3265
+ }
3266
+ }
3267
+ return -1
3268
+ }
3269
+
3270
+ /**
3271
+ * Forgets `slot`'s stream table, its connection gone or restarted as
3272
+ * generation `gen`: the requests only the server held go back.
3273
+ */
3274
+ private h3Clear(slot: i32, gen: i32): void {
3275
+ const base: i32 = slot * this.perConnection3
3276
+ for (let e: i32 = base; e < base + this.perConnection3; e++) {
3277
+ const at: i32 = this.h3Reqs[e]
3278
+ this.h3Reqs[e] = -1
3279
+ if (at >= 0) {
3280
+ const r: HttpServerRequest = this.requests[at]
3281
+ r.entry = -1
3282
+ this.drop(r)
3283
+ }
3284
+ }
3285
+ this.h3Count[slot] = 0
3286
+ this.h3Gen[slot] = gen
3287
+ }
3288
+
3289
+ // ---- Timeouts -------------------------------------------------------------------
3290
+
3291
+ /**
3292
+ * Once a second: a body slower than `bodyTimeout` is cut off (its HTTP/1.1
3293
+ * connection closed, its stream reset), an HTTP/2 connection with no
3294
+ * stream for `idleTimeout` is closed, and stream tables of connections
3295
+ * the carriers dropped are forgotten.
3296
+ */
3297
+ private expireAll(now: i64): void {
3298
+ const h1: Http1Server | null = this.h1
3299
+ if (h1 !== null) {
3300
+ for (let s: i32 = 0; s < toI32(this.h1Current.length); s++) {
3301
+ const at: i32 = this.h1Current[s]
3302
+ if (at >= 0 && this.late(this.requests[at], now) && h1.holds(s)) {
3303
+ this.h1Close(h1, s)
3304
+ }
3305
+ }
3306
+ }
3307
+ const h2c: Http2CleartextServer | null = this.h2c
3308
+ if (h2c !== null) {
3309
+ // Closes each connection past `prefaceTimeout` with no preface; the
3310
+ // loop below forgets it.
3311
+ h2c.expire(now)
3312
+ }
3313
+ for (let v: i32 = 0; v < toI32(this.h2Open.length); v++) {
3314
+ if (this.h2Open[v]) {
3315
+ this.h2Expire(v, now)
3316
+ }
3317
+ }
3318
+ const h3: Http3Server | null = this.h3
3319
+ if (h3 !== null) {
3320
+ for (let s: i32 = 0; s < toI32(this.h3Count.length); s++) {
3321
+ if (this.h3Count[s] > 0) {
3322
+ this.h3Expire(h3, s, now)
3323
+ }
3324
+ }
3325
+ }
3326
+ }
3327
+
3328
+ /** Whether `r` is still reading its body past `bodyTimeout`. */
3329
+ private late(r: HttpServerRequest, now: i64): boolean {
3330
+ return r.state === HTTP_SERVER_READING && now - r.since > this.bodyTimeout
3331
+ }
3332
+
3333
+ /** `expireAll` for HTTP/2 slot `s`. */
3334
+ private h2Expire(s: i32, now: i64): void {
3335
+ if (!this.h2Holds(s)) {
3336
+ this.h2Forget(s)
3337
+ return
3338
+ }
3339
+ if (this.h2Clear[s] && !this.h2cOf().prefaced(s - this.h2cBase)) {
3340
+ // `prefaceTimeout` holds it till then; `idleTimeout` runs from the preface.
3341
+ this.h2IdleSince[s] = now
3342
+ return
3343
+ }
3344
+ const conn: Http2Connection = this.h2Conn(s)
3345
+ const base: i32 = s * this.perConnection2
3346
+ for (let e: i32 = base; e < base + this.perConnection2; e++) {
3347
+ const at: i32 = this.h2Reqs[e]
3348
+ if (at >= 0 && this.late(this.requests[at], now)) {
3349
+ const sent: i32 = conn.reset(this.h2Streams[e], H2_CANCEL)
3350
+ this.release(this.requests[at])
3351
+ if (sent === H2_AGAIN) {
3352
+ // No room to send the reset: end the connection, as `abort` does.
3353
+ this.h2Close(s)
3354
+ return
3355
+ }
3356
+ }
3357
+ }
3358
+ if (this.h2Count[s] === 0 && this.h2IdleSince[s] > 0 && now - this.h2IdleSince[s] > this.idleTimeout) {
3359
+ this.h2Close(s)
3360
+ return
3361
+ }
3362
+ this.h2Settle(s)
3363
+ }
3364
+
3365
+ /** `expireAll` for HTTP/3 slot `s`. */
3366
+ private h3Expire(h3: Http3Server, s: i32, now: i64): void {
3367
+ if (!h3.holds(s) || h3.connection(s).generation !== this.h3Gen[s]) {
3368
+ this.h3Clear(s, h3.holds(s) ? h3.connection(s).generation : this.h3Gen[s])
3369
+ return
3370
+ }
3371
+ const conn: Http3Connection = h3.connection(s)
3372
+ const base: i32 = s * this.perConnection3
3373
+ for (let e: i32 = base; e < base + this.perConnection3; e++) {
3374
+ const at: i32 = this.h3Reqs[e]
3375
+ if (at >= 0 && this.late(this.requests[at], now)) {
3376
+ conn.reset(this.h3Streams[e], H3_REQUEST_CANCELLED)
3377
+ this.release(this.requests[at])
3378
+ h3.touch(s)
3379
+ }
3380
+ }
3381
+ }
3382
+ }