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. 4 import Base 5 import ./body.bend as Body 6 7 # a string divided at the first occurrence of a pattern, or not divided at all 8 type 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) 13 type 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 17 type 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 22 def 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 30 def 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 38 def 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 46 def 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 55 def 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 64 def 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 68 def 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 75 def hex.val(c: Char) -> U32: 76 hex.of(Char.to_u32(c)) 77 78 # one step of the hex read 79 def 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 87 def 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 97 def hexlen(s: String) -> Nat: 98 hex.go(String.trim(first(String.split(s, ';'))), 0n) 99 100 # whether a character is a hex digit 101 def 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 105 def 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) 115 def 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 123 def 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. 128 def 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 134 def 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 142 def 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 150 def 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 159 def 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 168 def 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 177 def 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 181 def 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 185 def 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 193 def 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. 205 def 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 213 def 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 218 type 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 224 def 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 234 def 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) 243 def chunks.next(+before: String, +after: String) -> Next: 244 chunks.next.hex(before, after, hex.well(chunks.token(before))) 245 246 # apply one scan step 247 def 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 258 def 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) 268 def 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) 278 def 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 291 def 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) 296 def 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 300 def 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 308 def 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 316 def 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 320 def 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) 329 def 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 338 def 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 342 def 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 350 def 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 355 def 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 363 def head.line(h: String) -> Maybe<&2, Header>: 364 head.from_cut(divide(h, ":")) 365 366 # prepend a parsed header when present 367 def 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 375 def 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 383 def 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 389 def 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) 397 def 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 406 def 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 410 def 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) 418 def 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). 428 def 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 # the port a scheme implies: 443 for a secure one, 80 otherwise (RFC 9110 442 # §4.2.1, §4.2.2) 443 def port.dflt(secure: Bool) -> U32: 444 match secure: 445 case True{}: 446 443 447 case False{}: 448 80 449 450 # the Host field value once it is known whether the port is the default 451 def authority.of(host: String, +port: U32, dflt: Bool) -> String: 452 match dflt: 453 case True{}: 454 host 455 case False{}: 456 host ++ ":" ++ U32.show(port) 457 458 # the Host field value: the host, and the port after a colon unless it is the 459 # scheme's default (RFC 9110 §7.2) 460 def authority(secure: Bool, host: String, +port: U32) -> String: 461 authority.of(host, port, U32.is_eq(port, port.dflt(secure))) 462 463 # the request a client sends to host and port, over TLS when secure 464 def request.at(method: String, secure: Bool, host: String, port: U32, 465 path: String, headers: List<&2, Header>, body: String) -> String: 466 request(method, authority(secure, host, port), path, headers, body) 467 468 # GET with optional headers 469 def get_req(host: String, path: String, headers: List<&2, Header>) -> String: 470 request("GET", host, path, headers, "") 471 472 # HEAD with optional headers (RFC 9110 §9.3.2): same as GET, no body 473 def head_req(host: String, path: String, headers: List<&2, Header>) -> String: 474 request("HEAD", host, path, headers, "") 475 476 # POST with body and optional headers 477 def post_req(host: String, path: String, headers: List<&2, Header>, 478 body: Body.Body) -> String: 479 request("POST", host, path, headers, Body.body.payload(body)) 480 481 # PUT with body and optional headers (RFC 9110 §9.3.4) 482 def put_req(host: String, path: String, headers: List<&2, Header>, 483 body: Body.Body) -> String: 484 request("PUT", host, path, headers, Body.body.payload(body)) 485 486 # DELETE with body and optional headers (RFC 9110 §9.3.5) 487 def delete_req(host: String, path: String, headers: List<&2, Header>, 488 body: Body.Body) -> String: 489 request("DELETE", host, path, headers, Body.body.payload(body)) 490 491 # OPTIONS with optional headers (RFC 9110 §9.3.7). No request body. 492 def options_req(host: String, path: String, headers: List<&2, Header>) -> String: 493 request("OPTIONS", host, path, headers, "") 494 495 # GET, HEAD, and OPTIONS are safe (RFC 9110 §9.2.1). Tokens are case-sensitive. 496 def method.safe(+method: String) -> Bool: 497 Bool.or(String.eq(method, "GET"), 498 Bool.or(String.eq(method, "HEAD"), String.eq(method, "OPTIONS"))) 499 500 # safe methods, plus PUT and DELETE, are idempotent (RFC 9110 §9.2.2) 501 def method.idempotent(+method: String) -> Bool: 502 Bool.or(method.safe(method), 503 Bool.or(String.eq(method, "PUT"), String.eq(method, "DELETE"))) 504 505 # the rest of a token once this character is known 506 def token.ok.step(space: Bool, rest: Unit -> Bool) -> Bool: 507 match space: 508 case True{}: 509 False{} 510 case False{}: 511 rest(Unit{}) 512 513 # a bearer token has no whitespace (RFC 6750 §2.1) 514 def token.ok(s: String) -> Bool: 515 match s: 516 case SNil{}: 517 True{} 518 case SCon{h, t}: 519 token.ok.step(Char.is_space(h), _u => token.ok(t)) 520 521 # origin-form request-target: absolute-path, optional query (RFC 9112 §3.2.1) 522 def target.origin(path: String) -> Bool: 523 String.starts_with(path, "/") 524 525 # asterisk-form is only `*` and only for OPTIONS (RFC 9112 §3.2.4) 526 def target.asterisk(method: String, star: Bool) -> Bool: 527 match star: 528 case False{}: 529 False{} 530 case True{}: 531 String.eq(method, "OPTIONS") 532 533 # origin-form, or OPTIONS asterisk-form 534 def target.form(method: String, path: String, absolute: Bool) -> Bool: 535 match absolute: 536 case True{}: 537 True{} 538 case False{}: 539 target.asterisk(method, String.eq(path, "*")) 540 541 # a body against the length its head promised 542 def parse.short(status: U32, headers: List<&2, Header>, n: Nat, body: String, 543 short: Bool) -> Reply: 544 match short: 545 case True{}: 546 Torn{"the response body stopped before its Content-Length"} 547 case False{}: 548 Reply{status, headers, utf8.take(body, n)} 549 550 # a body framed by Content-Length (RFC 9110 §8.6 / RFC 9112 §6.3) 551 def parse.clen(status: U32, headers: List<&2, Header>, +n: Nat, +body: String) 552 -> Reply: 553 parse.short(status, headers, n, body, Nat.is_lt(utf8.len(body), n)) 554 555 # Content-Length when present; else the rest of the connection is the body 556 def parse.len(status: U32, headers: List<&2, Header>, m: Maybe<&2, Nat>, 557 body: String) -> Reply: 558 match m: 559 case None{}: 560 Reply{status, headers, body} 561 case Some{n}: 562 parse.clen(status, headers, n, body) 563 564 # every Content-Length text equals the first 565 def clen.agree.step(same: Bool, rest: Unit -> Bool) -> Bool: 566 match same: 567 case False{}: 568 False{} 569 case True{}: 570 rest(Unit{}) 571 572 # the tail of a Content-Length list against the first value 573 def clen.agree.go(rest: List<&2, String>, +h: String) -> Bool: 574 match rest: 575 case []: 576 True{} 577 case x <> r: 578 clen.agree.step(String.eq(x, h), _u => clen.agree.go(r, h)) 579 580 # duplicate Content-Length fields must be the same digits (RFC 9112 §6.3) 581 def clen.agree(vs: List<&2, String>) -> Bool: 582 match vs: 583 case []: 584 True{} 585 case h <> t: 586 clen.agree.go(t, h) 587 588 # whether any Content-Length field was present 589 def clen.any(vs: List<&2, String>) -> Bool: 590 match vs: 591 case []: 592 False{} 593 case h <> t: 594 True{} 595 596 # a chunked body, or why the chunk framing was rejected 597 def parse.chunked(status: U32, headers: List<&2, Header>, body: String, 598 bad: Maybe<&2, String>) -> Reply: 599 match bad: 600 case None{}: 601 Reply{status, headers, dechunk(body)} 602 case Some{why}: 603 Torn{why} 604 605 # scan chunk sizes, then decode when they are hex and closed by 0 606 def parse.chunks(status: U32, headers: List<&2, Header>, +body: String) -> Reply: 607 parse.chunked(status, headers, body, 608 chunks.scan(String.length(body), divide(body, "\r\n"))) 609 610 # Transfer-Encoding together with Content-Length is a bad message 611 def parse.te.clash(status: U32, headers: List<&2, Header>, body: String, 612 present: Bool) -> Reply: 613 match present: 614 case True{}: 615 Torn{"Content-Length and Transfer-Encoding conflict"} 616 case False{}: 617 parse.chunks(status, headers, body) 618 619 # chunked framing, or Content-Length, or the rest of the connection 620 def parse.te(status: U32, headers: List<&2, Header>, +lens: List<&2, String>, 621 +body: String, chunked: Bool) -> Reply: 622 match chunked: 623 case False{}: 624 parse.len(status, headers, digits.read(first(lens)), body) 625 case True{}: 626 parse.te.clash(status, headers, body, clen.any(lens)) 627 628 # disagreeing Content-Length values are torn before framing 629 def parse.agree(status: U32, headers: List<&2, Header>, te: String, 630 +lens: List<&2, String>, body: String, ok: Bool) -> Reply: 631 match ok: 632 case False{}: 633 Torn{"Content-Length values disagree"} 634 case True{}: 635 parse.te(status, headers, lens, body, 636 String.contains(String.to_lower(te), "chunked")) 637 638 # the headers that decide the framing (RFC 9112 §6.3) 639 def parse.frame(status: U32, headers: List<&2, Header>, te: String, 640 +lens: List<&2, String>, body: String) -> Reply: 641 parse.agree(status, headers, te, lens, body, clen.agree(lens)) 642 643 # a head whose status line has been read (RFC 9112 §4) 644 def parse.status(m: Maybe<&2, U32>, +ls: List<&2, String>, body: String) 645 -> Reply: 646 match m: 647 case None{}: 648 Torn{"the response has no status line"} 649 case Some{n}: 650 +hs = head.list(ls) 651 parse.frame(n, hs, head.go(ls, "transfer-encoding"), 652 head.values(ls, "content-length"), body) 653 654 # the status code a head's first line names, if it names one (RFC 9112 §4) 655 def status.of(ls: List<&2, String>) -> Maybe<&2, U32>: 656 U32.read(second(String.split(first(ls), ' '))) 657 658 # the head's lines, with the status line read off the first 659 def parse.head(+ls: List<&2, String>, body: String) -> Reply: 660 parse.status(status.of(ls), ls, body) 661 662 # a response divided into its head and everything after the blank line 663 # (RFC 9112 §2.1: header section ends at empty line) 664 def parse.cut(c: Cut) -> Reply: 665 match c: 666 case NoCut{}: 667 Torn{"the response head has no blank line after it"} 668 case Cut{before, after}: 669 parse.head(String.lines(before), after) 670 671 # the status, headers, and body of a raw response 672 def parse(raw: String) -> Reply: 673 parse.cut(divide(raw, "\r\n\r\n")) 674 675 # a parsed response on one line, for a test to read 676 def show(r: Reply) -> String: 677 match r: 678 case Torn{why}: 679 "torn " ++ why 680 case Reply{status, headers, body}: 681 U32.show(status) ++ " " ++ body 682 683 # --- inbound request (server) and outbound response (server) --- 684 685 # a request that came apart, or the reason it would not (RFC 9112 §3) 686 type Request is Data: 687 Bad{why: String} 688 Request{method: String, target: String, headers: List<&2, Header>, 689 body: String} 690 691 # a status code and its reason-phrase 692 type Phrase is Data: 693 P{code: U32, text: String} 694 695 # the reason-phrases RFC 9110 §15 names (RFC 6585 §4 for 429) 696 def reasons() -> List<&2, Phrase>: 697 [P{200, "OK"}, P{201, "Created"}, P{202, "Accepted"}, P{204, "No Content"}, 698 P{301, "Moved Permanently"}, P{302, "Found"}, P{303, "See Other"}, 699 P{304, "Not Modified"}, P{307, "Temporary Redirect"}, 700 P{308, "Permanent Redirect"}, P{400, "Bad Request"}, 701 P{401, "Unauthorized"}, P{403, "Forbidden"}, P{404, "Not Found"}, 702 P{405, "Method Not Allowed"}, P{409, "Conflict"}, P{410, "Gone"}, 703 P{413, "Content Too Large"}, P{415, "Unsupported Media Type"}, 704 P{422, "Unprocessable Content"}, P{429, "Too Many Requests"}, 705 P{500, "Internal Server Error"}, P{501, "Not Implemented"}, 706 P{502, "Bad Gateway"}, P{503, "Service Unavailable"}, 707 P{504, "Gateway Timeout"}] 708 709 # this phrase when its code is the one asked for, else the rest's 710 def reason.pick(text: String, hit: Bool, rest: Unit -> String) -> String: 711 match hit: 712 case True{}: 713 text 714 case False{}: 715 rest(Unit{}) 716 717 # the phrase a list gives a code, "" when it gives none 718 def reason.in(ps: List<&2, Phrase>, +code: U32) -> String: 719 match ps: 720 case []: 721 "" 722 case P{c, text} <> t: 723 reason.pick(text, U32.is_eq(code, c), _u => reason.in(t, code)) 724 725 # the reason-phrase for a status code (RFC 9112 §4); "" for one not listed 726 def reason(+code: U32) -> String: 727 reason.in(reasons(), code) 728 729 # status-line + headers + body (RFC 9112 §4, §5). Connection: close ends the 730 # exchange after one response. 731 def respond(+status: U32, headers: List<&2, Header>, +body: String) -> String: 732 +n = utf8.len(body) 733 "HTTP/1.1 " ++ U32.show(status) ++ " " ++ reason(status) ++ "\r\n" 734 ++ "Connection: close\r\n" 735 ++ headers.lines(headers) 736 ++ clen.line(n, Nat.is_eq(n, 0n)) 737 ++ "\r\n" 738 ++ body 739 740 # 204 and 304 are terminated by the header section (RFC 9110 §15.3.5, §15.4.5) 741 def status.nocontent(+code: U32) -> Bool: 742 Bool.or(U32.is_eq(code, 204), U32.is_eq(code, 304)) 743 744 # drop a 204/304 body; any other status keeps it 745 def respond.of.body(+status: U32, headers: List<&2, Header>, body: String, 746 drop: Bool) -> String: 747 match drop: 748 case True{}: 749 respond(status, headers, "") 750 case False{}: 751 respond(status, headers, body) 752 753 # format a structured Reply as a response message 754 def respond.of(r: Reply) -> String: 755 match r: 756 case Torn{why}: 757 respond(500, [], why) 758 case Reply{+status, headers, body}: 759 respond.of.body(status, headers, body, status.nocontent(status)) 760 761 # HEAD carries no message body; any other method keeps the body (RFC 9110 §9.3.2) 762 def reply.for.pick(reply: Reply, head: Bool) -> Reply: 763 match reply head: 764 case Torn{why} _: 765 Torn{why} 766 case Reply{status, headers, body} False{}: 767 Reply{status, headers, body} 768 case Reply{status, headers, body} True{}: 769 Reply{status, headers, ""} 770 771 # drop a HEAD response body before it is written 772 def reply.for(method: String, reply: Reply) -> Reply: 773 reply.for.pick(reply, String.eq(method, "HEAD")) 774 775 # the method token, or "" when the request did not parse 776 def method.of(req: Request) -> String: 777 match req: 778 case Bad{why}: 779 "" 780 case Request{method, target, headers, body}: 781 method 782 783 # request body against Content-Length 784 def ask.short(method: String, target: String, headers: List<&2, Header>, 785 n: Nat, body: String, short: Bool) -> Request: 786 match short: 787 case True{}: 788 Bad{"the request body stopped before its Content-Length"} 789 case False{}: 790 Request{method, target, headers, utf8.take(body, n)} 791 792 # a request body framed by Content-Length (RFC 9110 §8.6 / RFC 9112 §6.3) 793 def ask.clen(method: String, target: String, headers: List<&2, Header>, 794 +n: Nat, +body: String) -> Request: 795 ask.short(method, target, headers, n, body, Nat.is_lt(utf8.len(body), n)) 796 797 # Content-Length when present; else the rest of the connection is the body 798 def ask.len(method: String, target: String, headers: List<&2, Header>, 799 m: Maybe<&2, Nat>, body: String) -> Request: 800 match m: 801 case None{}: 802 Request{method, target, headers, body} 803 case Some{n}: 804 ask.clen(method, target, headers, n, body) 805 806 # a chunked request body, or why the chunk framing was rejected 807 def ask.chunked(method: String, target: String, headers: List<&2, Header>, 808 body: String, bad: Maybe<&2, String>) -> Request: 809 match bad: 810 case None{}: 811 Request{method, target, headers, dechunk(body)} 812 case Some{why}: 813 Bad{why} 814 815 # scan chunk sizes, then decode when they are hex and closed by 0 816 def ask.chunks(method: String, target: String, headers: List<&2, Header>, 817 +body: String) -> Request: 818 ask.chunked(method, target, headers, body, 819 chunks.scan(String.length(body), divide(body, "\r\n"))) 820 821 # Transfer-Encoding together with Content-Length is a bad request 822 def ask.te.clash(method: String, target: String, headers: List<&2, Header>, 823 body: String, present: Bool) -> Request: 824 match present: 825 case True{}: 826 Bad{"Content-Length and Transfer-Encoding conflict"} 827 case False{}: 828 ask.chunks(method, target, headers, body) 829 830 # chunked framing, or Content-Length, or the rest of the connection 831 def ask.te(method: String, target: String, headers: List<&2, Header>, 832 +lens: List<&2, String>, +body: String, chunked: Bool) -> Request: 833 match chunked: 834 case False{}: 835 ask.len(method, target, headers, digits.read(first(lens)), body) 836 case True{}: 837 ask.te.clash(method, target, headers, body, clen.any(lens)) 838 839 # disagreeing Content-Length values are bad before framing 840 def ask.agree(method: String, target: String, headers: List<&2, Header>, 841 te: String, +lens: List<&2, String>, body: String, ok: Bool) -> Request: 842 match ok: 843 case False{}: 844 Bad{"Content-Length values disagree"} 845 case True{}: 846 ask.te(method, target, headers, lens, body, 847 String.contains(String.to_lower(te), "chunked")) 848 849 # the headers that decide request framing (RFC 9112 §6.3) 850 def ask.frame(method: String, target: String, headers: List<&2, Header>, 851 te: String, +lens: List<&2, String>, body: String) -> Request: 852 ask.agree(method, target, headers, te, lens, body, clen.agree(lens)) 853 854 # origin-form, or a bad request when the target is not an absolute-path 855 def ask.origin(method: String, target: String, +ls: List<&2, String>, 856 body: String, ok: Bool) -> Request: 857 match ok: 858 case False{}: 859 Bad{"the request-target is not in origin-form"} 860 case True{}: 861 +hs = head.list(ls) 862 ask.frame(method, target, hs, head.go(ls, "transfer-encoding"), 863 head.values(ls, "content-length"), body) 864 865 # request-line: method SP request-target SP HTTP-version (RFC 9112 §3) 866 def ask.line(+method: String, +target: String, +ls: List<&2, String>, 867 body: String) -> Request: 868 ask.origin(method, target, ls, body, 869 target.form(method, target, target.origin(target))) 870 871 # three fields of the request-line, or torn 872 def ask.parts(ps: List<&2, String>, +ls: List<&2, String>, body: String) 873 -> Request: 874 match ps: 875 case []: 876 Bad{"the request has no request line"} 877 case m <> rest: 878 match rest: 879 case []: 880 Bad{"the request line has no target"} 881 case t <> _ver: 882 ask.line(m, t, ls, body) 883 884 # the head's lines, with the request-line read off the first 885 def ask.head(+ls: List<&2, String>, body: String) -> Request: 886 match ls: 887 case []: 888 Bad{"the request has no request line"} 889 case _: 890 ask.parts(String.split(first(ls), ' '), ls, body) 891 892 # a request divided into its head and everything after the blank line 893 def ask.cut(c: Cut) -> Request: 894 match c: 895 case NoCut{}: 896 Bad{"the request head has no blank line after it"} 897 case Cut{before, after}: 898 ask.head(String.lines(before), after) 899 900 # the method, target, headers, and body of a raw request 901 def ask(raw: String) -> Request: 902 ask.cut(divide(raw, "\r\n\r\n")) 903 904 # a parsed request on one line, for a test to read 905 def ask.show(r: Request) -> String: 906 match r: 907 case Bad{why}: 908 "bad " ++ why 909 case Request{method, target, headers, body}: 910 method ++ " " ++ target ++ " " ++ body 911 912 # --- when a response has all arrived (RFC 9112 §6.3) --- 913 914 # how a response's body is framed 915 type Frame is Data: 916 Bare{} 917 Sized{n: Nat} 918 Chunked{} 919 Closed{} 920 921 # 204 and 304 carry no body; a status line that did not parse is framed by 922 # its headers 923 def status.bare(m: Maybe<&2, U32>) -> Bool: 924 match m: 925 case None{}: 926 False{} 927 case Some{n}: 928 status.nocontent(n) 929 930 # a Content-Length that reads as a number, or the close when none does 931 def frame.sized(m: Maybe<&2, Nat>) -> Frame: 932 match m: 933 case None{}: 934 Closed{} 935 case Some{n}: 936 Sized{n} 937 938 # Content-Length values that agree frame the body; any others leave the close 939 def frame.agree(+lens: List<&2, String>, ok: Bool) -> Frame: 940 match ok: 941 case False{}: 942 Closed{} 943 case True{}: 944 frame.sized(digits.read(first(lens))) 945 946 # chunked framing wins over Content-Length (RFC 9112 §6.3 item 4) 947 def frame.te(+lens: List<&2, String>, chunked: Bool) -> Frame: 948 match chunked: 949 case True{}: 950 Chunked{} 951 case False{}: 952 frame.agree(lens, clen.agree(lens)) 953 954 # the framing of a response: none when bare (a reply to HEAD, a 204 or a 304), 955 # else Transfer-Encoding chunked, else Content-Length, else the close 956 def frame(bare: Bool, te: String, +lens: List<&2, String>) -> Frame: 957 match bare: 958 case True{}: 959 Bare{} 960 case False{}: 961 frame.te(lens, String.contains(String.to_lower(te), "chunked")) 962 963 # a zero chunk's trailer section has ended: at once, or after its fields 964 def chunks.trailer(+after: String) -> Bool: 965 Bool.or(String.starts_with(after, "\r\n"), String.contains(after, "\r\n\r\n")) 966 967 # a chunk that has all arrived: on to the next chunk header, else not yet 968 def chunks.ended.data(+after: String, +n: Nat, ready: Bool, 969 rest: Cut -> Bool) -> Bool: 970 match ready: 971 case False{}: 972 False{} 973 case True{}: 974 rest(divide(utf8.drop(after, Nat.add(n, 2n)), "\r\n")) 975 976 # a chunk of size n: the last one when n is 0 977 def chunks.ended.size(+after: String, +n: Nat, zero: Bool, 978 rest: Cut -> Bool) -> Bool: 979 match zero: 980 case True{}: 981 chunks.trailer(after) 982 case False{}: 983 chunks.ended.data(after, n, chunks.ready(after, n), rest) 984 985 # a chunk header: a size that is not hex ends the read (the parse rejects it) 986 def chunks.ended.hex(+before: String, +after: String, ok: Bool, 987 rest: Cut -> Bool) -> Bool: 988 match ok: 989 case False{}: 990 True{} 991 case True{}: 992 +n = hexlen(before) 993 chunks.ended.size(after, n, Nat.is_eq(n, 0n), rest) 994 995 # a chunk header that has arrived, or not yet 996 def chunks.ended.at(c: Cut, rest: Cut -> Bool) -> Bool: 997 match c: 998 case NoCut{}: 999 False{} 1000 case Cut{+before, +after}: 1001 chunks.ended.hex(before, after, hex.well(chunks.token(before)), rest) 1002 1003 # whether a chunked body has reached the end of its last chunk 1004 def chunks.ended(fuel: Nat, c: Cut) -> Bool: 1005 match fuel: 1006 case 0n: 1007 False{} 1008 case 1n+f: 1009 chunks.ended.at(c, cut => chunks.ended(f, cut)) 1010 1011 # whether a body has all arrived under its framing 1012 def whole.of(f: Frame, +body: String) -> Bool: 1013 match f: 1014 case Bare{}: 1015 True{} 1016 case Sized{n}: 1017 Bool.not(Nat.is_lt(utf8.len(body), n)) 1018 case Chunked{}: 1019 chunks.ended(String.length(body), divide(body, "\r\n")) 1020 case Closed{}: 1021 False{} 1022 1023 # a response whose head has ended, or not yet 1024 def whole.cut(asked: Bool, c: Cut) -> Bool: 1025 match c: 1026 case NoCut{}: 1027 False{} 1028 case Cut{before, after}: 1029 +ls = String.lines(before) 1030 whole.of(frame(Bool.or(asked, status.bare(status.of(ls))), 1031 head.go(ls, "transfer-encoding"), head.values(ls, "content-length")), 1032 after) 1033 1034 # whether the text received so far is a whole response to a request with 1035 # this method (RFC 9112 §6.3); a response framed by the close never is 1036 def whole(+method: String, raw: String) -> Bool: 1037 whole.cut(String.eq(method, "HEAD"), divide(raw, "\r\n\r\n"))