nish 0.44.0 → 0.45.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +1 -1
  2. package/docs/AI.md +18 -16
  3. package/package.json +5 -5
  4. package/runtime/core/numbers.mjs +3 -1
  5. package/runtime/core/strings.mjs +90 -38
  6. package/runtime/core.d.ts +8 -0
  7. package/runtime/core.mjs +16 -0
  8. package/runtime/nish.d.ts +47 -5
  9. package/runtime/nish.mjs +4 -0
  10. package/std/README.md +3 -3
  11. package/std/array.ts +10 -2
  12. package/std/bytes.ts +239 -26
  13. package/std/cli-args.ts +1072 -606
  14. package/std/cli-flags.ts +180 -98
  15. package/std/cli.ts +21 -13
  16. package/std/collections.ts +245 -127
  17. package/std/compress/checksum.ts +32 -37
  18. package/std/compress/deflate.ts +1102 -542
  19. package/std/compress/gzip.ts +290 -145
  20. package/std/compress/zlib.ts +57 -21
  21. package/std/crypto/aes.ts +153 -75
  22. package/std/crypto/base64url.ts +84 -61
  23. package/std/crypto/bcrypt-batch.ts +164 -90
  24. package/std/crypto/bcrypt.ts +185 -107
  25. package/std/crypto/chacha20poly1305.ts +84 -68
  26. package/std/crypto/ct.ts +9 -7
  27. package/std/crypto/ed25519.ts +64 -27
  28. package/std/crypto/hkdf.ts +105 -63
  29. package/std/crypto/hmac.ts +95 -89
  30. package/std/crypto/jwt.ts +248 -126
  31. package/std/crypto/p256.ts +758 -444
  32. package/std/crypto/p384.ts +20 -13
  33. package/std/crypto/pki-roots.ts +95 -38
  34. package/std/crypto/pki.ts +164 -60
  35. package/std/crypto/rsa.ts +266 -223
  36. package/std/crypto/scram.ts +3 -4
  37. package/std/crypto/sha1.ts +107 -65
  38. package/std/crypto/sha256.ts +502 -422
  39. package/std/crypto/sha512.ts +204 -135
  40. package/std/crypto/x509-random.ts +9 -3
  41. package/std/crypto/x509.ts +331 -171
  42. package/std/json-equal.ts +35 -19
  43. package/std/json-format.ts +215 -108
  44. package/std/json-number.ts +126 -72
  45. package/std/json-pointer.ts +42 -13
  46. package/std/json-tokenizer.ts +498 -307
  47. package/std/json-typed.ts +115 -36
  48. package/std/json-value.ts +341 -152
  49. package/std/json.ts +300 -158
  50. package/std/net/buffer-pool.ts +17 -7
  51. package/std/net/dns-config.ts +427 -236
  52. package/std/net/dns-message.ts +114 -47
  53. package/std/net/dns-resolver.ts +736 -237
  54. package/std/net/dns.ts +205 -52
  55. package/std/net/fetch.ts +320 -184
  56. package/std/net/grpc.ts +948 -0
  57. package/std/net/handler.ts +1275 -217
  58. package/std/net/hpack.ts +395 -180
  59. package/std/net/http-compress.ts +502 -65
  60. package/std/net/http-fields.ts +85 -49
  61. package/std/net/http-server.ts +1764 -602
  62. package/std/net/http1-client-codec.ts +372 -161
  63. package/std/net/http1-codec.ts +665 -331
  64. package/std/net/http1-server.ts +660 -278
  65. package/std/net/http2-cleartext.ts +165 -95
  66. package/std/net/http2-frame.ts +232 -89
  67. package/std/net/http2-tls.ts +42 -12
  68. package/std/net/http2.ts +327 -101
  69. package/std/net/http3-frame.ts +68 -33
  70. package/std/net/http3-server.ts +647 -192
  71. package/std/net/http3.ts +667 -189
  72. package/std/net/oidc.ts +63 -24
  73. package/std/net/outbound.ts +207 -142
  74. package/std/net/postgres-async.ts +1165 -443
  75. package/std/net/postgres-carrier.ts +575 -372
  76. package/std/net/postgres.ts +1459 -559
  77. package/std/net/prefork.ts +254 -98
  78. package/std/net/protobuf.ts +1017 -0
  79. package/std/net/qpack.ts +143 -92
  80. package/std/net/quic-conn-ack.ts +50 -18
  81. package/std/net/quic-conn-cid.ts +66 -26
  82. package/std/net/quic-conn-params.ts +13 -7
  83. package/std/net/quic-datagram.ts +90 -27
  84. package/std/net/quic-frame.ts +225 -124
  85. package/std/net/quic-listener.ts +197 -89
  86. package/std/net/quic-packet.ts +289 -163
  87. package/std/net/quic-recovery.ts +279 -128
  88. package/std/net/quic-stream.ts +466 -167
  89. package/std/net/quic.ts +568 -257
  90. package/std/net/router.ts +450 -99
  91. package/std/net/serve.ts +651 -232
  92. package/std/net/static.ts +1458 -0
  93. package/std/net/tls/client.ts +140 -45
  94. package/std/net/tls/codec.ts +510 -260
  95. package/std/net/tls/record-client.ts +268 -76
  96. package/std/net/tls/record-server.ts +236 -79
  97. package/std/net/tls/record.ts +173 -47
  98. package/std/net/tls/schedule.ts +58 -39
  99. package/std/net/tls/ticket.ts +295 -103
  100. package/std/net/tls/verify.ts +1 -1
  101. package/std/net/tls-tcp.ts +218 -75
  102. package/std/net/tls.ts +260 -152
  103. package/std/net/upstream.ts +283 -86
  104. package/std/net/url.ts +277 -102
  105. package/std/net/websocket.ts +370 -186
  106. package/std/net/webtransport.ts +755 -436
  107. package/std/regex.ts +1659 -829
  108. package/std/sync/ring.ts +320 -156
  109. package/std/sync/shm.ts +53 -6
  110. package/std/text.ts +205 -124
  111. package/std/threads.ts +22 -2
@@ -1,16 +1,17 @@
1
1
  /**
2
2
  * `nish/net/http-compress` — content coding for HTTP responses (RFC 9110
3
3
  * §8.4 and §12.5.3): reading a request's `Accept-Encoding` and compressing a
4
- * body with `Content-Encoding: gzip`, for any of the three servers.
4
+ * body with `Content-Encoding: gzip` or `deflate`, for any of the three
5
+ * servers.
5
6
  *
6
7
  * import { DEFLATE_FAST } from "nish/compress/deflate";
7
- * import { HTTP_OFFER_GZIP, HttpCompressor, httpAcceptEncoding } from "nish/net/http-compress";
8
+ * import { HTTP_OFFER_DEFLATE, HTTP_OFFER_GZIP, HttpCompressor, httpAcceptEncoding } from "nish/net/http-compress";
8
9
  *
9
10
  * const enc = new HttpCompressor(DEFLATE_FAST, 1024, 65536); // once per thread
10
11
  * // HTTP/1.1, in one call:
11
12
  * conn.respondEncoded(200, names, values, body, 0, n, enc, conn.acceptEncoding());
12
13
  * // HTTP/2 or HTTP/3, by hand:
13
- * const coding: i32 = httpAcceptEncoding(value, 0, toI32(value.length), HTTP_OFFER_GZIP);
14
+ * const coding: i32 = httpAcceptEncoding(value, 0, toI32(value.length), HTTP_OFFER_GZIP | HTTP_OFFER_DEFLATE);
14
15
  * const m: i32 = enc.compress(coding, body, 0, n);
15
16
  * if (m >= 0) {
16
17
  * enc.addFields(names, values);
@@ -20,8 +21,8 @@
20
21
  *
21
22
  * **Opt-in.** Nothing here runs unless the program asks: it decides which
22
23
  * responses to compress, and `HttpCompressor` declines any body shorter than
23
- * its `minLength`, longer than its `maxLength`, or that gzip would not make
24
- * smaller, answering -1 so the program sends the bytes as they are.
24
+ * its `minLength`, longer than its `maxLength`, or that compressing would not
25
+ * make smaller, answering -1 so the program sends the bytes as they are.
25
26
  *
26
27
  * **Compression that pays for itself.** A body is sent compressed only when it
27
28
  * saves at least `minSaving` bytes and `minSavingPercent` percent of the body;
@@ -35,7 +36,7 @@
35
36
  * After each call `decision` says why (`HTTP_COMPRESS_SENT`, `_NOT_ACCEPTED`,
36
37
  * `_TOO_SMALL`, `_TOO_LARGE`, `_TOO_LITTLE_SAVED`, `_NO_FEWER_SEGMENTS`), for a
37
38
  * program to count. A response whose identity form already fits one segment is
38
- * `_NO_FEWER_SEGMENTS` without running gzip at all, as no compression could
39
+ * `_NO_FEWER_SEGMENTS` without running an encoder at all, as no compression could
39
40
  * take fewer.
40
41
  *
41
42
  * **Two encoders.** Bodies up to `fixedLimit` (16 KB) go through
@@ -44,12 +45,21 @@
44
45
  * 16 KB of JSON for output about 1.35 times larger. Larger bodies go through
45
46
  * the `GzipCompressor` at the level given; `encoder` forces either one.
46
47
  *
48
+ * **Two codings.** `gzip` (RFC 1952) and `deflate`, which HTTP means as the
49
+ * zlib format (RFC 1950, RFC 9110 §8.4.1.2), are the same DEFLATE stream in
50
+ * different framing. A deflate body is written by the same two encoders as a
51
+ * gzip member and reframed in place: the 10-byte gzip header becomes the
52
+ * 2-byte zlib header, and the CRC-32 and length trailer an Adler-32, 12 bytes
53
+ * shorter in all. So the compressor holds one set of tables for both, at the
54
+ * cost of a CRC-32 it computes and drops on each deflate body.
55
+ *
47
56
  * **`Vary: Accept-Encoding`** (with `vary`, on by default) goes on every
48
57
  * response whose coding depended on the request: one sent compressed, and
49
- * one sent as it is because the request did not accept gzip. A body that is
50
- * too small, too large or did not pay is sent the same to every client, so
51
- * it carries no `Vary`. A request that refuses identity (`identity;q=0`)
52
- * and accepts gzip is sent gzip whatever the policy (`compressAnyway`).
58
+ * one sent as it is because the request did not accept the coding offered. A
59
+ * body that is too small, too large or did not pay is sent the same to every
60
+ * client, so it carries no `Vary`. `respondEncoded` sends gzip to a request
61
+ * refusing identity whatever the policy (`compressAnyway`), up to `maxLength`;
62
+ * deflate it holds to the policy, so such a caller calls `compressAnyway`.
53
63
  *
54
64
  * **Negotiation** (`httpAcceptEncoding`) follows §12.5.3: each listed coding
55
65
  * with its q-value, `x-gzip` as `gzip`, `*` for every coding not listed, and
@@ -69,12 +79,11 @@
69
79
  * `HttpCompressor` holds a `GzipCompressor`, a `GzipFixedCompressor`, an
70
80
  * output buffer of `compressBound(maxLength)` bytes and
71
81
  * the field arrays `addFields` fills, all built once.
72
- * `HTTP_CODING_DEFLATE` (zlib framing) is negotiated but not produced: a
73
- * client that accepts only `deflate` is sent identity, which every client
74
- * reads.
75
82
  */
76
- import { DEFLATE_FAST, compressBound } from "nish/compress/deflate"
77
- import { GzipCompressor, GzipFixedCompressor } from "nish/compress/gzip"
83
+ import { DEFLATE_ERR_OUTPUT_LIMIT, DEFLATE_FAST, compressBound } from "nish/compress/deflate"
84
+ import { adler32 } from "nish/compress/checksum"
85
+ import { GzipCompressor, GzipDecompressor, GzipFixedCompressor } from "nish/compress/gzip"
86
+ import { ZlibDecompressor } from "nish/compress/zlib"
78
87
  import { wrappingAdd } from "nish:unsafe"
79
88
 
80
89
  /** No content coding: the body as it is. */
@@ -88,35 +97,47 @@ export const HTTP_CODING_DEFLATE: i32 = 2
88
97
 
89
98
  /** Nothing offered is acceptable, identity included (§12.5.3: 406, or identity anyway). */
90
99
  export const HTTP_CODING_NONE: i32 = -1
100
+ /** `httpTryAcceptEncoding` and `httpTryContentEncoding`: the window lies outside its buffer. */
101
+ export const HTTP_CODING_BAD_WINDOW: i32 = -2
91
102
 
92
103
  /** `httpAcceptEncoding`'s `offered` bits: the program can send gzip, deflate. */
93
104
  export const HTTP_OFFER_GZIP: i32 = 1
94
- /** The `offered` bit for deflate, which is negotiated but never produced here. */
105
+ /** The `offered` bit for deflate, which `HttpCompressor` sends in the zlib format. */
95
106
  export const HTTP_OFFER_DEFLATE: i32 = 2
96
107
 
97
108
  /**
98
109
  * What `HttpCompressor.compress` (and `respondEncoded`'s segment check) last
99
110
  * decided, in `HttpCompressor.decision`, for a program to count: the body
100
- * went out compressed; the client did not take gzip; it was shorter than
101
- * `minLength`; longer than `maxLength`; gzip did not save `minSaving` bytes
111
+ * went out compressed; the client took neither gzip nor deflate; it was shorter than
112
+ * `minLength`; longer than `maxLength`; compressing did not save `minSaving` bytes
102
113
  * and `minSavingPercent` percent; or the compressed response would not have
103
114
  * taken fewer TCP segments (`segmentMode`), which includes an identity
104
115
  * response that already fits one segment, decided without compressing.
105
116
  */
106
117
  export const HTTP_COMPRESS_SENT: i32 = 0
107
- /** The client did not accept gzip, so the body went as it is; the default before any decision. */
118
+ /** The coding passed was neither gzip nor deflate, so the body went as it is; the default before any decision. */
108
119
  export const HTTP_COMPRESS_NOT_ACCEPTED: i32 = 1
109
120
  /** The body was shorter than `minLength`, too small to be worth compressing. */
110
121
  export const HTTP_COMPRESS_TOO_SMALL: i32 = 2
111
122
  /** The body was longer than `maxLength`, more than `output` was sized for. */
112
123
  export const HTTP_COMPRESS_TOO_LARGE: i32 = 3
113
124
  /**
114
- * Gzip ran but did not save `minSaving` bytes and `minSavingPercent` percent,
125
+ * An encoder ran but did not save `minSaving` bytes and `minSavingPercent` percent,
115
126
  * or the saving asked for was the whole body, so no encoder ran.
116
127
  */
117
128
  export const HTTP_COMPRESS_TOO_LITTLE_SAVED: i32 = 4
118
129
  /** Under `segmentMode`, compressing would not have saved a TCP segment. */
119
130
  export const HTTP_COMPRESS_NO_FEWER_SEGMENTS: i32 = 5
131
+ /**
132
+ * The encoder's gzip member could not be written into `output` or reframed as
133
+ * zlib, so the body went as it is. `output` is built with
134
+ * `compressBound(maxLength)` bytes, room for any body `compress` or
135
+ * `compressAnyway` accepts; it is reached when a caller has since shrunk
136
+ * `output` (`readonly` keeps the array, not its length).
137
+ */
138
+ export const HTTP_COMPRESS_FAILED: i32 = 6
139
+ /** `tryCompress` and `tryCompressAnyway`: the window lies outside the body, so nothing was compressed. */
140
+ export const HTTP_COMPRESS_BAD_WINDOW: i32 = 7
120
141
 
121
142
  /**
122
143
  * `HttpCompressor.encoder`: by the body's length (the fixed-Huffman encoder up
@@ -143,6 +164,12 @@ export const HTTP_DEFAULT_MSS: i32 = 1448
143
164
  /** The bytes `content-encoding: gzip` adds to an HTTP/1.1 head: name, value, ": " and CRLF. */
144
165
  export const HTTP1_GZIP_FIELD_BYTES: i32 = 24
145
166
 
167
+ /** How many bytes shorter a zlib stream is than the gzip member around the same DEFLATE stream: a 10-byte header and 8-byte trailer against 2 and 4. */
168
+ const HTTP_ZLIB_SHORTER: i32 = 12
169
+
170
+ /** `httpGzipToZlib`: the member was too short to reframe or passed its buffer. */
171
+ const HTTP_ZLIB_FAILED: i32 = -1
172
+
146
173
  /**
147
174
  * The number of TCP segments `bytes` bytes take at `mss` bytes a segment.
148
175
  * A segment size of zero or less panics, since no count would mean anything.
@@ -156,17 +183,35 @@ export const httpSegments = (bytes: i32, mss: i32): i32 => {
156
183
  if (mss <= 0) {
157
184
  panic("httpSegments: a segment size of zero or less")
158
185
  }
186
+ return httpSegmentsOf(bytes, toU32(mss))
187
+ }
188
+
189
+ /**
190
+ * `httpSegments` without its panic, for a `size` its caller has shown is 1 or
191
+ * more: `httpSegments` by its panic, `fewerSegments` by `segmentSize`, which
192
+ * answers a size above 0 or `HTTP_DEFAULT_MSS`. A `size` of 0 counts 0.
193
+ */
194
+ const httpSegmentsOf = (bytes: i32, size: u32): i32 => {
159
195
  if (bytes <= 0) {
160
196
  return 0
161
197
  }
162
- return (bytes - 1) / mss + 1
198
+ // `size` is 1 or more, so the quotient is at most `bytes - 1` and the sum
199
+ // at most `bytes`: unsigned arithmetic gives the same count with no check.
200
+ // Both callers pass 1 or more, so the test always holds; it is what shows
201
+ // the division has a divisor.
202
+ if (size > 0) {
203
+ return toI32((toU32(bytes) - 1) / size + 1)
204
+ }
205
+ return 0
163
206
  }
164
207
 
165
208
  /** The digits of `n` in decimal, `n` 0 or more. */
166
209
  const httpDecimalDigits = (n: i32): i32 => {
167
210
  let digits: i32 = 1
168
211
  let rest: i32 = n
169
- while (rest >= 10) {
212
+ // An `i32` has at most ten digits, so the second test always holds; it is
213
+ // what shows the count cannot run past them.
214
+ while (rest >= 10 && digits < 10) {
170
215
  rest = rest / 10
171
216
  digits += 1
172
217
  }
@@ -202,16 +247,20 @@ const httpCodingIs = (buf: u8[], start: i32, end: i32, word: string): boolean =>
202
247
  if (end - start !== toI32(word.length)) {
203
248
  return false
204
249
  }
205
- for (let i: i32 = 0; i < end - start && i < toI32(word.length); i += 1) {
206
- let c: i32 = toI32(buf[start + i])
250
+ // `j` walks `buf` and `i` walks `word` side by side. A window outside `buf`
251
+ // stops the walk short of the word's end, which answers false.
252
+ let i: i32 = 0
253
+ for (let j: i32 = start; j >= 0 && j < end && j < toI32(buf.length) && i < toI32(word.length); j += 1) {
254
+ let c: i32 = toI32(buf[j])
207
255
  if (c >= 65 && c <= 90) {
208
256
  c += 32
209
257
  }
210
258
  if (c !== toI32(word.charCodeAt(i))) {
211
259
  return false
212
260
  }
261
+ i += 1
213
262
  }
214
- return true
263
+ return i === toI32(word.length)
215
264
  }
216
265
 
217
266
  /**
@@ -220,7 +269,7 @@ const httpCodingIs = (buf: u8[], start: i32, end: i32, word: string): boolean =>
220
269
  * when it is not one.
221
270
  */
222
271
  const httpQValue = (buf: u8[], start: i32, end: i32): i32 => {
223
- if (start >= end) {
272
+ if (start >= end || start < 0 || start >= toI32(buf.length)) {
224
273
  return -1
225
274
  }
226
275
  const lead: i32 = toI32(buf[start])
@@ -231,16 +280,19 @@ const httpQValue = (buf: u8[], start: i32, end: i32): i32 => {
231
280
  if (start + 1 === end) {
232
281
  return q
233
282
  }
234
- if (buf[start + 1] !== 46 || end - start > 5) {
283
+ const dot: i32 = start + 1
284
+ if (dot >= toI32(buf.length) || buf[dot] !== 46 || end - start > 5) {
235
285
  return -1
236
286
  }
237
287
  let scale: i32 = 100
238
- for (let i: i32 = start + 2; i < end && i >= 0 && i < toI32(buf.length); i += 1) {
288
+ for (let i: i32 = dot + 1; i < end && i >= 0 && i < toI32(buf.length); i += 1) {
239
289
  const d: i32 = toI32(buf[i]) - 48
240
290
  if (d < 0 || d > 9 || (lead === 49 && d !== 0)) {
241
291
  return -1
242
292
  }
243
- q += d * scale
293
+ // At most three digits follow the point, each 9 or less at a scale of 100
294
+ // or less, so `q` stays under 1000 and unsigned arithmetic cannot wrap.
295
+ q = toI32(toU32(q) + toU32(d) * toU32(scale))
244
296
  scale = scale / 10
245
297
  }
246
298
  return q
@@ -273,9 +325,30 @@ const httpOws = (c: i32): boolean => c === 32 || c === 9
273
325
  * when nothing offered is acceptable and identity is refused too
274
326
  */
275
327
  export const httpAcceptEncoding = (buf: u8[], start: i32, end: i32, offered: i32): i32 => {
276
- if (start < 0 || start > end || end > toI32(buf.length)) {
328
+ const coding: i32 = httpTryAcceptEncoding(buf, start, end, offered)
329
+ if (coding === HTTP_CODING_BAD_WINDOW) {
277
330
  panic("httpAcceptEncoding: the window lies outside its buffer")
278
331
  }
332
+ return coding
333
+ }
334
+
335
+ /**
336
+ * `httpAcceptEncoding` that answers `HTTP_CODING_BAD_WINDOW` where
337
+ * `httpAcceptEncoding` panics: a window outside `buf`. A caller a strict
338
+ * module reaches uses this one.
339
+ *
340
+ * @param buf the buffer holding the field value, such as the request head
341
+ * @param start the index in `buf` of the value's first octet
342
+ * @param end the index just past the value's last octet
343
+ * @param offered which codings the program can produce, `HTTP_OFFER_*` bits
344
+ * or 0 for none
345
+ * @returns the `HTTP_CODING_*` to send the body in, `HTTP_CODING_NONE` when
346
+ * nothing offered is acceptable, or `HTTP_CODING_BAD_WINDOW`
347
+ */
348
+ export const httpTryAcceptEncoding = (buf: u8[], start: i32, end: i32, offered: i32): i32 => {
349
+ if (start < 0 || start > end || end > toI32(buf.length)) {
350
+ return HTTP_CODING_BAD_WINDOW
351
+ }
279
352
  let qGzip: i32 = -1
280
353
  let qDeflate: i32 = -1
281
354
  let qIdentity: i32 = -1
@@ -391,15 +464,64 @@ export const httpIdentityRefused = (buf: u8[], start: i32, end: i32): boolean =>
391
464
 
392
465
  /** The bytes of an ASCII string. */
393
466
  const httpCompressBytes = (text: string): u8[] => {
394
- const out: u8[] = new Array<u8>(toI32(text.length))
395
- for (let i: i32 = 0; i < toI32(text.length) && i < toI32(out.length); i += 1) {
396
- out[i] = toU8(text.charCodeAt(i))
467
+ const out: u8[] = []
468
+ for (let i: i32 = 0; i < toI32(text.length); i += 1) {
469
+ out.push(toU8(text.charCodeAt(i)))
397
470
  }
398
471
  return out
399
472
  }
400
473
 
401
474
  /**
402
- * Compresses response bodies with gzip into a buffer of its own, and builds
475
+ * Reframes the gzip member `out[0 .. n)` (a 10-byte header with no optional
476
+ * fields, as `GzipCompressor` and `GzipFixedCompressor` write) as the zlib
477
+ * stream of the same DEFLATE stream, in place: the header `0x78` and the
478
+ * `FLEVEL` of `level` (RFC 1950 §2.2), the DEFLATE stream moved down 8 bytes,
479
+ * and the Adler-32 of `src[off .. off + len)`, the data compressed.
480
+ *
481
+ * @returns the zlib stream's length, `n - HTTP_ZLIB_SHORTER`; or
482
+ * `HTTP_ZLIB_FAILED` when `out[0 .. n)` is too short to be a gzip member or
483
+ * passes `out`, which its callers turn into `HTTP_COMPRESS_FAILED`
484
+ */
485
+ const httpGzipToZlib = (out: u8[], n: i32, level: i32, src: u8[], off: i32, len: i32): i32 => {
486
+ let flevel: u32 = 3
487
+ if (level < 2) {
488
+ flevel = 0
489
+ } else if (level < 6) {
490
+ flevel = 1
491
+ } else if (level === 6) {
492
+ flevel = 2
493
+ }
494
+ const cmf: u32 = 0x78
495
+ const top: u32 = flevel << 6
496
+ // FCHECK makes `cmf * 256 + flg` a multiple of 31. Every number here is
497
+ // under 31000, so unsigned arithmetic cannot wrap.
498
+ const flg: u32 = top + ((toU32(31) - ((cmf * 256 + top) % 31)) % 31)
499
+ // Both callers pass what an encoder just wrote at the start of `out`: at
500
+ // least 18 bytes of gzip header and trailer, inside `out`. So the tests
501
+ // hold; they are what prove the writes below in bounds, and a miss answers
502
+ // `HTTP_ZLIB_FAILED`, which sends the body as it is.
503
+ if (n < 18 || n > toI32(out.length) || toI32(out.length) < 2) {
504
+ return HTTP_ZLIB_FAILED
505
+ }
506
+ const end: i32 = n - HTTP_ZLIB_SHORTER - 4
507
+ if (end < 0 || end + 3 >= toI32(out.length)) {
508
+ return HTTP_ZLIB_FAILED
509
+ }
510
+ out[0] = toU8(cmf)
511
+ out[1] = toU8(flg)
512
+ for (let i: i32 = 2; i < end && i >= 0 && i + 8 < toI32(out.length); i += 1) {
513
+ out[i] = out[i + 8]
514
+ }
515
+ const a: u32 = adler32(src, off, len)
516
+ out[end] = toU8(a >>> 24)
517
+ out[end + 1] = toU8((a >>> 16) & 255)
518
+ out[end + 2] = toU8((a >>> 8) & 255)
519
+ out[end + 3] = toU8(a & 255)
520
+ return end + 4
521
+ }
522
+
523
+ /**
524
+ * Compresses response bodies with gzip or deflate into a buffer of its own, and builds
403
525
  * the response fields that say so. One per thread; allocated once.
404
526
  */
405
527
  export class HttpCompressor {
@@ -414,6 +536,11 @@ export class HttpCompressor {
414
536
  readonly values: u8[][]
415
537
  private readonly contentEncodingName: u8[]
416
538
  private readonly gzipValue: u8[]
539
+ private readonly deflateValue: u8[]
540
+ /** The `Content-Encoding` value `addFields` adds: that of the last body sent compressed, gzip before any. */
541
+ private codingValue: u8[]
542
+ /** The constructor's deflate level, which a deflate body's zlib header names. */
543
+ private readonly level: i32
417
544
  private readonly varyName: u8[]
418
545
  private readonly acceptEncodingValue: u8[]
419
546
  /** The shortest body worth compressing, and the longest the output can hold. */
@@ -479,11 +606,22 @@ export class HttpCompressor {
479
606
  }
480
607
  this.gzip = new GzipCompressor(level)
481
608
  this.fixed = new GzipFixedCompressor()
482
- this.output = new Array<u8>(compressBound(maxLength))
609
+ // Grown a byte at a time, once: a length the compiler cannot see is not
610
+ // negative would cost `new Array` a check. No bench/instructions.json row
611
+ // builds a compressor, so no counted figure includes this loop.
612
+ const output: u8[] = []
613
+ const bound: i32 = compressBound(maxLength)
614
+ while (toI32(output.length) < bound) {
615
+ output.push(0)
616
+ }
617
+ this.output = output
483
618
  this.names = []
484
619
  this.values = []
485
620
  this.contentEncodingName = httpCompressBytes("content-encoding")
486
621
  this.gzipValue = httpCompressBytes("gzip")
622
+ this.deflateValue = httpCompressBytes("deflate")
623
+ this.codingValue = this.gzipValue
624
+ this.level = level
487
625
  this.varyName = httpCompressBytes("vary")
488
626
  this.acceptEncodingValue = httpCompressBytes("accept-encoding")
489
627
  this.minLength = minLength
@@ -501,8 +639,9 @@ export class HttpCompressor {
501
639
 
502
640
  /**
503
641
  * Compresses `body[off .. off + len)` into `output` when the length is in
504
- * `[minLength, maxLength]`, `coding` is `HTTP_CODING_GZIP` and gzip saves
505
- * what `minSaving` and `minSavingPercent` ask; answers the compressed
642
+ * `[minLength, maxLength]`, `coding` is `HTTP_CODING_GZIP` or
643
+ * `HTTP_CODING_DEFLATE` and compressing saves what `minSaving` and
644
+ * `minSavingPercent` ask; answers the compressed
506
645
  * length, or -1 to send the body as it is, and sets `decision` either way.
507
646
  * `encoder` picks the encoder; the fixed-Huffman one stops as soon as its
508
647
  * output passes what would be kept. A window outside `body` panics.
@@ -512,13 +651,35 @@ export class HttpCompressor {
512
651
  * @param body the buffer holding the response body
513
652
  * @param off the index in `body` where the body starts
514
653
  * @param len the body's length in bytes
515
- * @returns how many bytes of `output` hold the gzip body, or -1 to send the
516
- * body uncompressed; `decision` says which reason applied
654
+ * @returns how many bytes of `output` hold the gzip or deflate body, or -1
655
+ * to send the body uncompressed; `decision` says which reason applied
517
656
  */
518
657
  compress(coding: i32, body: u8[], off: i32, len: i32): i32 {
519
- if (off < 0 || len < 0 || off > toI32(body.length) - len) {
658
+ const n: i32 = this.tryCompress(coding, body, off, len)
659
+ if (this.decision === HTTP_COMPRESS_BAD_WINDOW) {
520
660
  panic("HttpCompressor.compress: the window lies outside its body")
521
661
  }
662
+ return n
663
+ }
664
+
665
+ /**
666
+ * `compress` that answers -1 with `decision` set to
667
+ * `HTTP_COMPRESS_BAD_WINDOW` where `compress` panics: a window outside
668
+ * `body`. A caller a strict module reaches uses this one.
669
+ *
670
+ * @param coding the coding negotiated for this request, from
671
+ * `httpAcceptEncoding`
672
+ * @param body the buffer holding the response body
673
+ * @param off the index in `body` where the body starts
674
+ * @param len the body's length in bytes
675
+ * @returns how many bytes of `output` hold the gzip or deflate body, or -1
676
+ * to send the body uncompressed; `decision` says which reason applied
677
+ */
678
+ tryCompress(coding: i32, body: u8[], off: i32, len: i32): i32 {
679
+ if (off < 0 || len < 0 || off > toI32(body.length) - len) {
680
+ this.decision = HTTP_COMPRESS_BAD_WINDOW
681
+ return -1
682
+ }
522
683
  if (len < this.minLength) {
523
684
  this.decision = HTTP_COMPRESS_TOO_SMALL
524
685
  return -1
@@ -527,68 +688,128 @@ export class HttpCompressor {
527
688
  this.decision = HTTP_COMPRESS_TOO_LARGE
528
689
  return -1
529
690
  }
530
- if (coding !== HTTP_CODING_GZIP) {
691
+ const deflate: boolean = coding === HTTP_CODING_DEFLATE
692
+ if (coding !== HTTP_CODING_GZIP && !deflate) {
531
693
  this.decision = HTTP_COMPRESS_NOT_ACCEPTED
532
694
  return -1
533
695
  }
534
696
  // The longest output kept; `output` holds `compressBound(maxLength)`, more.
535
- const keep: i32 = len - this.leastSaving(len)
697
+ // `len` is 0 or more and the saving 1 or more, so the difference is an
698
+ // `i32` and unsigned arithmetic gives it with no check.
699
+ const keep: i32 = toI32(toU32(len) - toU32(this.leastSaving(len)))
536
700
  let n: i32 = -1
537
701
  if (keep > 0) {
538
702
  const fixed: boolean =
539
703
  this.encoder === HTTP_ENCODER_FIXED || (this.encoder !== HTTP_ENCODER_LEVEL && len <= this.fixedLimit)
540
704
  this.encoderRuns = wrappingAdd(this.encoderRuns, 1)
705
+ // A gzip member `HTTP_ZLIB_SHORTER` bytes over `keep` still makes a deflate body that fits.
706
+ let room: i32 = keep
707
+ if (deflate) {
708
+ // Below `size - HTTP_ZLIB_SHORTER`, `keep` plus that many is below
709
+ // `size`, so the unsigned sum is the `i32` one.
710
+ const size: i32 = toI32(this.output.length)
711
+ room = keep < size - HTTP_ZLIB_SHORTER ? toI32(toU32(keep) + toU32(HTTP_ZLIB_SHORTER)) : size
712
+ }
541
713
  n = fixed
542
- ? this.fixed.compress(body, off, len, this.output, toI32(0), keep)
714
+ ? this.fixed.compress(body, off, len, this.output, toI32(0), room)
543
715
  : this.gzip.compress(body, off, len, this.output, toI32(0))
716
+ if (deflate && n >= 0) {
717
+ n = httpGzipToZlib(this.output, n, fixed ? toI32(1) : this.level, body, off, len)
718
+ if (n === HTTP_ZLIB_FAILED) {
719
+ this.decision = HTTP_COMPRESS_FAILED
720
+ return -1
721
+ }
722
+ }
544
723
  }
545
724
  if (n < 0 || n > keep) {
546
725
  this.decision = HTTP_COMPRESS_TOO_LITTLE_SAVED
547
726
  return -1
548
727
  }
549
- this.decision = HTTP_COMPRESS_SENT
728
+ this.sent(deflate)
550
729
  return n
551
730
  }
552
731
 
732
+ /** Records a body sent compressed, and the coding `addFields` names for it. */
733
+ private sent(deflate: boolean): void {
734
+ this.decision = HTTP_COMPRESS_SENT
735
+ this.codingValue = deflate ? this.deflateValue : this.gzipValue
736
+ }
737
+
553
738
  /**
554
739
  * `compress` for a client that refuses identity (`httpIdentityRefused`):
555
- * gzip whatever the body's length, the saving or the
740
+ * gzip or deflate whatever the body's length, the saving or the
556
741
  * segments, so long as it is no longer than `maxLength`. Answers the
557
- * compressed length, or -1 when `coding` is not gzip or the body is too
558
- * long (sent as it is, which RFC 9110 §12.5.3 allows).
742
+ * compressed length, or -1 when `coding` is neither gzip nor deflate or the
743
+ * body is too long (sent as it is, which RFC 9110 §12.5.3 allows).
559
744
  *
560
745
  * @param coding the coding negotiated for this request, from
561
746
  * `httpAcceptEncoding`
562
747
  * @param body the buffer holding the response body
563
748
  * @param off the index in `body` where the body starts
564
749
  * @param len the body's length in bytes
565
- * @returns how many bytes of `output` hold the gzip body, or -1 to send the
566
- * body uncompressed
750
+ * @returns how many bytes of `output` hold the gzip or deflate body, or -1
751
+ * to send the body uncompressed
567
752
  */
568
753
  compressAnyway(coding: i32, body: u8[], off: i32, len: i32): i32 {
569
- if (off < 0 || len < 0 || off > toI32(body.length) - len) {
754
+ const n: i32 = this.tryCompressAnyway(coding, body, off, len)
755
+ if (this.decision === HTTP_COMPRESS_BAD_WINDOW) {
570
756
  panic("HttpCompressor.compressAnyway: the window lies outside its body")
571
757
  }
758
+ return n
759
+ }
760
+
761
+ /**
762
+ * `compressAnyway` that answers -1 with `decision` set to
763
+ * `HTTP_COMPRESS_BAD_WINDOW` where `compressAnyway` panics: a window outside
764
+ * `body`. A caller a strict module reaches uses this one.
765
+ *
766
+ * @param coding the coding negotiated for this request, from
767
+ * `httpAcceptEncoding`
768
+ * @param body the buffer holding the response body
769
+ * @param off the index in `body` where the body starts
770
+ * @param len the body's length in bytes
771
+ * @returns how many bytes of `output` hold the gzip or deflate body, or -1
772
+ * to send the body uncompressed
773
+ */
774
+ tryCompressAnyway(coding: i32, body: u8[], off: i32, len: i32): i32 {
775
+ if (off < 0 || len < 0 || off > toI32(body.length) - len) {
776
+ this.decision = HTTP_COMPRESS_BAD_WINDOW
777
+ return -1
778
+ }
572
779
  if (len > this.maxLength) {
573
780
  this.decision = HTTP_COMPRESS_TOO_LARGE
574
781
  return -1
575
782
  }
576
- if (coding !== HTTP_CODING_GZIP) {
783
+ const deflate: boolean = coding === HTTP_CODING_DEFLATE
784
+ if (coding !== HTTP_CODING_GZIP && !deflate) {
577
785
  this.decision = HTTP_COMPRESS_NOT_ACCEPTED
578
786
  return -1
579
787
  }
580
788
  this.encoderRuns = wrappingAdd(this.encoderRuns, 1)
581
789
  let n: i32 = -1
790
+ let level: i32 = this.level
582
791
  if (
583
792
  this.encoder === HTTP_ENCODER_FIXED ||
584
793
  (this.encoder !== HTTP_ENCODER_LEVEL && len <= this.fixedLimit)
585
794
  ) {
586
795
  n = this.fixed.compress(body, off, len, this.output, toI32(0), toI32(this.output.length))
796
+ level = 1
587
797
  }
588
798
  if (n < 0) {
589
799
  n = this.gzip.compress(body, off, len, this.output, toI32(0))
800
+ level = this.level
590
801
  }
591
- this.decision = HTTP_COMPRESS_SENT
802
+ if (deflate && n >= 0) {
803
+ n = httpGzipToZlib(this.output, n, level, body, off, len)
804
+ }
805
+ if (n < 0) {
806
+ // `output` holds `compressBound(maxLength)` bytes, so an encoder always
807
+ // fits, and its member is long enough to reframe; were either to fail,
808
+ // the body goes out as it is.
809
+ this.decision = HTTP_COMPRESS_FAILED
810
+ return -1
811
+ }
812
+ this.sent(deflate)
592
813
  return n
593
814
  }
594
815
 
@@ -596,7 +817,7 @@ export class HttpCompressor {
596
817
  * The bytes a compressed `len`-byte body must save: `minSaving` and `minSavingPercent`, at least 1.
597
818
  *
598
819
  * @param len the uncompressed body's length in bytes
599
- * @returns the fewest bytes gzip must shave off for the compressed body to
820
+ * @returns the fewest bytes compressing must shave off for the compressed body to
600
821
  * be sent, never below 1; the percent share rounds up
601
822
  */
602
823
  leastSaving(len: i32): i32 {
@@ -633,8 +854,9 @@ export class HttpCompressor {
633
854
  * compressed response is worth sending
634
855
  */
635
856
  fewerSegments(identityBytes: i32, encodedBytes: i32, mss: i32): boolean {
636
- const size: i32 = this.segmentSize(mss)
637
- if (httpSegments(encodedBytes, size) < httpSegments(identityBytes, size)) {
857
+ // `segmentSize` answers 1 or more, so neither count can be refused.
858
+ const size: u32 = toU32(this.segmentSize(mss))
859
+ if (httpSegmentsOf(encodedBytes, size) < httpSegmentsOf(identityBytes, size)) {
638
860
  return true
639
861
  }
640
862
  this.decision = HTTP_COMPRESS_NO_FEWER_SEGMENTS
@@ -657,7 +879,7 @@ export class HttpCompressor {
657
879
  /**
658
880
  * `segmentMode`'s shortcut, before any encoder runs: whether a `len`-byte
659
881
  * body that `compress` would try (its length in `[minLength, maxLength]`
660
- * and `coding` gzip) is no longer than one segment of `mss` bytes (as
882
+ * and `coding` gzip or deflate) is no longer than one segment of `mss` bytes (as
661
883
  * `fewerSegments` reads it). Sent as it is, such a response takes one
662
884
  * segment once its head fits beside it, and no compression takes fewer, so
663
885
  * `decision` becomes `HTTP_COMPRESS_NO_FEWER_SEGMENTS` and the caller checks
@@ -670,12 +892,12 @@ export class HttpCompressor {
670
892
  * compressor's own
671
893
  * @returns true when the body fits one segment, so compressing it cannot
672
894
  * help and it is sent as it is if its head fits too; false when `coding` is
673
- * not gzip, `len` is outside `[minLength, maxLength]`, or the body does not
895
+ * neither gzip nor deflate, `len` is outside `[minLength, maxLength]`, or the body does not
674
896
  * fit one segment
675
897
  */
676
898
  oneSegment(coding: i32, len: i32, mss: i32): boolean {
677
899
  if (
678
- coding !== HTTP_CODING_GZIP ||
900
+ (coding !== HTTP_CODING_GZIP && coding !== HTTP_CODING_DEFLATE) ||
679
901
  len < this.minLength ||
680
902
  len > this.maxLength ||
681
903
  len > this.segmentSize(mss)
@@ -690,7 +912,7 @@ export class HttpCompressor {
690
912
  * The bytes of the HTTP/1.1 head a `length`-byte body sent as it is would
691
913
  * get, from `encodedHead`, that of the same response sent compressed as
692
914
  * `encodedLength` bytes with the fields `addFields` built: less
693
- * `Content-Encoding: gzip`, less `Vary` (a body the segment count kept as
915
+ * `Content-Encoding` and its value, less `Vary` (a body the segment count kept as
694
916
  * it is would go out so to any client), and the other `Content-Length`.
695
917
  *
696
918
  * @param encodedHead the compressed response's HTTP/1.1 head length in bytes
@@ -701,17 +923,24 @@ export class HttpCompressor {
701
923
  * uncompressed
702
924
  */
703
925
  http1IdentityHead(encodedHead: i32, encodedLength: i32, length: i32): i32 {
704
- let head: i32 = encodedHead - HTTP1_GZIP_FIELD_BYTES
926
+ // `encodedHead` is a head's length, and every field here a few bytes, so
927
+ // the answer is an `i32`; unsigned arithmetic wraps on the way and lands
928
+ // on the same bytes with no check.
929
+ let head: u32 =
930
+ toU32(encodedHead) -
931
+ toU32(HTTP1_GZIP_FIELD_BYTES) +
932
+ toU32(this.gzipValue.length) -
933
+ toU32(this.codingValue.length)
705
934
  if (this.vary) {
706
- head -= toI32(this.varyName.length) + toI32(this.acceptEncodingValue.length) + 4
935
+ head -= toU32(this.varyName.length) + toU32(this.acceptEncodingValue.length) + 4
707
936
  }
708
- return head - httpDecimalDigits(encodedLength) + httpDecimalDigits(length)
937
+ return toI32(head - toU32(httpDecimalDigits(encodedLength)) + toU32(httpDecimalDigits(length)))
709
938
  }
710
939
 
711
940
  /**
712
941
  * Whether the last decision depended on the request's `Accept-Encoding`, so
713
942
  * the response needs `Vary: Accept-Encoding`: a body sent compressed, or
714
- * one sent as it is because the client did not take gzip. A body the
943
+ * one sent as it is because the client took neither gzip nor deflate. A body the
715
944
  * lengths or the saving kept as it is would go out the same to any client.
716
945
  *
717
946
  * @returns true when the response must carry `Vary: Accept-Encoding` so a
@@ -723,7 +952,8 @@ export class HttpCompressor {
723
952
 
724
953
  /**
725
954
  * Sets `names` / `values` to the program's fields followed by
726
- * `Content-Encoding: gzip` and, when `vary`, `Vary: Accept-Encoding`. The
955
+ * `Content-Encoding` naming the coding of the last body `compress` or
956
+ * `compressAnyway` sent (`gzip` before any) and, when `vary`, `Vary: Accept-Encoding`. The
727
957
  * arrays are reused, so after the first few calls this allocates nothing;
728
958
  * they hold until the next call.
729
959
  *
@@ -747,7 +977,7 @@ export class HttpCompressor {
747
977
  }
748
978
  }
749
979
  this.names.push(this.contentEncodingName)
750
- this.values.push(this.gzipValue)
980
+ this.values.push(this.codingValue)
751
981
  if (this.vary) {
752
982
  this.names.push(this.varyName)
753
983
  this.values.push(this.acceptEncodingValue)
@@ -800,3 +1030,210 @@ export class HttpCompressor {
800
1030
  * other setting at its default
801
1031
  */
802
1032
  export const httpCompressorDefault = (): HttpCompressor => new HttpCompressor(DEFLATE_FAST, 1024, 1048576)
1033
+
1034
+ /**
1035
+ * The content coding a `Content-Encoding` value `buf[start .. end)` names
1036
+ * (RFC 9110 §8.4): `HTTP_CODING_GZIP` for `gzip` or `x-gzip`,
1037
+ * `HTTP_CODING_DEFLATE` for `deflate`, `HTTP_CODING_IDENTITY` for an empty
1038
+ * value or `identity`, ignoring case, optional whitespace and empty list
1039
+ * elements. Anything else — an unknown coding, a byte no coding holds, or
1040
+ * two codings applied one over the other — is `HTTP_CODING_NONE`, which a
1041
+ * reader cannot undo in one step. A window outside `buf` panics.
1042
+ * @param buf the bytes that hold the field value
1043
+ * @param start where the value starts in `buf`
1044
+ * @param end where the value ends in `buf`, one past its last byte
1045
+ * @returns the one coding named, `HTTP_CODING_IDENTITY` for none, or `HTTP_CODING_NONE`
1046
+ */
1047
+ export const httpContentEncoding = (buf: u8[], start: i32, end: i32): i32 => {
1048
+ const coding: i32 = httpTryContentEncoding(buf, start, end)
1049
+ if (coding === HTTP_CODING_BAD_WINDOW) {
1050
+ panic("httpContentEncoding: the window lies outside its buffer")
1051
+ }
1052
+ return coding
1053
+ }
1054
+
1055
+ /**
1056
+ * `httpContentEncoding` that answers `HTTP_CODING_BAD_WINDOW` where
1057
+ * `httpContentEncoding` panics: a window outside `buf`. A caller a strict
1058
+ * module reaches uses this one.
1059
+ * @param buf the bytes that hold the field value
1060
+ * @param start where the value starts in `buf`
1061
+ * @param end where the value ends in `buf`, one past its last byte
1062
+ * @returns the one coding named, `HTTP_CODING_IDENTITY` for none, `HTTP_CODING_NONE`, or `HTTP_CODING_BAD_WINDOW`
1063
+ */
1064
+ export const httpTryContentEncoding = (buf: u8[], start: i32, end: i32): i32 => {
1065
+ if (start < 0 || start > end || end > toI32(buf.length)) {
1066
+ return HTTP_CODING_BAD_WINDOW
1067
+ }
1068
+ let coding: i32 = HTTP_CODING_IDENTITY
1069
+ let p: i32 = start
1070
+ while (p < end) {
1071
+ while (p < end && (httpOws(toI32(buf[p])) || buf[p] === 44)) {
1072
+ p += 1
1073
+ }
1074
+ if (p >= end) {
1075
+ break
1076
+ }
1077
+ const codingStart: i32 = p
1078
+ while (p < end && httpCodingChar(toI32(buf[p]))) {
1079
+ p += 1
1080
+ }
1081
+ const codingEnd: i32 = p
1082
+ while (p < end && httpOws(toI32(buf[p]))) {
1083
+ p += 1
1084
+ }
1085
+ if (codingEnd === codingStart || (p < end && buf[p] !== 44)) {
1086
+ return HTTP_CODING_NONE
1087
+ }
1088
+ let named: i32 = HTTP_CODING_NONE
1089
+ if (
1090
+ httpCodingIs(buf, codingStart, codingEnd, "gzip") ||
1091
+ httpCodingIs(buf, codingStart, codingEnd, "x-gzip")
1092
+ ) {
1093
+ named = HTTP_CODING_GZIP
1094
+ } else if (httpCodingIs(buf, codingStart, codingEnd, "deflate")) {
1095
+ named = HTTP_CODING_DEFLATE
1096
+ } else if (httpCodingIs(buf, codingStart, codingEnd, "identity")) {
1097
+ continue
1098
+ }
1099
+ if (named === HTTP_CODING_NONE || coding !== HTTP_CODING_IDENTITY) {
1100
+ return HTTP_CODING_NONE
1101
+ }
1102
+ coding = named
1103
+ }
1104
+ return coding
1105
+ }
1106
+
1107
+ /** `HttpBodyDecoder.decode`: the body decodes to more than `limit` bytes. */
1108
+ export const HTTP_DECODE_TOO_LARGE: i32 = -1
1109
+ /** `HttpBodyDecoder.decode`: the body is not a whole, well-formed stream of its coding. */
1110
+ export const HTTP_DECODE_MALFORMED: i32 = -2
1111
+ /**
1112
+ * `HttpBodyDecoder.tryDecode`: the coding is neither gzip nor deflate, or the
1113
+ * window lies outside its buffer; nothing was decoded.
1114
+ */
1115
+ export const HTTP_DECODE_BAD_CALL: i32 = -3
1116
+
1117
+ /** The first output buffer `HttpBodyDecoder` makes, when its limit allows that many bytes. */
1118
+ const HTTP_DECODE_FIRST: i32 = 4096
1119
+
1120
+ /**
1121
+ * Decodes a request body sent with `Content-Encoding: gzip` or `deflate`
1122
+ * under a limit on what it decodes to, so a small body that inflates to
1123
+ * gigabytes (a decompression bomb) is refused once `limit` bytes are out,
1124
+ * having inflated fewer than three times `limit` bytes to find that out.
1125
+ * The decompressors are built once; `output` grows, doubling, to the
1126
+ * largest body decoded and is kept. Not shared between threads.
1127
+ *
1128
+ * const d = new HttpBodyDecoder(1 << 20)
1129
+ * const n: i32 = d.decode(HTTP_CODING_GZIP, body, 0, bodyLength) // d.output[0 .. n), or < 0
1130
+ */
1131
+ export class HttpBodyDecoder {
1132
+ /** The most bytes a body may decode to; one more is `HTTP_DECODE_TOO_LARGE`. */
1133
+ readonly limit: i32
1134
+ /**
1135
+ * Where `decode` writes, from index 0. A caller may take the array and
1136
+ * leave another in its place, which `decode` then writes into, or grows
1137
+ * past.
1138
+ */
1139
+ output: u8[]
1140
+ private readonly gunzip: GzipDecompressor
1141
+ private readonly unzlib: ZlibDecompressor
1142
+
1143
+ /**
1144
+ * A decoder that refuses a body decoding to more than `limit` bytes; a
1145
+ * `limit` under 1 panics.
1146
+ * @param limit the most bytes one body may decode to
1147
+ */
1148
+ constructor(limit: i32) {
1149
+ if (limit < 1) {
1150
+ panic(`HttpBodyDecoder: a limit of ${limit} is under 1`)
1151
+ }
1152
+ this.limit = limit
1153
+ this.output = []
1154
+ this.gunzip = new GzipDecompressor()
1155
+ this.unzlib = new ZlibDecompressor()
1156
+ }
1157
+
1158
+ /**
1159
+ * Decodes `src[off .. off + len)`, one body in `coding`, into `output`
1160
+ * from index 0. Another coding than `HTTP_CODING_GZIP` or
1161
+ * `HTTP_CODING_DEFLATE`, or a window outside `src`, panics; `tryDecode`
1162
+ * answers `HTTP_DECODE_BAD_CALL` instead.
1163
+ * @param coding `HTTP_CODING_GZIP` (one gzip member or several) or `HTTP_CODING_DEFLATE` (a zlib stream)
1164
+ * @param src the array that holds the encoded body
1165
+ * @param off where the body starts in `src`
1166
+ * @param len how many bytes the body is; every one must belong to the stream
1167
+ * @returns how many bytes the body decoded to, `output[0 .. result)`;
1168
+ * `HTTP_DECODE_TOO_LARGE` past `limit`; or `HTTP_DECODE_MALFORMED` for
1169
+ * a stream that is cut short, fails its check or has bytes after it.
1170
+ * After a refusal `output` means nothing.
1171
+ */
1172
+ decode(coding: i32, src: u8[], off: i32, len: i32): i32 {
1173
+ if (coding !== HTTP_CODING_GZIP && coding !== HTTP_CODING_DEFLATE) {
1174
+ panic(`HttpBodyDecoder.decode: coding ${coding} is neither gzip nor deflate`)
1175
+ }
1176
+ const end: i32 = this.tryDecode(coding, src, off, len)
1177
+ if (end === HTTP_DECODE_BAD_CALL) {
1178
+ panic("HttpBodyDecoder.decode: the window lies outside its buffer")
1179
+ }
1180
+ return end
1181
+ }
1182
+
1183
+ /**
1184
+ * `decode` that answers `HTTP_DECODE_BAD_CALL`, decoding nothing, where
1185
+ * `decode` panics: a coding other than `HTTP_CODING_GZIP` or
1186
+ * `HTTP_CODING_DEFLATE`, or a window outside `src`. The coding often comes
1187
+ * from a request's `Content-Encoding` (`httpContentEncoding`), so a caller
1188
+ * that passes it on unchecked uses this one.
1189
+ * @param coding `HTTP_CODING_GZIP` (one gzip member or several) or `HTTP_CODING_DEFLATE` (a zlib stream)
1190
+ * @param src the array that holds the encoded body
1191
+ * @param off where the body starts in `src`
1192
+ * @param len how many bytes the body is; every one must belong to the stream
1193
+ * @returns what `decode` answers, or `HTTP_DECODE_BAD_CALL`
1194
+ */
1195
+ tryDecode(coding: i32, src: u8[], off: i32, len: i32): i32 {
1196
+ if (coding !== HTTP_CODING_GZIP && coding !== HTTP_CODING_DEFLATE) {
1197
+ return HTTP_DECODE_BAD_CALL
1198
+ }
1199
+ if (off < 0 || len < 0 || off > toI32(src.length) - len) {
1200
+ return HTTP_DECODE_BAD_CALL
1201
+ }
1202
+ const limit: i32 = this.limit
1203
+ // A first guess of four times the input, so most bodies decode at once.
1204
+ // Under the test, `len` is at most a quarter of `limit`, so four times it
1205
+ // is an `i32` and the unsigned product is the same.
1206
+ let size: i32 = len > limit >> 2 ? limit : toI32(toU32(len) * 4)
1207
+ if (size < HTTP_DECODE_FIRST) {
1208
+ size = limit < HTTP_DECODE_FIRST ? limit : HTTP_DECODE_FIRST
1209
+ }
1210
+ while (true) {
1211
+ // Grown in place rather than made anew: a length the compiler cannot
1212
+ // see is not negative would cost `new Array` a check. The bytes kept
1213
+ // mean nothing, since each decode writes from the start. No
1214
+ // bench/instructions.json row gets here: pg-carrier's HttpHandler owns a
1215
+ // decoder but sends no Content-Encoding.
1216
+ const output: u8[] = this.output
1217
+ while (toI32(output.length) < size) {
1218
+ output.push(0)
1219
+ }
1220
+ const end: i32 =
1221
+ coding === HTTP_CODING_GZIP
1222
+ ? this.gunzip.decompress(src, off, len, this.output, toI32(0), limit)
1223
+ : this.unzlib.decompress(src, off, len, this.output, toI32(0), limit)
1224
+ if (end >= 0) {
1225
+ return end
1226
+ }
1227
+ if (end !== DEFLATE_ERR_OUTPUT_LIMIT) {
1228
+ return HTTP_DECODE_MALFORMED
1229
+ }
1230
+ const have: i32 = toI32(this.output.length)
1231
+ if (have >= limit) {
1232
+ return HTTP_DECODE_TOO_LARGE
1233
+ }
1234
+ // Under the test, `have` is at most half of `limit`, so twice it is an
1235
+ // `i32` and the unsigned product is the same.
1236
+ size = have > limit >> 1 ? limit : toI32(toU32(have) * 2)
1237
+ }
1238
+ }
1239
+ }