src/http.bend
emerging-ezhttp@0.10.0.0 · 852 lines · 0 definitions
1# ezhttp/src/http: HTTP/1.1 message text for client and server — request and
2# response formatting/parsing — with no sockets. Semantics follow RFC 9110;
3# message syntax and framing follow RFC 9112. TLS is outside this module.
4import Base
5import emerging-ezhttp@0.10.0.0/src/body.bend as Body
6
7# a string divided at the first occurrence of a pattern, or not divided at all
8type Cut is Data:
9 NoCut{}
10 Cut{before: String, after: String}
11
12# one header field name and value (RFC 9110 §5 / RFC 9112 §5)
13type Header is Data:
14 H{name: String, value: String}
15
16# what a response turned out to be: status, headers, framed body — or why not
17type Reply is Data:
18 Torn{why: String}
19 Reply{status: U32, headers: List<&2, Header>, body: String}
20
21# the first of a list of pieces, "" when there are none
22def first(ps: List<&2, String>) -> String:
23 match ps:
24 case []:
25 ""
26 case h <> t:
27 h
28
29# the second of a list of pieces, "" when there is no second
30def second(ps: List<&2, String>) -> String:
31 match ps:
32 case []:
33 ""
34 case h <> t:
35 first(t)
36
37# one char of the divide, put back on the front of what the rest found
38def divide.push(h: Char, r: Cut) -> Cut:
39 match r:
40 case NoCut{}:
41 NoCut{}
42 case Cut{before, after}:
43 Cut{SCon{h, before}, after}
44
45# one step of the walk; rest is a thunk so Bool.pick does not force recursion
46def divide.step(here: Bool, h: Char, t: String, n: Nat,
47 rest: Unit -> Cut) -> Cut:
48 match here:
49 case True{}:
50 Cut{"", String.drop(SCon{h, t}, n)}
51 case False{}:
52 divide.push(h, rest(Unit{}))
53
54# the walk: stop at the first hit
55def divide.go(s: String, +pat: String, +n: Nat) -> Cut:
56 match s:
57 case SNil{}:
58 NoCut{}
59 case SCon{+h, +t}:
60 divide.step(String.starts_with(SCon{h, t}, pat), h, t, n,
61 _u => divide.go(t, pat, n))
62
63# a string in two halves around the first occurrence of a pattern
64def divide(s: String, +pat: String) -> Cut:
65 divide.go(s, pat, String.length(pat))
66
67# the value of one hex digit's code point, or 16 when it is not one
68def hex.of(+u: U32) -> U32:
69 Bool.pick(U32, Bool.and(U32.is_ge(u, 48), U32.is_le(u, 57)), U32.sub(u, 48),
70 Bool.pick(U32, Bool.and(U32.is_ge(u, 97), U32.is_le(u, 102)), U32.sub(u, 87),
71 Bool.pick(U32, Bool.and(U32.is_ge(u, 65), U32.is_le(u, 70)), U32.sub(u, 55),
72 16)))
73
74# the value of one hex digit, or 16 when the char is not one
75def hex.val(c: Char) -> U32:
76 hex.of(Char.to_u32(c))
77
78# one step of the hex read
79def hex.step(done: Bool, acc: Nat, rest: Unit -> Nat) -> Nat:
80 match done:
81 case True{}:
82 acc
83 case False{}:
84 rest(Unit{})
85
86# the hex digits at the front of a string, read until one is not a digit
87def hex.go(s: String, +acc: Nat) -> Nat:
88 match s:
89 case SNil{}:
90 acc
91 case SCon{+h, t}:
92 +v = hex.val(h)
93 hex.step(U32.is_ge(v, 16), acc,
94 _u => hex.go(t, Nat.add(Nat.mul(acc, 16n), U32.to_nat(v))))
95
96# chunk-size from a chunk header (RFC 9112 §7.1); extensions after `;` ignored
97def hexlen(s: String) -> Nat:
98 hex.go(String.trim(first(String.split(s, ';'))), 0n)
99
100# whether a character is a hex digit
101def hex.digit(c: Char) -> Bool:
102 U32.is_lt(hex.val(c), 16)
103
104# the rest of a hex token once the first digit is known
105def hex.rest(token: String, good: Bool) -> Bool:
106 match token good:
107 case _ False{}:
108 False{}
109 case SNil{} True{}:
110 True{}
111 case SCon{h, t} True{}:
112 hex.rest(t, hex.digit(h))
113
114# a chunk-size token is one or more hex digits (RFC 9112 §7.1)
115def hex.well(token: String) -> Bool:
116 match token:
117 case SNil{}:
118 False{}
119 case SCon{h, t}:
120 hex.rest(t, hex.digit(h))
121
122# the chunk-size token, extensions after `;` removed
123def chunks.token(before: String) -> String:
124 String.trim(first(String.split(before, ';')))
125
126# bytes one code point takes in UTF-8. Content-Length counts octets
127# (RFC 9110 §8.6); a Bend String counts code points.
128def utf8.width(+u: U32) -> Nat:
129 Bool.pick(Nat, U32.is_lt(u, 128), 1n,
130 Bool.pick(Nat, U32.is_lt(u, 2048), 2n,
131 Bool.pick(Nat, U32.is_lt(u, 65536), 3n, 4n)))
132
133# how many bytes of UTF-8 a string is
134def utf8.len(s: String) -> Nat:
135 match s:
136 case SNil{}:
137 0n
138 case SCon{h, t}:
139 Nat.add(utf8.width(Char.to_u32(h)), utf8.len(t))
140
141# one step of the take
142def utf8.take.step(short: Bool, h: Char, rest: Unit -> String) -> String:
143 match short:
144 case True{}:
145 SNil{}
146 case False{}:
147 SCon{h, rest(Unit{})}
148
149# the front of a string that is this many bytes of UTF-8
150def utf8.take(s: String, +n: Nat) -> String:
151 match s:
152 case SNil{}:
153 SNil{}
154 case SCon{+h, t}:
155 +w = utf8.width(Char.to_u32(h))
156 utf8.take.step(Nat.is_lt(n, w), h, _u => utf8.take(t, Nat.sub(n, w)))
157
158# one step of the drop
159def utf8.drop.step(short: Bool, h: Char, t: String,
160 rest: Unit -> String) -> String:
161 match short:
162 case True{}:
163 SCon{h, t}
164 case False{}:
165 rest(Unit{})
166
167# the rest of a string after this many bytes of UTF-8
168def utf8.drop(s: String, +n: Nat) -> String:
169 match s:
170 case SNil{}:
171 SNil{}
172 case SCon{+h, +t}:
173 +w = utf8.width(Char.to_u32(h))
174 utf8.drop.step(Nat.is_lt(n, w), h, t, _u => utf8.drop(t, Nat.sub(n, w)))
175
176# a decimal digit's value, or 10 when the character is not a digit
177def digits.val.of(+u: U32) -> U32:
178 Bool.pick(U32, Bool.and(U32.is_ge(u, 48), U32.is_le(u, 57)), U32.sub(u, 48), 10)
179
180# a decimal digit's value, or 10 when the character is not a digit
181def digits.val(c: Char) -> U32:
182 digits.val.of(Char.to_u32(c))
183
184# accept one digit and keep reading, or stop when it is not a digit
185def digits.step(ok: Bool, next: Unit -> Maybe<&2, Nat>) -> Maybe<&2, Nat>:
186 match ok:
187 case False{}:
188 None{}
189 case True{}:
190 next(Unit{})
191
192# read a decimal token without building Base's Nat.read ceiling
193def digits.go(s: String, +acc: Nat, left: Nat) -> Maybe<&2, Nat>:
194 match s left:
195 case _ 0n:
196 None{}
197 case SNil{} 1n+k:
198 Some{acc}
199 case SCon{+h, t} 1n+k:
200 +d = digits.val(h)
201 digits.step(U32.is_lt(d, 10),
202 _u => digits.go(t, Nat.add(Nat.mul(acc, 10n), U32.to_nat(d)), k))
203
204# a short decimal (Content-Length, max-age). Empty is none. At most 9 digits.
205def digits.read(s: String) -> Maybe<&2, Nat>:
206 match s:
207 case SNil{}:
208 None{}
209 case SCon{h, t}:
210 digits.go(SCon{h, t}, 0n, 9n)
211
212# a non-zero chunk has its data and the following CRLF
213def chunks.ready(+after: String, +n: Nat) -> Bool:
214 Bool.and(Bool.not(Nat.is_lt(utf8.len(after), Nat.add(n, 2n))),
215 String.starts_with(utf8.drop(after, n), "\r\n"))
216
217# the next scan step, or why this chunk header is not usable
218type Next is Data:
219 Stop{}
220 Go{cut: Cut}
221 Reject{why: String}
222
223# one chunk header: reject non-hex sizes, stop on the 0 chunk, else continue
224def chunks.next.of(zero: Bool, ready: Bool, +after: String, +n: Nat) -> Next:
225 match zero ready:
226 case True{} _:
227 Stop{}
228 case False{} False{}:
229 Reject{"the chunked body stopped short"}
230 case False{} True{}:
231 Go{divide(utf8.drop(after, Nat.add(n, 2n)), "\r\n")}
232
233# hex check, then the length
234def chunks.next.hex(+before: String, +after: String, ok: Bool) -> Next:
235 match ok:
236 case False{}:
237 Reject{"chunk size is not hexadecimal"}
238 case True{}:
239 +n = hexlen(before)
240 chunks.next.of(Nat.is_eq(n, 0n), chunks.ready(after, n), after, n)
241
242# classify one chunk header (RFC 9112 §7.1)
243def chunks.next(+before: String, +after: String) -> Next:
244 chunks.next.hex(before, after, hex.well(chunks.token(before)))
245
246# apply one scan step
247def chunks.scan.step(step: Next, rest: Cut -> Maybe<&2, String>)
248 -> Maybe<&2, String>:
249 match step:
250 case Stop{}:
251 None{}
252 case Reject{why}:
253 Some{why}
254 case Go{cut}:
255 rest(cut)
256
257# None when every chunk size is hex and the 0 chunk is reached
258def chunks.scan(fuel: Nat, c: Cut) -> Maybe<&2, String>:
259 match fuel c:
260 case 0n _:
261 Some{"the chunked body is truncated"}
262 case 1n+f NoCut{}:
263 None{}
264 case 1n+f Cut{before, +after}:
265 chunks.scan.step(chunks.next(before, after), cut => chunks.scan(f, cut))
266
267# a zero chunk ends the body; anything after it is a trailer (RFC 9112 §7.1)
268def chunks.more(+n: Nat, +after: String, rest: Unit -> String, zero: Bool)
269 -> String:
270 match zero:
271 case True{}:
272 ""
273 case False{}:
274 utf8.take(after, n)
275 ++ rest(Unit{})
276
277# a chunked body put back together (RFC 9112 §7.1)
278def chunks(fuel: Nat, c: Cut) -> String:
279 match fuel c:
280 case 0n _:
281 ""
282 case 1n+f NoCut{}:
283 ""
284 case 1n+f Cut{before, +after}:
285 +n = hexlen(before)
286 chunks.more(n, after,
287 _u => chunks(f, divide(utf8.drop(after, Nat.add(n, 2n)), "\r\n")),
288 Nat.is_eq(n, 0n))
289
290# a Transfer-Encoding: chunked body as the octets it stands for
291def dechunk(+s: String) -> String:
292 chunks(String.length(s), divide(s, "\r\n"))
293
294# whether a head line names this header (field names are case-insensitive:
295# RFC 9110 §5.1)
296def head.hit(h: String, +name: String) -> Bool:
297 String.starts_with(String.to_lower(h), name ++ ":")
298
299# this line's value when it is the header asked for
300def head.pick(hit: Bool, h: String, name: String, rest: String) -> String:
301 match hit:
302 case True{}:
303 String.trim(String.drop(h, Nat.add(String.length(name), 1n)))
304 case False{}:
305 rest
306
307# the value a head gave a header, "" when it gave none
308def head.go(ls: List<&2, String>, +name: String) -> String:
309 match ls:
310 case []:
311 ""
312 case +h <> t:
313 head.pick(head.hit(h, name), h, name, head.go(t, name))
314
315# this line's trimmed field value
316def head.value(h: String, name: String) -> String:
317 String.trim(String.drop(h, Nat.add(String.length(name), 1n)))
318
319# cons a value when the line is the header asked for
320def head.values.cons(hit: Bool, value: String, rest: Unit -> List<&2, String>)
321 -> List<&2, String>:
322 match hit:
323 case False{}:
324 rest(Unit{})
325 case True{}:
326 value <> rest(Unit{})
327
328# every value a head gave a header, in order (RFC 9112 §6.3 lists Content-Length)
329def head.values(ls: List<&2, String>, +name: String) -> List<&2, String>:
330 match ls:
331 case []:
332 []
333 case +h <> t:
334 head.values.cons(head.hit(h, name), head.value(h, name),
335 _u => head.values(t, name))
336
337# a field value still holding a line break is obs-fold, which we refuse
338def field.folded(+value: String) -> Bool:
339 Bool.or(String.contains(value, "\n"), String.contains(value, "\r"))
340
341# a trimmed field value, or none when it still contains obs-fold
342def field.keep(name: String, +value: String, folded: Bool) -> Maybe<&2, Header>:
343 match folded:
344 case True{}:
345 None{}
346 case False{}:
347 Some{H{name, value}}
348
349# name and trimmed value from a cut at the first colon
350def head.from_kept(before: String, +after: String) -> Maybe<&2, Header>:
351 +value = String.trim(after)
352 field.keep(before, value, field.folded(value))
353
354# one header line as a Header, or none when it has no colon
355def head.from_cut(c: Cut) -> Maybe<&2, Header>:
356 match c:
357 case NoCut{}:
358 None{}
359 case Cut{before, after}:
360 head.from_kept(before, after)
361
362# one header line as a Header, or none when it has no colon
363def head.line(h: String) -> Maybe<&2, Header>:
364 head.from_cut(divide(h, ":"))
365
366# prepend a parsed header when present
367def head.cons(m: Maybe<&2, Header>, rest: List<&2, Header>) -> List<&2, Header>:
368 match m:
369 case None{}:
370 rest
371 case Some{hdr}:
372 hdr <> rest
373
374# header lines after the status line as a list of fields
375def head.list(ls: List<&2, String>) -> List<&2, Header>:
376 match ls:
377 case []:
378 []
379 case h <> t:
380 head.cons(head.line(h), head.list(t))
381
382# one request header line
383def header.line(h: Header) -> String:
384 match h:
385 case H{name, value}:
386 name ++ ": " ++ value ++ "\r\n"
387
388# the value when this field is the one asked for
389def headers.find.pick(value: String, hit: Bool, rest: Unit -> String) -> String:
390 match hit:
391 case True{}:
392 value
393 case False{}:
394 rest(Unit{})
395
396# case-insensitive field lookup (RFC 9110 §5.1)
397def headers.find.go(hs: List<&2, Header>, +name: String) -> String:
398 match hs:
399 case []:
400 ""
401 case H{n, v} <> t:
402 headers.find.pick(v, String.eq(String.to_lower(n), name),
403 _u => headers.find.go(t, name))
404
405# the value of a field, "" when it is absent
406def headers.find(hs: List<&2, Header>, +name: String) -> String:
407 headers.find.go(hs, String.to_lower(name))
408
409# extra headers rendered in order
410def headers.lines(hs: List<&2, Header>) -> String:
411 match hs:
412 case []:
413 ""
414 case h <> t:
415 header.line(h) ++ headers.lines(t)
416
417# Content-Length line when the body is not empty (RFC 9110 §8.6)
418def clen.line(+n: Nat, empty: Bool) -> String:
419 match empty:
420 case True{}:
421 ""
422 case False{}:
423 "Content-Length: " ++ Nat.show(n) ++ "\r\n"
424
425# a request-line and headers (RFC 9112 §3, §5). Absolute-path request-target
426# (RFC 9112 §3.2.1). Connection: close so the connection end frames the body
427# when no Content-Length / chunked framing applies (RFC 9112 §9.6 / §6.3).
428def request(method: String, host: String, path: String,
429 headers: List<&2, Header>, +body: String) -> String:
430 +n = utf8.len(body)
431 method ++ " " ++ path ++ " HTTP/1.1\r\n"
432 ++ "Host: " ++ host ++ "\r\n"
433 ++ "User-Agent: ezhttp\r\n"
434 ++ "Accept: */*\r\n"
435 ++ "Connection: close\r\n"
436 ++ headers.lines(headers)
437 ++ clen.line(n, Nat.is_eq(n, 0n))
438 ++ "\r\n"
439 ++ body
440
441# GET with optional headers
442def get_req(host: String, path: String, headers: List<&2, Header>) -> String:
443 request("GET", host, path, headers, "")
444
445# HEAD with optional headers (RFC 9110 §9.3.2): same as GET, no body
446def head_req(host: String, path: String, headers: List<&2, Header>) -> String:
447 request("HEAD", host, path, headers, "")
448
449# POST with body and optional headers
450def post_req(host: String, path: String, headers: List<&2, Header>,
451 body: Body.Body) -> String:
452 request("POST", host, path, headers, Body.body.payload(body))
453
454# PUT with body and optional headers (RFC 9110 §9.3.4)
455def put_req(host: String, path: String, headers: List<&2, Header>,
456 body: Body.Body) -> String:
457 request("PUT", host, path, headers, Body.body.payload(body))
458
459# DELETE with body and optional headers (RFC 9110 §9.3.5)
460def delete_req(host: String, path: String, headers: List<&2, Header>,
461 body: Body.Body) -> String:
462 request("DELETE", host, path, headers, Body.body.payload(body))
463
464# OPTIONS with optional headers (RFC 9110 §9.3.7). No request body.
465def options_req(host: String, path: String, headers: List<&2, Header>) -> String:
466 request("OPTIONS", host, path, headers, "")
467
468# GET, HEAD, and OPTIONS are safe (RFC 9110 §9.2.1). Tokens are case-sensitive.
469def method.safe(+method: String) -> Bool:
470 Bool.or(String.eq(method, "GET"),
471 Bool.or(String.eq(method, "HEAD"), String.eq(method, "OPTIONS")))
472
473# safe methods, plus PUT and DELETE, are idempotent (RFC 9110 §9.2.2)
474def method.idempotent(+method: String) -> Bool:
475 Bool.or(method.safe(method),
476 Bool.or(String.eq(method, "PUT"), String.eq(method, "DELETE")))
477
478# the rest of a token once this character is known
479def token.ok.step(space: Bool, rest: Unit -> Bool) -> Bool:
480 match space:
481 case True{}:
482 False{}
483 case False{}:
484 rest(Unit{})
485
486# a bearer token has no whitespace (RFC 6750 §2.1)
487def token.ok(s: String) -> Bool:
488 match s:
489 case SNil{}:
490 True{}
491 case SCon{h, t}:
492 token.ok.step(Char.is_space(h), _u => token.ok(t))
493
494# origin-form request-target: absolute-path, optional query (RFC 9112 §3.2.1)
495def target.origin(path: String) -> Bool:
496 String.starts_with(path, "/")
497
498# asterisk-form is only `*` and only for OPTIONS (RFC 9112 §3.2.4)
499def target.asterisk(method: String, star: Bool) -> Bool:
500 match star:
501 case False{}:
502 False{}
503 case True{}:
504 String.eq(method, "OPTIONS")
505
506# origin-form, or OPTIONS asterisk-form
507def target.form(method: String, path: String, absolute: Bool) -> Bool:
508 match absolute:
509 case True{}:
510 True{}
511 case False{}:
512 target.asterisk(method, String.eq(path, "*"))
513
514# a body against the length its head promised
515def parse.short(status: U32, headers: List<&2, Header>, n: Nat, body: String,
516 short: Bool) -> Reply:
517 match short:
518 case True{}:
519 Torn{"the response body stopped before its Content-Length"}
520 case False{}:
521 Reply{status, headers, utf8.take(body, n)}
522
523# a body framed by Content-Length (RFC 9110 §8.6 / RFC 9112 §6.3)
524def parse.clen(status: U32, headers: List<&2, Header>, +n: Nat, +body: String)
525 -> Reply:
526 parse.short(status, headers, n, body, Nat.is_lt(utf8.len(body), n))
527
528# Content-Length when present; else the rest of the connection is the body
529def parse.len(status: U32, headers: List<&2, Header>, m: Maybe<&2, Nat>,
530 body: String) -> Reply:
531 match m:
532 case None{}:
533 Reply{status, headers, body}
534 case Some{n}:
535 parse.clen(status, headers, n, body)
536
537# every Content-Length text equals the first
538def clen.agree.step(same: Bool, rest: Unit -> Bool) -> Bool:
539 match same:
540 case False{}:
541 False{}
542 case True{}:
543 rest(Unit{})
544
545# the tail of a Content-Length list against the first value
546def clen.agree.go(rest: List<&2, String>, +h: String) -> Bool:
547 match rest:
548 case []:
549 True{}
550 case x <> r:
551 clen.agree.step(String.eq(x, h), _u => clen.agree.go(r, h))
552
553# duplicate Content-Length fields must be the same digits (RFC 9112 §6.3)
554def clen.agree(vs: List<&2, String>) -> Bool:
555 match vs:
556 case []:
557 True{}
558 case h <> t:
559 clen.agree.go(t, h)
560
561# whether any Content-Length field was present
562def clen.any(vs: List<&2, String>) -> Bool:
563 match vs:
564 case []:
565 False{}
566 case h <> t:
567 True{}
568
569# a chunked body, or why the chunk framing was rejected
570def parse.chunked(status: U32, headers: List<&2, Header>, body: String,
571 bad: Maybe<&2, String>) -> Reply:
572 match bad:
573 case None{}:
574 Reply{status, headers, dechunk(body)}
575 case Some{why}:
576 Torn{why}
577
578# scan chunk sizes, then decode when they are hex and closed by 0
579def parse.chunks(status: U32, headers: List<&2, Header>, +body: String) -> Reply:
580 parse.chunked(status, headers, body,
581 chunks.scan(String.length(body), divide(body, "\r\n")))
582
583# Transfer-Encoding together with Content-Length is a bad message
584def parse.te.clash(status: U32, headers: List<&2, Header>, body: String,
585 present: Bool) -> Reply:
586 match present:
587 case True{}:
588 Torn{"Content-Length and Transfer-Encoding conflict"}
589 case False{}:
590 parse.chunks(status, headers, body)
591
592# chunked framing, or Content-Length, or the rest of the connection
593def parse.te(status: U32, headers: List<&2, Header>, +lens: List<&2, String>,
594 +body: String, chunked: Bool) -> Reply:
595 match chunked:
596 case False{}:
597 parse.len(status, headers, digits.read(first(lens)), body)
598 case True{}:
599 parse.te.clash(status, headers, body, clen.any(lens))
600
601# disagreeing Content-Length values are torn before framing
602def parse.agree(status: U32, headers: List<&2, Header>, te: String,
603 +lens: List<&2, String>, body: String, ok: Bool) -> Reply:
604 match ok:
605 case False{}:
606 Torn{"Content-Length values disagree"}
607 case True{}:
608 parse.te(status, headers, lens, body,
609 String.contains(String.to_lower(te), "chunked"))
610
611# the headers that decide the framing (RFC 9112 §6.3)
612def parse.frame(status: U32, headers: List<&2, Header>, te: String,
613 +lens: List<&2, String>, body: String) -> Reply:
614 parse.agree(status, headers, te, lens, body, clen.agree(lens))
615
616# a head whose status line has been read (RFC 9112 §4)
617def parse.status(m: Maybe<&2, U32>, +ls: List<&2, String>, body: String)
618 -> Reply:
619 match m:
620 case None{}:
621 Torn{"the response has no status line"}
622 case Some{n}:
623 +hs = head.list(ls)
624 parse.frame(n, hs, head.go(ls, "transfer-encoding"),
625 head.values(ls, "content-length"), body)
626
627# the head's lines, with the status line read off the first
628def parse.head(+ls: List<&2, String>, body: String) -> Reply:
629 parse.status(U32.read(second(String.split(first(ls), ' '))), ls, body)
630
631# a response divided into its head and everything after the blank line
632# (RFC 9112 §2.1: header section ends at empty line)
633def parse.cut(c: Cut) -> Reply:
634 match c:
635 case NoCut{}:
636 Torn{"the response head has no blank line after it"}
637 case Cut{before, after}:
638 parse.head(String.lines(before), after)
639
640# the status, headers, and body of a raw response
641def parse(raw: String) -> Reply:
642 parse.cut(divide(raw, "\r\n\r\n"))
643
644# a parsed response on one line, for a test to read
645def show(r: Reply) -> String:
646 match r:
647 case Torn{why}:
648 "torn " ++ why
649 case Reply{status, headers, body}:
650 U32.show(status) ++ " " ++ body
651
652# --- inbound request (server) and outbound response (server) ---
653
654# a request that came apart, or the reason it would not (RFC 9112 §3)
655type Request is Data:
656 Bad{why: String}
657 Request{method: String, target: String, headers: List<&2, Header>,
658 body: String}
659
660# reason-phrase for a few common status codes (RFC 9112 §4); others get ""
661def reason(+code: U32) -> String:
662 Bool.pick(String, U32.is_eq(code, 200), "OK",
663 Bool.pick(String, U32.is_eq(code, 201), "Created",
664 Bool.pick(String, U32.is_eq(code, 204), "No Content",
665 Bool.pick(String, U32.is_eq(code, 400), "Bad Request",
666 Bool.pick(String, U32.is_eq(code, 404), "Not Found",
667 Bool.pick(String, U32.is_eq(code, 405), "Method Not Allowed",
668 Bool.pick(String, U32.is_eq(code, 500), "Internal Server Error",
669 "")))))))
670
671# status-line + headers + body (RFC 9112 §4, §5). Connection: close ends the
672# exchange after one response.
673def respond(+status: U32, headers: List<&2, Header>, +body: String) -> String:
674 +n = utf8.len(body)
675 "HTTP/1.1 " ++ U32.show(status) ++ " " ++ reason(status) ++ "\r\n"
676 ++ "Connection: close\r\n"
677 ++ headers.lines(headers)
678 ++ clen.line(n, Nat.is_eq(n, 0n))
679 ++ "\r\n"
680 ++ body
681
682# 204 and 304 are terminated by the header section (RFC 9110 §15.3.5, §15.4.5)
683def status.nocontent(+code: U32) -> Bool:
684 Bool.or(U32.is_eq(code, 204), U32.is_eq(code, 304))
685
686# drop a 204/304 body; any other status keeps it
687def respond.of.body(+status: U32, headers: List<&2, Header>, body: String,
688 drop: Bool) -> String:
689 match drop:
690 case True{}:
691 respond(status, headers, "")
692 case False{}:
693 respond(status, headers, body)
694
695# format a structured Reply as a response message
696def respond.of(r: Reply) -> String:
697 match r:
698 case Torn{why}:
699 respond(500, [], why)
700 case Reply{+status, headers, body}:
701 respond.of.body(status, headers, body, status.nocontent(status))
702
703# HEAD carries no message body; any other method keeps the body (RFC 9110 §9.3.2)
704def reply.for.pick(reply: Reply, head: Bool) -> Reply:
705 match reply head:
706 case Torn{why} _:
707 Torn{why}
708 case Reply{status, headers, body} False{}:
709 Reply{status, headers, body}
710 case Reply{status, headers, body} True{}:
711 Reply{status, headers, ""}
712
713# drop a HEAD response body before it is written
714def reply.for(method: String, reply: Reply) -> Reply:
715 reply.for.pick(reply, String.eq(method, "HEAD"))
716
717# the method token, or "" when the request did not parse
718def method.of(req: Request) -> String:
719 match req:
720 case Bad{why}:
721 ""
722 case Request{method, target, headers, body}:
723 method
724
725# request body against Content-Length
726def ask.short(method: String, target: String, headers: List<&2, Header>,
727 n: Nat, body: String, short: Bool) -> Request:
728 match short:
729 case True{}:
730 Bad{"the request body stopped before its Content-Length"}
731 case False{}:
732 Request{method, target, headers, utf8.take(body, n)}
733
734# a request body framed by Content-Length (RFC 9110 §8.6 / RFC 9112 §6.3)
735def ask.clen(method: String, target: String, headers: List<&2, Header>,
736 +n: Nat, +body: String) -> Request:
737 ask.short(method, target, headers, n, body, Nat.is_lt(utf8.len(body), n))
738
739# Content-Length when present; else the rest of the connection is the body
740def ask.len(method: String, target: String, headers: List<&2, Header>,
741 m: Maybe<&2, Nat>, body: String) -> Request:
742 match m:
743 case None{}:
744 Request{method, target, headers, body}
745 case Some{n}:
746 ask.clen(method, target, headers, n, body)
747
748# a chunked request body, or why the chunk framing was rejected
749def ask.chunked(method: String, target: String, headers: List<&2, Header>,
750 body: String, bad: Maybe<&2, String>) -> Request:
751 match bad:
752 case None{}:
753 Request{method, target, headers, dechunk(body)}
754 case Some{why}:
755 Bad{why}
756
757# scan chunk sizes, then decode when they are hex and closed by 0
758def ask.chunks(method: String, target: String, headers: List<&2, Header>,
759 +body: String) -> Request:
760 ask.chunked(method, target, headers, body,
761 chunks.scan(String.length(body), divide(body, "\r\n")))
762
763# Transfer-Encoding together with Content-Length is a bad request
764def ask.te.clash(method: String, target: String, headers: List<&2, Header>,
765 body: String, present: Bool) -> Request:
766 match present:
767 case True{}:
768 Bad{"Content-Length and Transfer-Encoding conflict"}
769 case False{}:
770 ask.chunks(method, target, headers, body)
771
772# chunked framing, or Content-Length, or the rest of the connection
773def ask.te(method: String, target: String, headers: List<&2, Header>,
774 +lens: List<&2, String>, +body: String, chunked: Bool) -> Request:
775 match chunked:
776 case False{}:
777 ask.len(method, target, headers, digits.read(first(lens)), body)
778 case True{}:
779 ask.te.clash(method, target, headers, body, clen.any(lens))
780
781# disagreeing Content-Length values are bad before framing
782def ask.agree(method: String, target: String, headers: List<&2, Header>,
783 te: String, +lens: List<&2, String>, body: String, ok: Bool) -> Request:
784 match ok:
785 case False{}:
786 Bad{"Content-Length values disagree"}
787 case True{}:
788 ask.te(method, target, headers, lens, body,
789 String.contains(String.to_lower(te), "chunked"))
790
791# the headers that decide request framing (RFC 9112 §6.3)
792def ask.frame(method: String, target: String, headers: List<&2, Header>,
793 te: String, +lens: List<&2, String>, body: String) -> Request:
794 ask.agree(method, target, headers, te, lens, body, clen.agree(lens))
795
796# origin-form, or a bad request when the target is not an absolute-path
797def ask.origin(method: String, target: String, +ls: List<&2, String>,
798 body: String, ok: Bool) -> Request:
799 match ok:
800 case False{}:
801 Bad{"the request-target is not in origin-form"}
802 case True{}:
803 +hs = head.list(ls)
804 ask.frame(method, target, hs, head.go(ls, "transfer-encoding"),
805 head.values(ls, "content-length"), body)
806
807# request-line: method SP request-target SP HTTP-version (RFC 9112 §3)
808def ask.line(+method: String, +target: String, +ls: List<&2, String>,
809 body: String) -> Request:
810 ask.origin(method, target, ls, body,
811 target.form(method, target, target.origin(target)))
812
813# three fields of the request-line, or torn
814def ask.parts(ps: List<&2, String>, +ls: List<&2, String>, body: String)
815 -> Request:
816 match ps:
817 case []:
818 Bad{"the request has no request line"}
819 case m <> rest:
820 match rest:
821 case []:
822 Bad{"the request line has no target"}
823 case t <> _ver:
824 ask.line(m, t, ls, body)
825
826# the head's lines, with the request-line read off the first
827def ask.head(+ls: List<&2, String>, body: String) -> Request:
828 match ls:
829 case []:
830 Bad{"the request has no request line"}
831 case _:
832 ask.parts(String.split(first(ls), ' '), ls, body)
833
834# a request divided into its head and everything after the blank line
835def ask.cut(c: Cut) -> Request:
836 match c:
837 case NoCut{}:
838 Bad{"the request head has no blank line after it"}
839 case Cut{before, after}:
840 ask.head(String.lines(before), after)
841
842# the method, target, headers, and body of a raw request
843def ask(raw: String) -> Request:
844 ask.cut(divide(raw, "\r\n\r\n"))
845
846# a parsed request on one line, for a test to read
847def ask.show(r: Request) -> String:
848 match r:
849 case Bad{why}:
850 "bad " ++ why
851 case Request{method, target, headers, body}:
852 method ++ " " ++ target ++ " " ++ body