tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

1694 lignes · 49863 octetsBrut · Historique
1/// A small HTTP/1.1 server (native programs only).
2///
3/// pub fn main() -> () / <io, proc> {
4/// match http.listen("0.0.0.0", 8080) {
5/// Ok(server) -> http.serve(server, fn(req) {
6/// http.html(<h1>{"Hello from " <> req.path}</h1>)
7/// }),
8/// Error(e) -> io.eprintln(e),
9/// }
10/// }
11///
12/// Each connection is handled by an actor of its own, which serves its
13/// requests one after another (keep-alive; ADR 0012):
14/// - an HTTP/1.1 connection stays open unless the request or the response
15/// has `Connection: close`; an HTTP/1.0 one only if the request has
16/// `Connection: keep-alive`;
17/// - a connection that waits longer than the idle timeout for a request
18/// to start, or for more of a body, is closed; so is one whose request
19/// head, once begun, takes longer than the head timeout to arrive whole
20/// (a client that trickles it), and one whose response takes longer
21/// than the write timeout to send (a client that stops reading); the
22/// handler is not timed;
23/// - at most `max_open` connections are open at once. At the limit, the
24/// next client is accepted and held while the oldest connection is
25/// asked to close: at once if it waits for a request, else after its
26/// current response (`Connection: close`). So kept-alive clients cannot
27/// starve waiting ones (issue #304), and the next client gets in within
28/// about one response time. A streamed response is not cut: its
29/// connection closes when the stream ends;
30/// - a connection serves at most `max_requests` requests: the last one is
31/// answered with `Connection: close`, and the client reconnects;
32/// - request bodies are read whole, sized by `Content-Length` or chunked
33/// (`Transfer-Encoding: chunked`), up to a size limit (413 beyond it),
34/// which can be larger under some path prefixes (`large_bodies`); a
35/// malformed request gets an error response, and the connection is
36/// closed;
37/// - the server sets `Content-Length` and `Connection` on responses, except
38/// that final 204 and 304 responses have no content length or body;
39/// - a response can be **streamed** (ADR 0053): the head goes out with
40/// `Transfer-Encoding: chunked`, the handler's stream fn writes chunks
41/// (each flushed, each write timed per chunk; the stream between chunks
42/// is not timed), and keep-alive continues after the final chunk.
43/// Server-Sent Events are a streamed response that stays open. A response
44/// with final status 204 or 304 sends no framing, chunks or final chunk, and
45/// does not call the stream fn.
46///
47/// Request heads and chunk sizes are parsed by httparse (picohttpparser's
48/// design) in the runtime.
49
50import std/bytes.{type Builder}
51import std/dict.{type Dict}
52import std/ffi.{type Resource}
53import std/file.{type fs}
54import std/html.{type Html}
55import std/int
56import std/io
57import std/list
58import std/net.
59{type SocketAddress, type TcpListener, type TcpStream, SocketAddress}
60import std/option
61import std/process.
62{type ExitReason, type Pid, type Subject, type proc, Crashed, Down}
63import std/random.{type random}
64import std/result
65import std/string
66import std/time.{type clock}
67
68pub type Request
69{ Request(
70 method: String
71 , path: String
72 , headers: List<(String, String)>
73 , body: Bytes
74 )
75}
76
77pub type Response
78{ Response(status: Int, headers: List<(String, String)>, body: Body) }
79
80/// What a response's body is (ADR 0053).
81pub type Body
82{ /// The whole body, in hand.
83 Whole(Bytes)
84 /// Written chunk by chunk: the server sends the head with
85 /// `Transfer-Encoding: chunked`, then calls `write` with a `Writer`
86 /// and sends the final chunk when it returns. Between chunks the
87 /// connection is not timed; each chunk's write is, per chunk, by the
88 /// write timeout. A 204 or 304 response skips `write` and sends neither
89 /// framing nor a final chunk. A HEAD request for any other status
90 /// sends the head only: `write` runs with a writer whose every write fails,
91 /// so it stops, and whatever cleanup it does on a failed write runs (#363).
92 /// If `write` unwinds, the connection dies without the final
93 /// chunk: the client sees a truncated stream, the only honest end
94 /// once the status line is sent.
95, Streamed(write: fn(Writer) -> () / <io, proc, clock, random, fs, ffi>)
96}
97
98/// What a streamed response writes with (ADR 0053): the connection,
99/// memory when the body is read in hand (`collect_body`), or nothing, for
100/// a HEAD request, whose writes all fail.
101pub opaque type Writer
102{ Socket(conn: Resource<TcpStream>, activity: Subject<Activity>)
103, Memory(chunks: Subject<Bytes>)
104, Headless
105}
106
107/// Write one chunk, flushed (one frame, one socket write). `Error` says
108/// the client is gone: stop writing. An empty chunk writes nothing: its
109/// frame would be the chunked encoding's last one, ending the body.
110pub fn write_chunk :: w: Writer chunk: Bytes -> Result<(), String> / <io, proc>
111{
112 match w
113 { _ if bytes.length chunk == 0 -> Ok(())
114 , Socket(conn, activity) ->
115 {
116 process.send activity Writing
117 match net.write conn (frame chunk)
118 { Ok(()) ->
119 {
120 process.send activity Streaming
121 Ok(())
122 }
123 , Error(e) -> Error(e)
124 }
125 }
126 , Memory(chunks) ->
127 {
128 process.send chunks chunk
129 Ok(())
130 }
131 , Headless -> Error("a HEAD request has no body")
132 }
133}
134
135/// Write one chunk of text, flushed.
136pub fn write_string :: w: Writer text: String -> Result<(), String> / <io, proc>
137{
138 write_chunk w (bytes.from_string text)
139}
140
141/// A chunk's frame: its length in hex, CRLF, the data, CRLF.
142fn frame :: chunk: Bytes -> Bytes
143{
144 let head = to_hex (bytes.length chunk) <> "\r\n"
145 bytes.concat_all [bytes.from_string head, chunk, bytes.from_string "\r\n"]
146}
147
148fn to_hex :: n: Int -> String
149{
150 if n <= 0
151 {
152 "0"
153 }
154 else
155 {
156 hex_up n ""
157 }
158}
159
160fn hex_up :: n: Int acc: String -> String
161{
162 if n == 0
163 {
164 acc
165 }
166 else
167 {
168 hex_up (int.shift_right n 4) (hex_digit (int.and n 15) <> acc)
169 }
170}
171
172fn hex_digit :: d: Int -> String
173{
174 match d
175 { 0 -> "0"
176 , 1 -> "1"
177 , 2 -> "2"
178 , 3 -> "3"
179 , 4 -> "4"
180 , 5 -> "5"
181 , 6 -> "6"
182 , 7 -> "7"
183 , 8 -> "8"
184 , 9 -> "9"
185 , 10 -> "a"
186 , 11 -> "b"
187 , 12 -> "c"
188 , 13 -> "d"
189 , 14 -> "e"
190 , _ -> "f"
191 }
192}
193
194/// Change the defaults with a record update:
195/// `Settings(..http.defaults(), idle_timeout: 1000)`.
196pub type Settings
197{ /// - `connections`: serve this many connections, then return (all of
198 /// them if negative);
199 /// - `idle_timeout`: close a connection that waits this many
200 /// milliseconds for a request to start, or for more of a body (never
201 /// if negative);
202 /// - `write_timeout`: close a connection whose response takes longer
203 /// than this many milliseconds to send (never if negative);
204 /// - `max_body`: answer 413 to a request whose body is larger than this
205 /// many bytes, and close the connection (no limit if negative);
206 /// - `large_bodies`: other body limits for some paths, as `(prefix,
207 /// limit)`: the first prefix that matches the request's path on whole
208 /// segments (`/uploads` matches `/uploads` and `/uploads/a`, not
209 /// `/uploadsx`) sets its limit instead of `max_body` (see
210 /// `body_limit`). The 413 still comes before any byte of the body is
211 /// read;
212 /// - `max_open`: keep at most this many connections open at once (no
213 /// limit if negative). At the limit, the next client is held (one
214 /// more open socket) and the oldest connection asked to close, at once
215 /// if it waits for a request, else after its current response;
216 /// - `max_requests`: answer this many requests on one connection, the
217 /// last with `Connection: close` (no limit if negative);
218 /// - `head_timeout`: close a connection whose request head, once begun,
219 /// takes longer than this many milliseconds to arrive whole (never if
220 /// negative);
221 /// - `drain_timeout`: once `serve_until` is told to stop, give the
222 /// requests in flight this many milliseconds to finish, then close
223 /// their connections (no limit if negative).
224 Settings(
225 connections: Int
226 , idle_timeout: Int
227 , write_timeout: Int
228 , max_body: Int
229 , large_bodies: List<(String, Int)>
230 , max_open: Int
231 , head_timeout: Int
232 , max_requests: Int
233 , drain_timeout: Int
234 )
235}
236
237/// Every connection, at most 512 at once (under the usual limit of 1024
238/// open files, so the limit is reached before `accept` fails); closed
239/// after 5 idle seconds, when a request head takes over 10 seconds to
240/// arrive, when a response takes over 30 seconds to send, or after 1,000
241/// requests (nginx's `keepalive_requests`); bodies up to 1 MiB on every
242/// path; 10 seconds to drain when stopped.
243pub fn defaults :: -> Settings
244{
245 Settings( connections: -1
246 , idle_timeout: 5000
247 , write_timeout: 30000
248 , max_body: 1048576
249 , large_bodies: []
250 , max_open: 512
251 , head_timeout: 10000
252 , max_requests: 1000
253 , drain_timeout: 10000
254 )
255}
256
257/// The client's address (issue #308): the other end of the connection the
258/// request came on, as the server accepted it. Behind a proxy, that is
259/// the proxy: see `client_address`. `None` for a request built by hand
260/// (in tests).
261///
262/// The server puts it among the request's headers as the pseudo-header
263/// `:peer` (`"127.0.0.1:52144"`, `"[::1]:52144"`), which no client can
264/// send: a header name cannot contain `:`. It is found anywhere in the
265/// list (issue #313); a server-built request always has it first.
266/// `wire_headers` leaves it out.
267pub fn peer :: req: Request -> Option<SocketAddress>
268{
269 option.then (find_header req.headers ":peer") parse_address
270}
271
272/// `req` as if it arrived from `address` (for tests): the `:peer`
273/// pseudo-header first, where the server puts it.
274pub fn with_peer :: req: Request address: SocketAddress -> Request
275{
276 Request(..req, headers: [(":peer", address_text address), ..req.headers])
277}
278
279/// `host:port`, or `[host]:port` for an IPv6 host.
280fn parse_address :: value: String -> Option<SocketAddress>
281{
282 let ( host
283 , port
284 ) = if string.starts_with value "["
285 {
286 match string.split (string.slice value 1 (string.length value)) "]:"
287 { [host, port] -> (host, port), _ -> ("", "") }
288 }
289 else
290 {
291 match string.split value ":" { [host, port] -> (host, port), _ -> ("", "") }
292 }
293 match string.to_int port
294 { Ok(port) -> if host == "" { None } else { Some(SocketAddress(host, port)) }
295 , Error(_) -> None
296 }
297}
298
299/// How the server writes a peer in `:peer`.
300fn address_text :: address: SocketAddress -> String
301{
302 let host = if string.contains address.host ":"
303 {
304 "[" <> address.host <> "]"
305 }
306 else
307 {
308 address.host
309 }
310 host <> ":" <> show address.port
311}
312
313/// The headers the client sent, without the server's pseudo-headers
314/// (`:peer`): what to forward or log.
315pub fn wire_headers :: req: Request -> List<(String, String)>
316{
317 use h <- list.filter req.headers
318 !string.starts_with h.0 ":"
319}
320
321/// The client's IP address, through the proxies in `trusted` (exact
322/// addresses, as text). When the peer is not trusted, it is the client:
323/// its `X-Forwarded-For`, which anyone can send, is ignored. When it is,
324/// the client is the right-most `X-Forwarded-For` entry that is not
325/// trusted (each proxy appends the address it got the request from), or
326/// the left-most one if all are; with no entries, the peer itself.
327/// `None` without a peer (a request built by hand).
328///
329/// // Behind one nginx on 10.0.0.2:
330/// http.client_address(req, ["10.0.0.2"])
331pub fn client_address :: req: Request trusted: List<String> -> Option<String>
332{
333 match peer req
334 { None -> None
335 , Some(p) -> if !is_trusted trusted p.host
336 {
337 Some(p.host)
338 }
339 else
340 {
341 Some(untrusted_hop (list.reverse (forwarded_for req)) trusted p.host)
342 }
343 }
344}
345
346/// Every `X-Forwarded-For` entry, in order, across repeated headers.
347fn forwarded_for :: req: Request -> List<String>
348{
349 use h <- list.flat_map req.headers
350 if string.eq_ignore_ascii_case h.0 "x-forwarded-for"
351 {
352 string.split h.1 ","
353 |> list.map string.trim
354 |> list.filter fn entry { entry != "" }
355 }
356 else
357 {
358 []
359 }
360}
361
362/// The first of `hops` (right-most first) not in `trusted`, else the
363/// last one seen (`seen`: the peer, before any).
364fn untrusted_hop ::
365 hops: List<String>
366 trusted: List<String>
367 seen: String
368 -> String
369{
370 match hops
371 { [] -> seen
372 , [ hop
373 , ..rest
374 ] -> if is_trusted trusted hop
375 {
376 untrusted_hop rest trusted hop
377 }
378 else
379 {
380 hop
381 }
382 }
383}
384
385fn is_trusted :: trusted: List<String> address: String -> Bool
386{
387 list.any trusted fn t { t == address }
388}
389
390/// The value of header `name` (case-insensitive), if present.
391pub fn header :: req: Request name: String -> Option<String>
392{
393 find_header req.headers name
394}
395
396fn find_header :: headers name
397{
398 match headers
399 { [] -> None
400 , [(k, v), ..rest] -> if string.eq_ignore_ascii_case k name
401 {
402 Some(v)
403 }
404 else
405 {
406 find_header rest name
407 }
408 }
409}
410
411/// The request body as text, if it is valid UTF-8.
412pub fn body_text :: req: Request -> Result<String, String>
413{
414 bytes.to_string req.body
415}
416
417/// The fields of a form-encoded request body (see `form`).
418pub fn form_body :: req: Request -> List<(String, String)>
419{
420 form (bytes.to_string_lossy req.body)
421}
422
423/// A response with `body` of type `content_type`.
424pub fn response :: status: Int content_type: String body: Bytes -> Response
425{
426 Response(status, [("Content-Type", content_type)], Whole(body))
427}
428
429/// A 200 response written chunk by chunk (ADR 0053): the head goes out
430/// first (`Transfer-Encoding: chunked`), then `write` runs with a
431/// `Writer`; each `write_chunk`/`write_string` flushes. Between chunks
432/// the connection is not timed; each write is, per chunk. Keep-alive
433/// continues after the final chunk.
434///
435/// http.stream("text/html; charset=utf-8", fn(w) {
436/// let _ = http.write_string(w, html.render(shell_top))
437/// // each component, as it finishes
438/// let _ = http.write_string(w, "</body></html>")
439/// })
440pub fn stream ::
441 content_type: String
442 write: fn(Writer) -> () / <io, proc, clock, random, fs, ffi>
443 -> Response
444{
445 Response(200, [("Content-Type", content_type)], Streamed(write))
446}
447
448/// The body a response holds, if it is a whole one (a streamed response's
449/// body is written, not held).
450pub fn whole_body :: resp: Response -> Option<Bytes>
451{
452 match resp.body { Whole(body) -> Some(body), Streamed(_) -> None }
453}
454
455/// A response's body in hand: a streamed one is written into memory,
456/// chunk by chunk, as the server would send it. For tests and tools: the
457/// whole body is held at once.
458pub fn collect_body ::
459 resp: Response
460 -> Bytes / <io, proc, clock, random, fs, ffi>
461{
462 match resp.body
463 { Whole(body) -> body
464 , Streamed(write) ->
465 {
466 let chunks = process.subject ()
467 write Memory(chunks)
468 bytes.concat_all (written chunks [])
469 }
470 }
471}
472
473/// The chunks a memory writer was given, in order.
474fn written :: chunks: Subject<Bytes> held: List<Bytes> -> List<Bytes> / <proc>
475{
476 match process.receive chunks 0
477 { Some(chunk) -> written chunks [chunk, ..held], None -> list.reverse held }
478}
479
480/// A 200 response with a rendered page.
481pub fn html :: page: Html -> Response
482{
483 response 200 "text/html; charset=utf-8" (bytes.from_string (html.render page))
484}
485
486/// A plain-text response.
487pub fn text :: status: Int body: String -> Response
488{
489 response status "text/plain; charset=utf-8" (bytes.from_string body)
490}
491
492pub fn not_found :: -> Response
493{
494 text 404 "not found"
495}
496
497/// `resp` with the header `name: value` added, after the ones it has
498/// (headers can repeat: each `Set-Cookie` is its own header).
499pub fn with_header :: resp: Response name: String value: String -> Response
500{
501 Response(..resp, headers: list.append resp.headers [(name, value)])
502}
503
504/// Listen for HTTP connections.
505pub fn listen ::
506 host: String
507 port: Int
508 -> Result<Resource<TcpListener>, String> / <io>
509{
510 net.listen host port
511}
512
513/// Serve forever with the default settings.
514pub fn serve ::
515 server: Resource<TcpListener>
516 handler: send fn(Request) -> Response / <io, proc, clock, random, fs, ffi>
517 -> () / <io, proc>
518{
519 serve_with server (defaults ()) handler
520}
521
522/// Serve with `settings`: one actor per connection. When this returns,
523/// the last connections' actors may still be running.
524pub fn serve_with ::
525 server: Resource<TcpListener>
526 settings: Settings
527 handler: send fn(Request) -> Response / <io, proc, clock, random, fs, ffi>
528 -> () / <io, proc>
529{
530 accept_all
531 server
532 settings
533 handler
534 (process.subject ())
535 Open(0, dict.empty (), 0, False)
536 10
537}
538
539/// Serve with `settings` until a message arrives on `stop`, then stop
540/// gracefully (ADR 0060): new clients are refused at once; idle
541/// connections are closed, and busy ones after their current response
542/// (with `Connection: close`); after `settings.drain_timeout`, the
543/// connections still open are closed. Returns once every connection is.
544///
545/// `stop` is one of the calling actor's subjects, and any message on it
546/// stops the server: `os.signals([Term])` for a program that stops on
547/// SIGTERM, `process.exits()` for a `main` that traps exits under
548/// `[application]` (ADR 0060), or a `process.subject()` another actor
549/// sends on.
550pub fn serve_until ::
551 server: Resource<TcpListener>
552 settings: Settings
553 handler: send fn(Request) -> Response / <io, proc, clock, random, fs, ffi>
554 stop: Subject<m>
555 -> () / <io, proc>
556{
557 let ready = process.subject ()
558 let (_, done) =
559 process.spawn_monitor
560 fn
561 {
562 let events = process.subject ()
563 process.send ready events
564 accept_all
565 server
566 settings
567 handler
568 events
569 Open(0, dict.empty (), 0, False)
570 10
571 }
572 let events = process.receive_forever ready
573 let stopped =
574 process.new_selector ()
575 |> process.selecting stop fn _ { True }
576 |> process.selecting done fn _ { False }
577 if process.select_forever stopped
578 {
579 // Wakes the acceptor, parked in `accept`, which then drains.
580 process.send events Stop
581 net.close_listener server
582 let Down(_, reason) = process.receive_forever done
583 stopped_with reason
584 }
585 else
586 {
587 // `settings.connections` were served.
588 ()
589 }
590}
591
592/// The acceptor's end: a crash is `serve_until`'s.
593fn stopped_with :: reason: ExitReason -> ()
594{
595 match reason
596 { Crashed(message) -> panic ("http: the acceptor crashed: " <> message)
597 , _ -> ()
598 }
599}
600
601/// Accept connections while `settings.connections` lasts. Their
602/// watchdogs report on `events` when they open and end. After a failed
603/// `accept` (out of file descriptors, say), wait `pause` milliseconds,
604/// doubling up to a second while it keeps failing (ADR 0012, Revision 2).
605fn accept_all ::
606 server
607 settings: Settings
608 handler
609 events: Subject<Event>
610 open: Open
611 pause: Int
612 -> () / <io, proc>
613{
614 if settings.connections != 0
615 {
616 let next = Settings(..settings, connections: settings.connections - 1)
617 match net.accept server
618 { Ok(conn) ->
619 {
620 // At `max_open`, this client is held until there is room (or the
621 // server stops: it is served, then drained).
622 let open =
623 make_room
624 events
625 (take_events events open False)
626 settings.max_open
627 False
628 let id = open.next
629 let _ =
630 process.spawn fn { handle_connection conn id settings handler events }
631 accept_all
632 server
633 next
634 handler
635 events
636 Open(..open, count: open.count + 1, next: id + 1)
637 10
638 }
639 , Error(e) ->
640 {
641 let open = take_events events open False
642 if open.stopping
643 {
644 drain events open settings.drain_timeout
645 }
646 else
647 {
648 io.eprintln ("http: accept failed: " <> e)
649 process.sleep pause
650 accept_all
651 server
652 next
653 handler
654 events
655 open
656 if pause >= 500 { 1000 } else { pause * 2 }
657 }
658 }
659 }
660 }
661 else
662 {
663 ()
664 }
665}
666
667/// Stop serving (`serve_until`): ask every open connection to close
668/// (idle ones at once, busy ones after their response), and wait until
669/// they have, for `timeout` milliseconds at most; then close the rest.
670fn drain :: events: Subject<Event> open: Open timeout: Int -> () / <proc>
671{
672 let asked =
673 list.map (dict.to_list open.closable) fn entry { ask_to_close entry.1 }
674 let timer = if timeout >= 0
675 {
676 Some( process.spawn
677 fn
678 {
679 process.sleep timeout
680 process.send events DrainOver
681 }
682 )
683 }
684 else
685 {
686 None
687 }
688 wait_drained events open.count asked
689 match timer { Some(pid) -> process.kill pid, None -> () }
690}
691
692/// Ask a connection to close: its actor and its watchdog (see `Opened`).
693/// Returns its actor's subject.
694fn ask_to_close :: subjects: (Subject<()>, Subject<()>) -> Subject<()> / <proc>
695{
696 let (actor, watchdog) = subjects
697 process.send actor ()
698 process.send watchdog ()
699 actor
700}
701
702/// Wait until `count` connections have ended, asking those that open
703/// meanwhile (accepted just before the stop) to close too; at
704/// `DrainOver`, stop the actors of those asked.
705fn wait_drained ::
706 events: Subject<Event>
707 count: Int
708 asked: List<Subject<()>>
709 -> () / <proc>
710{
711 if count > 0
712 {
713 match process.receive_forever events
714 { Ended(_) -> wait_drained events (count - 1) asked
715 , Opened(_, actor, watchdog) ->
716 wait_drained events count [ask_to_close (actor, watchdog), ..asked]
717 , DrainOver ->
718 list.each asked fn actor { process.kill (process.owner actor) }
719 , Stop -> wait_drained events count asked
720 }
721 }
722 else
723 {
724 ()
725 }
726}
727
728/// What a connection's watchdog tells the acceptor.
729type Event
730{ /// Connection `id` is open: a `()` on both subjects (its actor's, its
731 /// watchdog's) asks it to close.
732 Opened(id: Int, actor: Subject<()>, watchdog: Subject<()>)
733 /// Connection `id` ended.
734, Ended(id: Int)
735 /// `serve_until` was told to stop: drain once `accept` fails.
736, Stop
737 /// The drain timeout passed.
738, DrainOver
739}
740
741/// The acceptor's view: `count` connections open, those it may still ask
742/// to close by id (ids grow, so the least is the oldest), the next id,
743/// and whether `serve_until` was told to stop.
744type Open
745{ Open(
746 count: Int
747 , closable: Dict<Int, (Subject<()>, Subject<()>)>
748 , next: Int
749 , stopping: Bool
750 )
751}
752
753/// `open` after the events received so far; with `wait`, after waiting
754/// for one first.
755fn take_events :: events: Subject<Event> open: Open wait: Bool -> Open / <proc>
756{
757 match process.receive events if wait { -1 } else { 0 }
758 { Some(Opened(id, actor, watchdog)) ->
759 take_events
760 events
761 Open(..open, closable: dict.insert open.closable id (actor, watchdog))
762 False
763 , Some(Ended(id)) ->
764 take_events
765 events
766 Open( ..open
767 , count: open.count - 1
768 , closable: dict.remove open.closable id
769 )
770 False
771 , Some(Stop) -> take_events events Open(..open, stopping: True) False
772 , Some(DrainOver) -> take_events events open False
773 , None -> open
774 }
775}
776
777/// `open` once a connection more fits under `max_open`. While full, the
778/// oldest connection not asked yet is asked to close (once per held
779/// client, `asked`), and the acceptor waits for one to end: that one, or
780/// any other.
781fn make_room ::
782 events: Subject<Event>
783 open: Open
784 max_open: Int
785 asked: Bool
786 -> Open / <proc>
787{
788 if max_open < 0 || open.count < max_open || open.stopping
789 {
790 open
791 }
792 else
793 {
794 let (open, asked) = match (asked, dict.first open.closable)
795 { (False, Some((id, (actor, watchdog)))) ->
796 {
797 process.send actor ()
798 process.send watchdog ()
799 (Open(..open, closable: dict.remove open.closable id), True)
800 }
801 , _ -> (open, asked)
802 }
803 make_room events (take_events events open True) max_open asked
804 }
805}
806
807/// What a connection's watchdog learns.
808type Activity
809{ /// The connection's actor waits for a request to start: timed by
810 /// `idle_timeout`. Asked to close now, the connection closes at once.
811 Idle
812 /// It waits for more of a body: timed by `idle_timeout` from each read.
813, Reading
814 /// A request head has begun and is not whole yet: timed by
815 /// `head_timeout` from here, once, since nothing else is sent until the
816 /// head is read.
817, HeadStarted
818 /// It runs the handler: not timed.
819, Handling
820 /// It sends a response: timed.
821, Writing
822 /// A streamed response, between chunks: not timed (a stream may be
823 /// quiet arbitrarily long); each chunk's write is `Writing`.
824, Streaming
825 /// It stopped (also by crashing).
826, Stopped
827 /// The acceptor asks the connection to close (at `max_open`, for a
828 /// waiting client): the watchdog closes it if it is `Idle`; otherwise
829 /// its actor answers the current request with `Connection: close`.
830, Drain
831}
832
833fn handle_connection ::
834 conn: Resource<TcpStream>
835 id: Int
836 settings: Settings
837 handler: fn(Request) -> Response / <io, proc, clock, random, fs, ffi>
838 events: Subject<Event>
839 -> () / <io, proc, clock, random, fs, ffi>
840{
841 let me = process.self ()
842 let ready = process.subject ()
843 let drain = process.subject ()
844 let _ = process.spawn fn { watchdog conn me id drain settings ready events }
845 let activity = process.receive_forever ready
846 let peer = match net.peer conn
847 { Ok(address) -> [(":peer", address_text address)], Error(_) -> [] }
848 let serving = Serving(conn, peer, activity, drain, settings, handler)
849 serve_requests serving (bytes.empty ()) 0 0
850 net.close conn
851}
852
853/// Close the connection when it waits too long for a request, takes too
854/// long to send its head, or takes too long to send a response: its actor
855/// then reads the end of the stream, or fails to write, and stops. The
856/// watchdog monitors that actor, and stops with it, releasing its
857/// reference to the socket. It tells the acceptor that the connection
858/// opened, with how to ask it to close (`drain`, its actor's subject, and
859/// one of its own), and, once, that it ended (for `max_open`).
860fn watchdog ::
861 conn: Resource<TcpStream>
862 owner: Pid
863 id: Int
864 drain: Subject<()>
865 settings: Settings
866 ready: Subject<Subject<Activity>>
867 acceptor: Subject<Event>
868 -> () / <io, proc>
869{
870 let activity = process.subject ()
871 let asked = process.subject ()
872 let down = process.monitor owner
873 process.send ready activity
874 process.send acceptor Opened(id, drain, asked)
875 let events =
876 process.new_selector ()
877 |> process.selecting activity fn a { a }
878 |> process.selecting down fn _ { Stopped }
879 |> process.selecting asked fn _ { Drain }
880 watch conn settings events settings.idle_timeout True
881 process.send acceptor Ended(id)
882}
883
884/// `idle`: the actor waits for a request to start. (A `Drain` otherwise
885/// restarts the current timeout; it comes at most once.) Closing an idle
886/// connection races with a request just sent, as the idle timeout does:
887/// a client retries it on a new connection (RFC 9112, section 9.3.1).
888fn watch :: conn settings: Settings events timeout idle: Bool
889{
890 match process.select events timeout
891 { None -> net.close conn
892 , Some(Idle) -> watch conn settings events settings.idle_timeout True
893 , Some(Reading) -> watch conn settings events settings.idle_timeout False
894 , Some(HeadStarted) -> watch conn settings events settings.head_timeout False
895 , Some(Handling) -> watch conn settings events (-1) False
896 , Some(Writing) -> watch conn settings events settings.write_timeout False
897 , Some(Streaming) -> watch conn settings events (-1) False
898 , Some
899 ( Drain
900 ) -> if idle
901 {
902 net.close conn
903 }
904 else
905 {
906 watch conn settings events timeout False
907 }
908 , Some(Stopped) -> ()
909 }
910}
911
912/// Why no request was read.
913type Failure
914{ /// The connection closed or failed: nothing to answer.
915 Closed
916 /// A malformed request, answered with `status` before closing.
917, Bad(status: Int, message: String)
918}
919
920/// A request, whether the client keeps the connection open after it, and
921/// where the next request starts (offset `at` of `buffer`).
922type Incoming
923{ Incoming(request: Request, keep_alive: Bool, buffer: Bytes, at: Int) }
924
925/// Serve the requests in `buffer` (from offset `at`), then those that
926/// arrive, until either side closes the connection.
927/// A connection's actor: the socket, its watchdog's subject, its own
928/// subject on which the acceptor asks it to close, and how to serve.
929type Serving
930{ Serving(
931 conn: Resource<TcpStream>
932 // `[(":peer", address)]`, or none if it is not known: put first among
933 // every request's headers (`peer`).
934 , peer: List<(String, String)>
935 , activity: Subject<Activity>
936 , drain: Subject<()>
937 , settings: Settings
938 , handler: fn(Request) -> Response / <io, proc, clock, random, fs, ffi>
939 )
940}
941
942/// Serve requests from `buffer` at `at`, `served` of them so far. The
943/// connection is kept unless the request, the response, the acceptor
944/// (`drain`) or `max_requests` says otherwise.
945fn serve_requests ::
946 serving: Serving
947 buffer: Bytes
948 at: Int
949 served: Int
950 -> () / <io, proc, clock, random, fs, ffi>
951{
952 let conn = serving.conn
953 let activity = serving.activity
954 match read_request conn activity serving.settings buffer at
955 { Ok(Incoming(req, keep_alive, buffer, at)) ->
956 {
957 process.send activity Handling
958 let req = Request(..req, headers: list.append serving.peer req.headers)
959 // HEAD is GET without the body (RFC 9110 §9.3.2): the handler sees
960 // a GET, and the body is not sent (a stream fn is not called).
961 let with_body = req.method != "HEAD"
962 let req = if with_body { req } else { Request(..req, method: "GET") }
963 let handler = serving.handler
964 let resp = handler req
965 let served = served + 1
966 let closes =
967 find_header resp.headers "connection"
968 |> option.unwrap_or ""
969 |> has_token "close"
970 let max = serving.settings.max_requests
971 let drained = option.is_some (process.receive serving.drain 0)
972 let keep = keep_alive && !closes && !drained && (max < 0 || served < max)
973 let sent = if final_status_without_body resp.status
974 {
975 send_response
976 conn
977 activity
978 (bytes.from_string (head_bytes resp.status resp.headers keep ""))
979 }
980 else
981 {
982 match resp.body
983 { Whole(_) ->
984 send_response conn activity (serialize resp keep with_body)
985 , Streamed
986 ( write
987 ) -> if with_body
988 {
989 serve_streamed conn activity resp keep write
990 }
991 else
992 {
993 // HEAD: the head only. The stream fn still runs, and its first
994 // write fails, so what it started is stopped (#363).
995 let head =
996 send_response conn activity (serialize_stream_head resp keep)
997 write Headless
998 head
999 }
1000 }
1001 }
1002 match sent
1003 { Ok(_) -> if keep { serve_requests serving buffer at served } else { () }
1004 , Error(_) -> ()
1005 }
1006 }
1007 , Error(Closed) -> ()
1008 , Error(Bad(status, message)) ->
1009 {
1010 let _ =
1011 send_response conn activity (serialize (text status message) False True)
1012 ()
1013 }
1014 }
1015}
1016
1017/// A streamed response (ADR 0053): the head (chunked, no length), the
1018/// stream fn, the final chunk. Between chunks the connection is untimed;
1019/// each write is timed per chunk by the watchdog.
1020fn serve_streamed ::
1021 conn: Resource<TcpStream>
1022 activity: Subject<Activity>
1023 resp: Response
1024 keep: Bool
1025 write: fn(Writer) -> () / <io, proc, clock, random, fs, ffi>
1026 -> Result<(), String> / <io, proc, clock, random, fs, ffi>
1027{
1028 use () <-
1029 result.try (send_response conn activity (serialize_stream_head resp keep))
1030 process.send activity Streaming
1031 write Socket(conn, activity)
1032 process.send activity Writing
1033 net.write conn (bytes.from_string "0\r\n\r\n")
1034}
1035
1036/// Write a response (timed by the watchdog).
1037fn send_response ::
1038 conn: Resource<TcpStream>
1039 activity: Subject<Activity>
1040 data: Bytes
1041 -> Result<(), String> / <io, proc>
1042{
1043 process.send activity Writing
1044 net.write conn data
1045}
1046
1047/// The largest request head, in bytes (431 beyond it).
1048fn head_limit :: -> Int
1049{
1050 65536
1051}
1052
1053fn read_request ::
1054 conn
1055 activity
1056 settings: Settings
1057 buffer: Bytes
1058 at: Int
1059 -> Result<Incoming, Failure> / <io, proc>
1060{
1061 match parse_head buffer at
1062 { Partial -> if bytes.length buffer > at
1063 {
1064 // A head has begun: it must arrive whole within `head_timeout`.
1065 process.send activity HeadStarted
1066 let begun = bytes.slice buffer at (bytes.length buffer)
1067 read_head
1068 conn
1069 activity
1070 settings
1071 (bytes.append (bytes.builder ()) begun)
1072 (bytes.length begun)
1073 (last_bytes begun)
1074 }
1075 else
1076 {
1077 // Waiting for a request to start: `idle_timeout`, and the acceptor
1078 // may close the connection now (`Idle`).
1079 process.send activity Idle
1080 match read_raw conn
1081 { Ok(more) -> read_request conn activity settings more 0
1082 , Error(e) -> Error(e)
1083 }
1084 }
1085 , head -> request_of conn activity settings head buffer at
1086 }
1087}
1088
1089/// The request whose head, from offset `at` of `buffer`, is `head`.
1090fn request_of ::
1091 conn
1092 activity
1093 settings: Settings
1094 head: Head
1095 buffer: Bytes
1096 at: Int
1097 -> Result<Incoming, Failure> / <io, proc>
1098{
1099 match head
1100 { Complete
1101 ( method
1102 , path
1103 , version
1104 , headers
1105 , end
1106 , length
1107 ) -> if end - at > head_limit ()
1108 {
1109 Error(Bad(431, "request head too large"))
1110 }
1111 else
1112 {
1113 let max_body = body_limit settings path
1114 match read_body conn activity max_body headers length buffer end
1115 { Ok((body, buffer, at)) ->
1116 Ok( Incoming( Request(method, path, headers, body)
1117 , keeps_alive version headers
1118 , buffer
1119 , at
1120 )
1121 )
1122 , Error(e) -> Error(e)
1123 }
1124 }
1125 , Invalid(reason) -> Error(Bad(400, "bad request: " <> reason))
1126 // Its end was found, yet it is incomplete: blank lines before the
1127 // request line, which would otherwise restart `head_timeout`.
1128 , Partial -> Error(Bad(400, "bad request: an empty head"))
1129 }
1130}
1131
1132/// Read the rest of a head begun in `received` (`size` bytes, ending in
1133/// `tail`), not reported to the watchdog, which times it by
1134/// `head_timeout`. Each read is scanned once for the head's end, with
1135/// the 3 bytes before it; then the head is built and parsed once (ADR
1136/// 0012, Revision 2).
1137fn read_head ::
1138 conn
1139 activity
1140 settings: Settings
1141 received: Builder
1142 size: Int
1143 tail: Bytes
1144 -> Result<Incoming, Failure> / <io, proc>
1145{
1146 if size > head_limit ()
1147 {
1148 Error(Bad(431, "request head too large"))
1149 }
1150 else
1151 {
1152 match read_raw conn
1153 { Ok(more) ->
1154 {
1155 let window = bytes.concat tail more
1156 let received = bytes.append received more
1157 if parse_head_end window 0 >= 0
1158 {
1159 let buffer = bytes.build received
1160 request_of conn activity settings (parse_head buffer 0) buffer 0
1161 }
1162 else
1163 {
1164 read_head
1165 conn
1166 activity
1167 settings
1168 received
1169 (size + bytes.length more)
1170 (last_bytes window)
1171 }
1172 }
1173 , Error(e) -> Error(e)
1174 }
1175 }
1176}
1177
1178/// The last 3 bytes of `b` (all of them if fewer): an end of head may
1179/// straddle two reads.
1180fn last_bytes :: b: Bytes -> Bytes
1181{
1182 let n = bytes.length b
1183 bytes.slice b if n > 3 { n - 3 } else { 0 } n
1184}
1185
1186/// Whether the client wants the connection kept open after its request.
1187fn keeps_alive :: version: Int headers: List<(String, String)> -> Bool
1188{
1189 let connection = option.unwrap_or (find_header headers "connection") ""
1190 if version == 0
1191 {
1192 has_token connection "keep-alive"
1193 }
1194 else
1195 {
1196 !has_token connection "close"
1197 }
1198}
1199
1200/// Whether the comma-separated `value` lists `token` (lowercase).
1201fn has_token :: value: String token: String -> Bool
1202{
1203 list.any
1204 (string.split (string.to_lower value) ",")
1205 fn t { string.trim t == token }
1206}
1207
1208/// The body that starts at offset `at` of `buffer`, then where the next
1209/// request starts. A body over `max_body` bytes (if not negative) is not
1210/// read: it gets a 413, and the connection is closed.
1211fn read_body ::
1212 conn
1213 activity
1214 max_body: Int
1215 headers
1216 length: Int
1217 buffer: Bytes
1218 at: Int
1219 -> Result<(Bytes, Bytes, Int), Failure> / <io, proc>
1220{
1221 match find_header headers "transfer-encoding"
1222 { Some
1223 ( coding
1224 ) -> if length >= 0
1225 {
1226 // Two framings: reading the wrong one would desynchronize the
1227 // connection (request smuggling).
1228 Error(Bad(400, "bad request: both Content-Length and Transfer-Encoding"))
1229 }
1230 else if string.to_lower (string.trim coding) == "chunked"
1231 {
1232 continue_if_expected conn headers buffer at
1233 read_chunks conn activity max_body buffer at (bytes.builder ()) 0
1234 }
1235 else
1236 {
1237 Error(Bad(501, "unsupported Transfer-Encoding: " <> coding))
1238 }
1239 , None -> if too_large length max_body
1240 {
1241 // Before `100 Continue`: a waiting client does not send the body.
1242 Error(too_large_error ())
1243 }
1244 else if length > 0
1245 {
1246 continue_if_expected conn headers buffer at
1247 take conn activity buffer at length
1248 }
1249 else
1250 {
1251 Ok((bytes.empty (), buffer, at))
1252 }
1253 }
1254}
1255
1256/// The body limit for a request to `target` (a path, with or without its
1257/// query): the limit of the first of `settings.large_bodies` whose
1258/// prefix matches the path on whole segments, else `settings.max_body`.
1259/// The path is matched as the client wrote it, not decoded: a request
1260/// that spells a prefix another way (`/upl%6Fads`) gets `max_body`.
1261pub fn body_limit :: settings: Settings target: String -> Int
1262{
1263 let path = (target_split target).0
1264 match list.find settings.large_bodies fn entry { under path entry.0 }
1265 { Some((_, limit)) -> limit, None -> settings.max_body }
1266}
1267
1268/// Whether `path` is `prefix` or below it, on whole segments.
1269fn under :: path: String prefix: String -> Bool
1270{
1271 string.starts_with path prefix
1272 && ( string.ends_with prefix "/"
1273 || string.byte_length path == string.byte_length prefix
1274 || string.starts_with
1275 (string.slice path (string.length prefix) (string.length path))
1276 "/"
1277 )
1278}
1279
1280fn too_large :: size: Int max_body: Int -> Bool
1281{
1282 max_body >= 0 && size > max_body
1283}
1284
1285fn too_large_error :: -> Failure
1286{
1287 Bad(413, "request body too large")
1288}
1289
1290/// Tell a client that waits for it (`Expect: 100-continue`) to send the
1291/// body.
1292fn continue_if_expected :: conn headers buffer: Bytes at: Int -> () / <io>
1293{
1294 let expect = option.map (find_header headers "expect") string.to_lower
1295 if expect == Some("100-continue") && bytes.length buffer == at
1296 {
1297 let _ = net.write_string conn "HTTP/1.1 100 Continue\r\n\r\n"
1298 ()
1299 }
1300 else
1301 {
1302 ()
1303 }
1304}
1305
1306/// The data of the chunks from offset `at` of `buffer` on, appended to
1307/// `body` (`size` bytes so far); then where the next request starts.
1308fn read_chunks ::
1309 conn
1310 activity
1311 max_body: Int
1312 buffer: Bytes
1313 at: Int
1314 body: Builder
1315 size: Int
1316 -> Result<(Bytes, Bytes, Int), Failure> / <io, proc>
1317{
1318 match parse_chunk buffer at
1319 { ChunkData(start, chunk) -> if too_large (size + chunk) max_body
1320 {
1321 Error(too_large_error ())
1322 }
1323 else
1324 {
1325 match take conn activity buffer start (chunk + 2)
1326 { Ok((data, buffer, at)) -> if bytes.slice data chunk (chunk + 2)
1327 == bytes.from_string "\r\n"
1328 {
1329 read_chunks
1330 conn
1331 activity
1332 max_body
1333 buffer
1334 at
1335 (bytes.append body (bytes.slice data 0 chunk))
1336 (size + chunk)
1337 }
1338 else
1339 {
1340 Error(Bad(400, "bad request: no CRLF after a chunk"))
1341 }
1342 , Error(e) -> Error(e)
1343 }
1344 }
1345 , ChunkEnd(end) -> Ok((bytes.build body, buffer, end))
1346 , ChunkInvalid(reason) -> Error(Bad(400, "bad request: " <> reason))
1347 , ChunkPartial -> if bytes.length buffer - at > 65536
1348 {
1349 Error(Bad(400, "bad request: chunk header too large"))
1350 }
1351 else
1352 {
1353 match receive_more conn activity buffer at
1354 { Ok(buffer) -> read_chunks conn activity max_body buffer 0 body size
1355 , Error(e) -> Error(e)
1356 }
1357 }
1358 }
1359}
1360
1361/// `length` bytes from offset `at` of `buffer`, reading more as needed;
1362/// then where what follows them starts. Reads go into a builder, so a
1363/// large body is copied a bounded number of times.
1364fn take ::
1365 conn
1366 activity
1367 buffer: Bytes
1368 at: Int
1369 length: Int
1370 -> Result<(Bytes, Bytes, Int), Failure> / <io, proc>
1371{
1372 let available = bytes.length buffer - at
1373 if available >= length
1374 {
1375 Ok((bytes.slice buffer at (at + length), buffer, at + length))
1376 }
1377 else
1378 {
1379 let rest = bytes.slice buffer at (bytes.length buffer)
1380 take_more
1381 conn
1382 activity
1383 (bytes.append (bytes.builder ()) rest)
1384 available
1385 length
1386 }
1387}
1388
1389fn take_more ::
1390 conn
1391 activity
1392 received: Builder
1393 size: Int
1394 length: Int
1395 -> Result<(Bytes, Bytes, Int), Failure> / <io, proc>
1396{
1397 if size >= length
1398 {
1399 let all = bytes.build received
1400 Ok((bytes.slice all 0 length, all, length))
1401 }
1402 else
1403 {
1404 match read_some conn activity
1405 { Ok(more) ->
1406 take_more
1407 conn
1408 activity
1409 (bytes.append received more)
1410 (size + bytes.length more)
1411 length
1412 , Error(e) -> Error(e)
1413 }
1414 }
1415}
1416
1417/// The unread part of `buffer` (from offset `at`), then what arrives next.
1418fn receive_more ::
1419 conn
1420 activity
1421 buffer: Bytes
1422 at: Int
1423 -> Result<Bytes, Failure> / <io, proc>
1424{
1425 match read_some conn activity
1426 { Ok(more) ->
1427 Ok(bytes.concat (bytes.slice buffer at (bytes.length buffer)) more)
1428 , Error(e) -> Error(e)
1429 }
1430}
1431
1432/// The next bytes from the connection, timed by `idle_timeout` from now.
1433fn read_some ::
1434 conn: Resource<TcpStream>
1435 activity: Subject<Activity>
1436 -> Result<Bytes, Failure> / <io, proc>
1437{
1438 process.send activity Reading
1439 read_raw conn
1440}
1441
1442/// The next bytes from the connection, under whatever timeout runs.
1443fn read_raw :: conn: Resource<TcpStream> -> Result<Bytes, Failure> / <io>
1444{
1445 match net.read conn 65536
1446 { Ok(more) -> if bytes.length more == 0 { Error(Closed) } else { Ok(more) }
1447 , Error(_) -> Error(Closed)
1448 }
1449}
1450
1451type Head
1452{ Partial
1453, Invalid(reason: String)
1454 /// The head ends at offset `end`; `content_length` is -1 when absent.
1455, Complete(
1456 method: String
1457 , path: String
1458 , version: Int
1459 , headers: List<(String, String)>
1460 , end: Int
1461 , content_length: Int
1462 )
1463}
1464
1465@extern c "tl_http_parse_request"
1466fn parse_head :: buffer: Bytes at: Int -> Head
1467
1468/// Where the head in `buffer` ends (just past its empty line), if it ends
1469/// at or after `from`; else -1.
1470@extern c "tl_http_parse_head_end"
1471fn parse_head_end :: buffer: Bytes from: Int -> Int
1472
1473type Chunk
1474{ ChunkPartial
1475, ChunkInvalid(reason: String)
1476 /// `size` bytes of data from offset `start`, then CRLF.
1477, ChunkData(start: Int, size: Int)
1478 /// The last chunk and its trailers end at offset `end`.
1479, ChunkEnd(end: Int)
1480}
1481
1482@extern c "tl_http_parse_chunk"
1483fn parse_chunk :: buffer: Bytes at: Int -> Chunk
1484
1485/// Whether `status` is a final status this server sends without framing or a
1486/// message body: 204 No Content or 304 Not Modified.
1487fn final_status_without_body :: status: Int -> Bool
1488{
1489 status == 204 || status == 304
1490}
1491
1492/// The head and (unless `with_body` is false, for HEAD requests) the body,
1493/// in one buffer so they leave in one write. The whole-body case.
1494fn serialize :: resp: Response keep_alive: Bool with_body: Bool -> Bytes
1495{
1496 let body = option.unwrap_or (whole_body resp) (bytes.empty ())
1497 let head =
1498 head_bytes
1499 resp.status
1500 resp.headers
1501 keep_alive
1502 ("Content-Length: " <> show (bytes.length body))
1503 let out = bytes.append_string (bytes.builder ()) head
1504 bytes.build if with_body { bytes.append out body } else { out }
1505}
1506
1507/// A streamed response's head: `Transfer-Encoding: chunked`, no length.
1508fn serialize_stream_head :: resp: Response keep_alive: Bool -> Bytes
1509{
1510 bytes.from_string
1511 ( head_bytes
1512 resp.status
1513 resp.headers
1514 keep_alive
1515 "Transfer-Encoding: chunked"
1516 )
1517}
1518
1519/// The status line, the caller's headers (framing filtered), the framing
1520/// header, and the keep-alive line.
1521fn head_bytes ::
1522 status: Int
1523 headers: List<(String, String)>
1524 keep_alive: Bool
1525 framing: String
1526 -> String
1527{
1528 let own = list.filter headers fn h { !is_framing (string.to_lower h.0) }
1529 string.concat
1530 [ "HTTP/1.1 "
1531 , show status
1532 , " "
1533 , reason status
1534 , "\r\n"
1535 , string.concat (list.map own fn h { h.0 <> ": " <> h.1 <> "\r\n" })
1536 , if framing == "" { "" } else { framing <> "\r\n" }
1537 , if keep_alive
1538 {
1539 "Connection: keep-alive\r\n\r\n"
1540 }
1541 else
1542 {
1543 "Connection: close\r\n\r\n"
1544 }
1545 ]
1546}
1547
1548/// Headers the server sets itself.
1549fn is_framing :: name: String -> Bool
1550{
1551 match name
1552 { "content-length" | "connection" | "transfer-encoding" -> True, _ -> False }
1553}
1554
1555/// The status line's reason phrase (RFC 9110 §15 and the registered
1556/// extensions); `"Status"` for one not in the set.
1557pub fn reason :: status: Int -> String
1558{
1559 match status
1560 { 100 -> "Continue"
1561 , 101 -> "Switching Protocols"
1562 , 200 -> "OK"
1563 , 201 -> "Created"
1564 , 202 -> "Accepted"
1565 , 203 -> "Non-Authoritative Information"
1566 , 204 -> "No Content"
1567 , 205 -> "Reset Content"
1568 , 206 -> "Partial Content"
1569 , 226 -> "IM Used"
1570 , 300 -> "Multiple Choices"
1571 , 301 -> "Moved Permanently"
1572 , 302 -> "Found"
1573 , 303 -> "See Other"
1574 , 304 -> "Not Modified"
1575 , 305 -> "Use Proxy"
1576 , 307 -> "Temporary Redirect"
1577 , 308 -> "Permanent Redirect"
1578 , 400 -> "Bad Request"
1579 , 401 -> "Unauthorized"
1580 , 402 -> "Payment Required"
1581 , 403 -> "Forbidden"
1582 , 404 -> "Not Found"
1583 , 405 -> "Method Not Allowed"
1584 , 406 -> "Not Acceptable"
1585 , 407 -> "Proxy Authentication Required"
1586 , 408 -> "Request Timeout"
1587 , 409 -> "Conflict"
1588 , 410 -> "Gone"
1589 , 411 -> "Length Required"
1590 , 412 -> "Precondition Failed"
1591 , 413 -> "Content Too Large"
1592 , 414 -> "URI Too Long"
1593 , 415 -> "Unsupported Media Type"
1594 , 416 -> "Range Not Satisfiable"
1595 , 417 -> "Expectation Failed"
1596 , 418 -> "I'm a Teapot"
1597 , 421 -> "Misdirected Request"
1598 , 422 -> "Unprocessable Content"
1599 , 423 -> "Locked"
1600 , 424 -> "Failed Dependency"
1601 , 425 -> "Too Early"
1602 , 426 -> "Upgrade Required"
1603 , 428 -> "Precondition Required"
1604 , 429 -> "Too Many Requests"
1605 , 431 -> "Request Header Fields Too Large"
1606 , 451 -> "Unavailable For Legal Reasons"
1607 , 500 -> "Internal Server Error"
1608 , 501 -> "Not Implemented"
1609 , 502 -> "Bad Gateway"
1610 , 503 -> "Service Unavailable"
1611 , 504 -> "Gateway Timeout"
1612 , 505 -> "HTTP Version Not Supported"
1613 , 507 -> "Insufficient Storage"
1614 , 508 -> "Loop Detected"
1615 , 510 -> "Not Extended"
1616 , 511 -> "Network Authentication Required"
1617 , _ -> "Status"
1618 }
1619}
1620
1621/// The fields of an `application/x-www-form-urlencoded` body (or query
1622/// string): `a=1&b=two+words` gives `[("a", "1"), ("b", "two words")]`.
1623/// Pairs split on `&`, each on its first `=`, both sides percent-decoded
1624/// with `+` a space — in the query (`query_params`) as in a form body,
1625/// as browsers send both; empty pairs are dropped, a bare `k` is
1626/// `("k", "")`.
1627@extern c "tl_http_parse_query"
1628pub fn form :: body: String -> List<(String, String)>
1629
1630/// The request target split at its first `?`: `(path, query)`, the query
1631/// without the `?` ("" when there is none). Later `?`s stay in the query:
1632/// `target_split("/a?b?c")` is `("/a", "b?c")`.
1633pub fn target_split :: target: String -> (String, String)
1634{
1635 match string.split target "?"
1636 { [path] -> (path, "")
1637 , [path, ..rest] -> (path, string.join rest "?")
1638 , [] -> ("", "")
1639 }
1640}
1641
1642/// The path of the request's target (before any `?`).
1643pub fn path :: req: Request -> String
1644{
1645 (target_split req.path).0
1646}
1647
1648/// The query of the request's target (after the first `?`), "" when it
1649/// has none.
1650pub fn query :: req: Request -> String
1651{
1652 (target_split req.path).1
1653}
1654
1655/// The path's segments: split on `/` with empty segments dropped, each
1656/// percent-decoded. Decoding happens after splitting, so an encoded slash
1657/// (`%2F`) stays inside its segment.
1658pub fn segments :: req: Request -> List<String>
1659{
1660 list.map
1661 (list.filter (string.split (path req) "/") fn s { s != "" })
1662 url_decode
1663}
1664
1665/// The query's parameters: split on `&`, each `k=v` on its first `=`,
1666/// both sides percent-decoded; a bare `k` is `("k", "")`.
1667pub fn query_params :: req: Request -> List<(String, String)>
1668{
1669 form (query req)
1670}
1671
1672/// The value of field `name` in a form, if present.
1673pub fn field :: fields: List<(String, String)> name: String -> Option<String>
1674{
1675 match fields
1676 { [] -> None
1677 , [(k, v), ..rest] -> if k == name { Some(v) } else { field rest name }
1678 }
1679}
1680
1681/// Decode `%XX` escapes and `+` (a space); invalid escapes stay as they
1682/// are. A string without `%` or `+` is returned as is.
1683@extern c "tl_url_decode" owned
1684pub fn url_decode :: s: String -> String
1685
1686/// Percent-encode `s` for a URL path or query (RFC 3986): every byte
1687/// outside the unreserved set (`A-Z a-z 0-9 - _ . ~`) becomes `%XX`
1688/// (uppercase hex). A space is `%20`, not `+`: `url_decode` maps both
1689/// back to a space, and a `+` in a path segment decodes as a space only
1690/// in a query or form, so `%20` is the safe spelling everywhere.
1691/// `url_decode(url_encode(s))` is `s`. A string without a byte to encode
1692/// is returned as is.
1693@extern c "tl_url_encode" owned
1694pub fn url_encode :: s: String -> String