Skip to main content

quilt/serve/
http.rs

1//! The least HTTP a local session needs: request in, response out, and one
2//! long-lived stream for events.
3//!
4//! Hand-written, on `std::net`, because of what this server *is*. It binds
5//! `127.0.0.1`, it serves one notebook to one person, its handlers hold a
6//! mutex over a `Notebook` and run subprocesses — nothing about it is
7//! throughput, TLS, HTTP/2, or a thousand concurrent sockets. Against that,
8//! an async runtime and a framework are a dependency tree the published
9//! `quiltlang` would carry for one subcommand; the parts actually used here
10//! are a request line, a `Content-Length`, and `text/event-stream`, which is
11//! this file.
12//!
13//! What it deliberately does *not* do: chunked request bodies (browsers do
14//! not send them for `fetch` with a string body), `100-continue`, ranges,
15//! compression, or trailers. A request it cannot read is answered `400` and
16//! the connection is closed.
17
18use std::collections::BTreeMap;
19use std::fmt::Write as _;
20use std::io::{BufRead, BufReader, Read, Write};
21use std::net::TcpStream;
22use std::sync::mpsc::Receiver;
23
24/// The most a request body may carry: a cell's source, a page fragment, a
25/// posted result. Anything larger is a mistake or an attack, and is refused
26/// before it is read.
27const MAX_BODY: usize = 16 * 1024 * 1024;
28
29/// The most a request line or header may carry.
30const MAX_LINE: usize = 64 * 1024;
31
32/**************************************************************/
33
34/// One request, as the handlers want it.
35#[derive(Debug, Clone, Default)]
36pub struct Request {
37    pub method: String,
38    /// The path, percent-decoded, without the query.
39    pub path: String,
40    /// The query string, as written, without the `?`.
41    pub query: String,
42    /// Header names lowercased — the wire says they are case-insensitive.
43    pub headers: BTreeMap<String, String>,
44    pub body: Vec<u8>,
45}
46
47impl Request {
48    #[must_use]
49    pub fn header(&self, name: &str) -> Option<&str> {
50        self.headers.get(name).map(String::as_str)
51    }
52
53    /// The body as text; invalid UTF-8 is replaced rather than refused.
54    #[must_use]
55    pub fn text(&self) -> String {
56        String::from_utf8_lossy(&self.body).into_owned()
57    }
58
59    /// The path split on `/`, empty segments dropped: `/cells/3/run` is
60    /// `["cells", "3", "run"]`.
61    #[must_use]
62    pub fn segments(&self) -> Vec<&str> {
63        self.path.split('/').filter(|s| !s.is_empty()).collect()
64    }
65
66    /// One query parameter, percent-decoded.
67    #[must_use]
68    pub fn param(&self, name: &str) -> Option<String> {
69        self.query.split('&').find_map(|pair| {
70            let (k, v) = pair.split_once('=')?;
71            (percent_decode(k) == name).then(|| percent_decode(v))
72        })
73    }
74
75    /// One cookie value.
76    #[must_use]
77    pub fn cookie(&self, name: &str) -> Option<String> {
78        self.header("cookie")?.split(';').find_map(|pair| {
79            let (k, v) = pair.split_once('=')?;
80            (k.trim() == name).then(|| v.trim().to_string())
81        })
82    }
83}
84
85/// One response.
86#[derive(Debug, Clone)]
87pub struct Response {
88    pub status: u16,
89    pub content_type: String,
90    pub body: Vec<u8>,
91    /// Extra headers, in the order they are written.
92    pub headers: Vec<(String, String)>,
93}
94
95impl Response {
96    #[must_use]
97    pub fn new(status: u16, content_type: &str, body: impl Into<Vec<u8>>) -> Response {
98        Response {
99            status,
100            content_type: content_type.to_string(),
101            body: body.into(),
102            headers: Vec::new(),
103        }
104    }
105
106    #[must_use]
107    pub fn html(body: impl Into<Vec<u8>>) -> Response {
108        Response::new(200, "text/html; charset=utf-8", body)
109    }
110
111    #[must_use]
112    pub fn text(body: impl Into<Vec<u8>>) -> Response {
113        Response::new(200, "text/plain; charset=utf-8", body)
114    }
115
116    #[must_use]
117    pub fn json(body: impl Into<Vec<u8>>) -> Response {
118        Response::new(200, "application/json; charset=utf-8", body)
119    }
120
121    /// A status with a plain-text reason — every error this server answers.
122    #[must_use]
123    pub fn status(status: u16, message: &str) -> Response {
124        Response::new(status, "text/plain; charset=utf-8", message.to_string())
125    }
126
127    #[must_use]
128    pub fn with_header(mut self, name: &str, value: &str) -> Response {
129        self.headers.push((name.to_string(), value.to_string()));
130        self
131    }
132}
133
134/// One server-sent event.
135#[derive(Debug, Clone)]
136pub struct Event {
137    pub name: String,
138    pub data: String,
139}
140
141/// What a handler answers: a response, or the event stream.
142pub enum Reply {
143    Done(Response),
144    /// Hold the connection open and write every event that arrives, until
145    /// the viewer goes away.
146    Events(Receiver<Event>),
147}
148
149/**************************************************************/
150
151/// Read one request. `Ok(None)` is a connection the peer closed between
152/// requests — the ordinary end of a keep-alive connection, not an error.
153pub fn read_request<R: BufRead>(r: &mut R) -> std::io::Result<Option<Request>> {
154    let Some(line) = read_line(r)? else {
155        return Ok(None);
156    };
157    if line.trim().is_empty() {
158        return Ok(None);
159    }
160    let mut parts = line.split_whitespace();
161    let (Some(method), Some(target)) = (parts.next(), parts.next()) else {
162        return Err(bad("a request line is `METHOD TARGET VERSION`"));
163    };
164    let (path, query) = target.split_once('?').unwrap_or((target, ""));
165    let mut req = Request {
166        method: method.to_ascii_uppercase(),
167        path: percent_decode(path),
168        query: query.to_string(),
169        ..Request::default()
170    };
171    while let Some(line) = read_line(r)? {
172        if line.trim().is_empty() {
173            break;
174        }
175        if let Some((name, value)) = line.split_once(':') {
176            req.headers
177                .insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
178        }
179    }
180    let length: usize = req
181        .header("content-length")
182        .and_then(|v| v.trim().parse().ok())
183        .unwrap_or(0);
184    if length > MAX_BODY {
185        return Err(bad("request body too large"));
186    }
187    req.body = vec![0; length];
188    r.read_exact(&mut req.body)?;
189    Ok(Some(req))
190}
191
192/// Read one CRLF-terminated line, without its terminator.
193fn read_line<R: BufRead>(r: &mut R) -> std::io::Result<Option<String>> {
194    let mut buf = Vec::new();
195    let read = r.take(MAX_LINE as u64).read_until(b'\n', &mut buf)?;
196    if read == 0 {
197        return Ok(None);
198    }
199    while buf.last().is_some_and(|c| *c == b'\n' || *c == b'\r') {
200        buf.pop();
201    }
202    Ok(Some(String::from_utf8_lossy(&buf).into_owned()))
203}
204
205fn bad(message: &str) -> std::io::Error {
206    std::io::Error::new(std::io::ErrorKind::InvalidData, message)
207}
208
209/// Percent-decoding, plus `+` for a space — enough for the paths and query
210/// values a browser sends here.
211#[must_use]
212pub fn percent_decode(s: &str) -> String {
213    let bytes = s.as_bytes();
214    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
215    let mut i = 0;
216    while i < bytes.len() {
217        match bytes[i] {
218            b'%' if i + 2 < bytes.len() => {
219                let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("");
220                if let Ok(byte) = u8::from_str_radix(hex, 16) {
221                    out.push(byte);
222                    i += 3;
223                } else {
224                    out.push(bytes[i]);
225                    i += 1;
226                }
227            }
228            b'+' => {
229                out.push(b' ');
230                i += 1;
231            }
232            byte => {
233                out.push(byte);
234                i += 1;
235            }
236        }
237    }
238    String::from_utf8_lossy(&out).into_owned()
239}
240
241/**************************************************************/
242
243/// Serve one connection until the peer closes it or a handler takes it over
244/// as an event stream.
245pub fn serve_connection<H>(stream: TcpStream, handle: &H)
246where
247    H: Fn(&Request) -> Reply,
248{
249    let _ = stream.set_nodelay(true);
250    let Ok(write_half) = stream.try_clone() else {
251        return;
252    };
253    let mut reader = BufReader::new(stream);
254    let mut writer = write_half;
255    loop {
256        let request = match read_request(&mut reader) {
257            Ok(Some(request)) => request,
258            // A request that cannot be read is answered and the connection
259            // ends; a closed connection just ends.
260            Err(e) if e.kind() == std::io::ErrorKind::InvalidData => {
261                let _ = write_response(&mut writer, &Response::status(400, &e.to_string()), false);
262                return;
263            }
264            Ok(None) | Err(_) => return,
265        };
266        // A client that said `Connection: close` is waiting for the end of
267        // the stream, not for another response.
268        let keep_alive = !request
269            .header("connection")
270            .is_some_and(|v| v.eq_ignore_ascii_case("close"));
271        match handle(&request) {
272            Reply::Done(response) => {
273                if write_response(&mut writer, &response, keep_alive).is_err() || !keep_alive {
274                    return;
275                }
276            }
277            Reply::Events(events) => {
278                stream_events(&mut writer, &events);
279                return;
280            }
281        }
282    }
283}
284
285/// Write one response. `keep_alive` is a promise about this connection, not
286/// about the request: a body is always length-delimited here, so the peer
287/// can always find the end.
288pub fn write_response<W: Write>(
289    w: &mut W,
290    response: &Response,
291    keep_alive: bool,
292) -> std::io::Result<()> {
293    let mut head = format!(
294        "HTTP/1.1 {} {}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: {}\r\n",
295        response.status,
296        reason(response.status),
297        response.content_type,
298        response.body.len(),
299        if keep_alive { "keep-alive" } else { "close" },
300    );
301    for (name, value) in &response.headers {
302        let _ = write!(head, "{name}: {value}\r\n");
303    }
304    head.push_str("\r\n");
305    w.write_all(head.as_bytes())?;
306    w.write_all(&response.body)?;
307    w.flush()
308}
309
310/// Hold the connection open, writing events as they arrive. Returns when the
311/// viewer goes away (the write fails) or the sender is dropped.
312fn stream_events<W: Write>(w: &mut W, events: &Receiver<Event>) {
313    let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-store\r\n\
314                Connection: keep-alive\r\n\r\n";
315    if w.write_all(head.as_bytes()).is_err() || w.flush().is_err() {
316        return;
317    }
318    while let Ok(event) = events.recv() {
319        if write_event(w, &event).is_err() {
320            return;
321        }
322    }
323}
324
325/// One event, in the `text/event-stream` framing: a `data:` line per line of
326/// the payload, then a blank line.
327pub fn write_event<W: Write>(w: &mut W, event: &Event) -> std::io::Result<()> {
328    let mut out = String::new();
329    if !event.name.is_empty() {
330        let _ = writeln!(out, "event: {}", event.name);
331    }
332    for line in event.data.split('\n') {
333        let _ = writeln!(out, "data: {line}");
334    }
335    out.push('\n');
336    w.write_all(out.as_bytes())?;
337    w.flush()
338}
339
340fn reason(status: u16) -> &'static str {
341    match status {
342        200 => "OK",
343        204 => "No Content",
344        400 => "Bad Request",
345        403 => "Forbidden",
346        404 => "Not Found",
347        405 => "Method Not Allowed",
348        409 => "Conflict",
349        500 => "Internal Server Error",
350        _ => "Status",
351    }
352}
353
354/**************************************************************/
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359
360    fn parse(raw: &str) -> Request {
361        let mut reader = BufReader::new(raw.as_bytes());
362        read_request(&mut reader)
363            .expect("the request reads")
364            .expect("there is a request")
365    }
366
367    #[test]
368    fn a_request_is_its_line_headers_and_body() {
369        let req = parse(
370            "POST /cells/3/run?engine=browser HTTP/1.1\r\nHost: localhost\r\n\
371             Content-Length: 7\r\n\r\n{\"a\":1}",
372        );
373        assert_eq!(req.method, "POST");
374        assert_eq!(req.segments(), ["cells", "3", "run"]);
375        assert_eq!(req.param("engine").as_deref(), Some("browser"));
376        assert_eq!(req.header("host"), Some("localhost"));
377        assert_eq!(req.text(), "{\"a\":1}");
378    }
379
380    #[test]
381    fn paths_and_params_are_decoded() {
382        let req = parse("GET /page/a%20b?q=x%2By&t=%E2%86%96 HTTP/1.1\r\n\r\n");
383        assert_eq!(req.path, "/page/a b");
384        assert_eq!(req.param("q").as_deref(), Some("x+y"));
385        assert_eq!(req.param("t").as_deref(), Some("↖"));
386    }
387
388    #[test]
389    fn cookies_are_read_by_name() {
390        let req = parse("GET / HTTP/1.1\r\nCookie: other=1; quilt_token=abc\r\n\r\n");
391        assert_eq!(req.cookie("quilt_token").as_deref(), Some("abc"));
392    }
393
394    #[test]
395    fn an_event_is_framed_line_by_line() {
396        let mut out = Vec::new();
397        write_event(
398            &mut out,
399            &Event {
400                name: "page".into(),
401                data: "one\ntwo".into(),
402            },
403        )
404        .expect("write");
405        assert_eq!(
406            String::from_utf8(out).unwrap(),
407            "event: page\ndata: one\ndata: two\n\n"
408        );
409    }
410}