Skip to main content

netio/
http.rs

1// http -- HTTP/1.1 messages and their wire format
2//
3//   Headers (case-insensitive names), Request, Response, Body
4//   Reader: buffered reading of a Stream (lines, heads, bodies by Content-Length or chunked;
5//           body_to hands a body over piece by piece)
6//   write_response / write_request
7//   Body::Upgrade(Upgrade): a 101 answer whose connection a protocol takes over (ws::Acceptor);
8//           the server runs it on a thread of its own with the Upgraded connection
9//
10// Limits: a message head of at most 16 KiB and 100 header lines, bodies up to the caller's
11// limit, chunk sizes checked before use.
12
13use alloc::boxed::Box;
14use alloc::format;
15use alloc::string::String;
16use alloc::sync::Arc;
17use alloc::vec::Vec;
18use core::sync::atomic::AtomicBool;
19
20use formats::json::{self, Value};
21use plat::net::{NetError, NetErrorKind, SocketAddr};
22
23use crate::Stream;
24
25pub const MAX_HEAD: usize = 16 * 1024;
26pub const MAX_HEADERS: usize = 100;
27
28/// header lines; names compare case-insensitively
29#[derive(Clone, Debug, Default, PartialEq, Eq)]
30pub struct Headers(pub Vec<(String, String)>);
31
32impl Headers {
33    pub fn new() -> Headers {
34        Headers(Vec::new())
35    }
36
37    pub fn get(&self, name: &str) -> Option<&str> {
38        self.0.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
39    }
40
41    /// replace (or add) a header
42    pub fn set(&mut self, name: &str, value: &str) {
43        self.remove(name);
44        self.0.push((String::from(name), String::from(value)));
45    }
46
47    pub fn add(&mut self, name: &str, value: &str) {
48        self.0.push((String::from(name), String::from(value)));
49    }
50
51    /// the Content-Length: Ok(None) without one, Err for a value that is not plain digits or
52    /// headers that disagree
53    pub fn content_length(&self) -> Result<Option<u64>, ()> {
54        let mut found: Option<u64> = None;
55        for (k, v) in &self.0 {
56            if !k.eq_ignore_ascii_case("content-length") {
57                continue;
58            }
59            let v = v.trim();
60            if v.is_empty() || !v.bytes().all(|b| b.is_ascii_digit()) {
61                return Err(());
62            }
63            let n: u64 = v.parse().map_err(|_| ())?;
64            if found.is_some_and(|f| f != n) {
65                return Err(());
66            }
67            found = Some(n);
68        }
69        Ok(found)
70    }
71
72    pub fn remove(&mut self, name: &str) {
73        self.0.retain(|(k, _)| !k.eq_ignore_ascii_case(name));
74    }
75
76    /// whether a comma-separated header contains a token (Connection: close, ...)
77    pub fn has_token(&self, name: &str, token: &str) -> bool {
78        self.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case(name)).any(|(_, v)| v.split(',').any(|t| t.trim().eq_ignore_ascii_case(token)))
79    }
80}
81
82/// a request as the server sees it (and as the client sends it)
83#[derive(Debug, Default)]
84pub struct Request {
85    pub method: String,
86    /// path and query, as sent ("/api/jobs?limit=5")
87    pub target: String,
88    pub headers: Headers,
89    pub body: Vec<u8>,
90    /// the remote address (server side)
91    pub peer: Option<SocketAddr>,
92    /// the identity the transport proved (TLS client certificate), if any
93    pub client_id: Option<String>,
94}
95
96impl Request {
97    pub fn new(method: &str, target: &str) -> Request {
98        Request { method: String::from(method), target: String::from(target), ..Request::default() }
99    }
100
101    /// the path without the query
102    pub fn path(&self) -> &str {
103        crate::url::split_target(&self.target).0
104    }
105
106    /// a query parameter, decoded
107    pub fn query(&self, key: &str) -> Option<String> {
108        crate::url::query_pairs(crate::url::split_target(&self.target).1).into_iter().find(|(k, _)| k == key).map(|(_, v)| v)
109    }
110
111    pub fn header(&self, name: &str) -> Option<&str> {
112        self.headers.get(name)
113    }
114
115    /// the body as JSON (None: not JSON or over the limits)
116    pub fn json(&self, limits: json::Limits) -> Option<Value> {
117        json::parse_with_limits(&self.body, limits).ok()
118    }
119
120    /// the bearer token of the Authorization header
121    pub fn bearer(&self) -> Option<&str> {
122        let v = self.header("authorization")?;
123        let (scheme, token) = v.split_once(' ')?;
124        scheme.eq_ignore_ascii_case("bearer").then(|| token.trim())
125    }
126}
127
128/// a response body
129#[non_exhaustive]
130pub enum Body {
131    Empty,
132    Bytes(Vec<u8>),
133    /// produced piece by piece and sent chunked: the callback appends the next piece to the
134    /// buffer and returns false after the last one (Content-Length when `len` is known)
135    Stream { len: Option<u64>, next: Box<dyn FnMut(&mut Vec<u8>) -> bool + Send> },
136    /// (G7d) with status 101: the server sends the head as it is (Connection and Upgrade as the
137    /// handler set them, no length), then hands the connection to the upgrade on a thread of its
138    /// own (`ws::Acceptor::accept` makes such answers).  With any other status: no body
139    Upgrade(Upgrade),
140}
141
142/// (G7d) what takes over a connection after `101 Switching Protocols` (a WebSocket): runs once on
143/// a thread of the server's own, with the connection
144pub struct Upgrade(Box<dyn FnOnce(Upgraded) + Send>);
145
146impl Upgrade {
147    /// the code that takes over the connection (it ends the connection by returning)
148    pub fn new(f: impl FnOnce(Upgraded) + Send + 'static) -> Upgrade {
149        Upgrade(Box::new(f))
150    }
151
152    /// run it with the connection (the server does this)
153    pub fn run(self, up: Upgraded) {
154        (self.0)(up)
155    }
156}
157
158/// (G7d) a connection after an upgrade, as the server hands it over
159pub struct Upgraded {
160    /// the connection (TCP, or TLS under `Server::start_with`); reads and writes have no timeouts
161    /// set, the protocol sets its own
162    pub stream: Box<dyn crate::Stream>,
163    /// bytes the client sent after its request that the server had already read
164    pub buffered: Vec<u8>,
165    /// the client's address
166    pub peer: Option<SocketAddr>,
167    /// set when the server stops (`Server::stop` waits for the upgraded connections to end)
168    pub stop: Arc<AtomicBool>,
169}
170
171impl core::fmt::Debug for Body {
172    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
173        match self {
174            Body::Empty => f.write_str("Empty"),
175            Body::Bytes(b) => write!(f, "Bytes({})", b.len()),
176            Body::Stream { len, .. } => write!(f, "Stream({:?})", len),
177            Body::Upgrade(_) => f.write_str("Upgrade"),
178        }
179    }
180}
181
182#[derive(Debug)]
183pub struct Response {
184    pub status: u16,
185    pub headers: Headers,
186    pub body: Body,
187}
188
189impl Response {
190    pub fn new(status: u16) -> Response {
191        Response { status, headers: Headers::new(), body: Body::Empty }
192    }
193
194    pub fn bytes(status: u16, content_type: &str, body: Vec<u8>) -> Response {
195        let mut r = Response::new(status);
196        r.headers.set("Content-Type", content_type);
197        r.body = Body::Bytes(body);
198        r
199    }
200
201    pub fn text(status: u16, s: &str) -> Response {
202        Response::bytes(status, "text/plain; charset=utf-8", Vec::from(s.as_bytes()))
203    }
204
205    pub fn json(status: u16, v: &Value) -> Response {
206        let lim = json::Limits { bytes: 64 << 20, depth: 32, values: 4_000_000, string_bytes: 16 << 20, members: 1_000_000 };
207        match json::stringify_with_limits(v, lim) {
208            Ok(s) => Response::bytes(status, "application/json", s.into_bytes()),
209            Err(_) => Response::text(500, "response too large"),
210        }
211    }
212
213    pub fn header(mut self, name: &str, value: &str) -> Response {
214        self.headers.set(name, value);
215        self
216    }
217
218    /// the body bytes (client side: always Bytes)
219    pub fn body_bytes(&self) -> &[u8] {
220        match &self.body {
221            Body::Bytes(b) => b,
222            _ => &[],
223        }
224    }
225
226    pub fn body_json(&self, limits: json::Limits) -> Option<Value> {
227        json::parse_with_limits(self.body_bytes(), limits).ok()
228    }
229}
230
231/// the reason phrase of a status code
232pub fn reason(status: u16) -> &'static str {
233    match status {
234        100 => "Continue",
235        101 => "Switching Protocols",
236        200 => "OK",
237        201 => "Created",
238        202 => "Accepted",
239        204 => "No Content",
240        206 => "Partial Content",
241        301 => "Moved Permanently",
242        302 => "Found",
243        304 => "Not Modified",
244        400 => "Bad Request",
245        401 => "Unauthorized",
246        403 => "Forbidden",
247        404 => "Not Found",
248        405 => "Method Not Allowed",
249        408 => "Request Timeout",
250        409 => "Conflict",
251        411 => "Length Required",
252        413 => "Content Too Large",
253        414 => "URI Too Long",
254        415 => "Unsupported Media Type",
255        422 => "Unprocessable Content",
256        423 => "Locked",
257        429 => "Too Many Requests",
258        431 => "Request Header Fields Too Large",
259        500 => "Internal Server Error",
260        501 => "Not Implemented",
261        502 => "Bad Gateway",
262        503 => "Service Unavailable",
263        504 => "Gateway Timeout",
264        505 => "HTTP Version Not Supported",
265        _ => "Unknown",
266    }
267}
268
269// ------------------------------------------------------------------ reading
270
271/// why reading a message failed
272#[derive(Clone, Copy, Debug, PartialEq, Eq)]
273#[non_exhaustive]
274pub enum ReadError {
275    /// the connection ended before a message started (normal end of keep-alive)
276    Closed,
277    Net(NetError),
278    /// malformed (400)
279    Bad,
280    /// head over 16 KiB or too many header lines (431)
281    HeadTooLarge,
282    /// body over the limit (413)
283    BodyTooLarge,
284}
285
286impl From<NetError> for ReadError {
287    fn from(e: NetError) -> Self {
288        ReadError::Net(e)
289    }
290}
291
292/// buffered reading of a stream
293pub struct Reader<'a> {
294    s: &'a dyn Stream,
295    buf: Vec<u8>,
296    pos: usize,
297    deadline_us: Option<u64>,
298    // (since, grace in us, bytes a second) of set_min_rate, and the bytes read since
299    rate: Option<(u64, u64, u64)>,
300    got: u64,
301}
302
303impl<'a> Reader<'a> {
304    pub fn new(s: &'a dyn Stream) -> Reader<'a> {
305        Reader { s, buf: Vec::with_capacity(8192), pos: 0, deadline_us: None, rate: None, got: 0 }
306    }
307
308    /// reads fail with TimedOut once fewer than `bytes_per_s` arrived on average since this
309    /// call, counted after a first `grace_ms` (a body that dribbles in a byte now and then, each
310    /// within the stream's timeout, must not hold the reader for hours); None: no such limit
311    pub fn set_min_rate(&mut self, rate: Option<(u32, u32)>) {
312        self.rate = rate.map(|(r, g)| (plat::time_us(), g as u64 * 1000, r.max(1) as u64));
313        self.got = 0;
314    }
315
316    /// reads fail with TimedOut once plat::time_us() is past this, and a read waits for bytes
317    /// only until then (a limit for a whole head, where the stream's timeout counts each read)
318    pub fn set_deadline(&mut self, deadline_us: Option<u64>) {
319        self.deadline_us = deadline_us;
320    }
321
322    /// whether unread bytes are buffered (a pipelined next request)
323    pub fn has_buffered(&self) -> bool {
324        self.pos < self.buf.len()
325    }
326
327    /// (G7d) the bytes read from the stream but not consumed yet, taken out of the reader (what
328    /// came after a head that ended the HTTP part of a connection: a WebSocket's first frames)
329    pub fn take_buffered(&mut self) -> Vec<u8> {
330        let rest = self.buf[self.pos..].to_vec();
331        self.pos = self.buf.len();
332        rest
333    }
334
335    fn fill(&mut self) -> Result<usize, NetError> {
336        if self.pos > 0 && self.pos == self.buf.len() {
337            self.buf.clear();
338            self.pos = 0;
339        }
340        if let Some(d) = self.deadline_us {
341            // a read starts only with bytes there before the deadline (not a stream timeout later)
342            let left = d.saturating_sub(plat::time_us()) / 1000;
343            if left == 0 || !self.s.wait_readable(left.min(u32::MAX as u64) as u32) {
344                return Err(NetError::new(NetErrorKind::TimedOut, 0));
345            }
346        }
347        if let Some((t0, grace, r)) = self.rate {
348            if plat::time_us() > t0 + grace + self.got.saturating_mul(1_000_000) / r {
349                return Err(NetError::new(NetErrorKind::TimedOut, 0));
350            }
351        }
352        let old = self.buf.len();
353        self.buf.resize(old + 16 * 1024, 0);
354        let n = self.s.read(&mut self.buf[old..]);
355        let got = *n.as_ref().unwrap_or(&0);
356        self.buf.truncate(old + got);
357        self.got += got as u64;
358        n
359    }
360
361    /// one line without CRLF (LF alone accepted); at most `max` bytes
362    fn line(&mut self, max: usize, first: bool) -> Result<String, ReadError> {
363        loop {
364            if let Some(i) = self.buf[self.pos..].iter().position(|&c| c == b'\n') {
365                let mut l = &self.buf[self.pos..self.pos + i];
366                self.pos += i + 1;
367                if l.last() == Some(&b'\r') {
368                    l = &l[..l.len() - 1];
369                }
370                return core::str::from_utf8(l).map(String::from).map_err(|_| ReadError::Bad);
371            }
372            if self.buf.len() - self.pos > max {
373                return Err(ReadError::HeadTooLarge);
374            }
375            let n = self.fill().map_err(|e| if first && self.buf.len() == self.pos && e.kind == NetErrorKind::Reset { ReadError::Closed } else { ReadError::Net(e) })?;
376            if n == 0 {
377                return Err(if first && self.buf.len() == self.pos { ReadError::Closed } else { ReadError::Bad });
378            }
379        }
380    }
381
382    /// the start line and the headers of a message
383    pub fn head(&mut self) -> Result<(String, Headers), ReadError> {
384        let mut budget = MAX_HEAD;
385        let mut start = self.line(budget, true)?;
386        // tolerate empty lines before a request (RFC 9112 2.2)
387        let mut skipped = 0;
388        while start.is_empty() && skipped < 4 {
389            start = self.line(budget, false)?;
390            skipped += 1;
391        }
392        budget = budget.saturating_sub(start.len());
393        let mut h = Headers::new();
394        loop {
395            let l = self.line(budget, false)?;
396            if l.is_empty() {
397                break;
398            }
399            budget = budget.checked_sub(l.len() + 2).ok_or(ReadError::HeadTooLarge)?;
400            if h.0.len() >= MAX_HEADERS {
401                return Err(ReadError::HeadTooLarge);
402            }
403            if l.starts_with([' ', '\t']) {
404                return Err(ReadError::Bad); // obsolete line folding
405            }
406            let (k, v) = l.split_once(':').ok_or(ReadError::Bad)?;
407            if k.is_empty() || k.bytes().any(|b| b <= b' ' || b == 0x7f) {
408                return Err(ReadError::Bad);
409            }
410            let v = v.trim();
411            if v.bytes().any(|b| (b < b' ' && b != b'\t') || b == 0x7f) {
412                return Err(ReadError::Bad);
413            }
414            h.add(k, v);
415        }
416        Ok((start, h))
417    }
418
419    // n bytes of the body to sink (false from sink: Bad)
420    fn pass(&mut self, n: u64, sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<(), ReadError> {
421        let mut need = n;
422        while need > 0 {
423            if self.pos == self.buf.len() && self.fill()? == 0 {
424                return Err(ReadError::Bad);
425            }
426            let k = need.min((self.buf.len() - self.pos) as u64) as usize;
427            if !sink(&self.buf[self.pos..self.pos + k]) {
428                return Err(ReadError::Bad);
429            }
430            self.pos += k;
431            need -= k as u64;
432        }
433        Ok(())
434    }
435
436    /// a message body by Content-Length or chunked transfer (`until_close`: a response without
437    /// either reads to the end)
438    pub fn body(&mut self, h: &Headers, max: usize, until_close: bool) -> Result<Vec<u8>, ReadError> {
439        let mut out = Vec::new();
440        if h.get("transfer-encoding").is_none() {
441            if let Ok(Some(n)) = h.content_length() {
442                out.reserve((n.min(max as u64) as usize).min(1 << 20));
443            }
444        }
445        self.body_to(h, max as u64, until_close, &mut |b| {
446            out.extend_from_slice(b);
447            true
448        })?;
449        Ok(out)
450    }
451
452    /// the body like body(), but each piece goes to `sink` as it arrives (downloads of any
453    /// size); `sink` returning false stops reading with Err(Bad) -> the number of body bytes
454    pub fn body_to(&mut self, h: &Headers, max: u64, until_close: bool, sink: &mut dyn FnMut(&[u8]) -> bool) -> Result<u64, ReadError> {
455        if h.get("transfer-encoding").is_some() {
456            // chunked and only chunked, over all Transfer-Encoding lines: another coding (or
457            // chunked twice) would leave the length to whoever reads it differently
458            let mut codings = h.0.iter().filter(|(k, _)| k.eq_ignore_ascii_case("transfer-encoding")).flat_map(|(_, v)| v.split(',')).map(str::trim).filter(|c| !c.is_empty());
459            if !codings.next().is_some_and(|c| c.eq_ignore_ascii_case("chunked")) || codings.next().is_some() {
460                return Err(ReadError::Bad);
461            }
462            let mut total: u64 = 0;
463            loop {
464                let l = self.line(1024, false)?;
465                let size = l.split(';').next().unwrap_or("").trim();
466                if !size.bytes().all(|c| c.is_ascii_hexdigit()) {
467                    return Err(ReadError::Bad);
468                }
469                let n = u64::from_str_radix(size, 16).map_err(|_| ReadError::Bad)?;
470                if n == 0 {
471                    // trailers up to the empty line
472                    let mut budget = MAX_HEAD;
473                    for _ in 0..=MAX_HEADERS {
474                        let l = self.line(budget, false)?;
475                        if l.is_empty() {
476                            return Ok(total);
477                        }
478                        budget = budget.checked_sub(l.len() + 2).ok_or(ReadError::HeadTooLarge)?;
479                    }
480                    return Err(ReadError::HeadTooLarge);
481                }
482                if total.saturating_add(n) > max {
483                    return Err(ReadError::BodyTooLarge);
484                }
485                self.pass(n, sink)?;
486                total += n;
487                if !self.line(2, false)?.is_empty() {
488                    return Err(ReadError::Bad);
489                }
490            }
491        }
492        if let Some(n) = h.content_length().map_err(|_| ReadError::Bad)? {
493            if n > max {
494                return Err(ReadError::BodyTooLarge);
495            }
496            self.pass(n, sink)?;
497            return Ok(n);
498        }
499        if until_close {
500            let mut total: u64 = 0;
501            loop {
502                let piece = &self.buf[self.pos..];
503                total += piece.len() as u64;
504                if total > max {
505                    return Err(ReadError::BodyTooLarge);
506                }
507                if !piece.is_empty() && !sink(piece) {
508                    return Err(ReadError::Bad);
509                }
510                self.pos = self.buf.len();
511                // only an orderly end ends such a body: a reset, or TLS without close_notify,
512                // may be the body cut short, which must not pass for the whole of it
513                match self.fill() {
514                    Ok(0) if self.s.end_is_clean() => return Ok(total),
515                    Ok(0) => return Err(ReadError::Net(NetError::new(NetErrorKind::Reset, 0))),
516                    Ok(_) => {}
517                    Err(e) => return Err(ReadError::Net(e)),
518                }
519            }
520        }
521        Ok(0)
522    }
523}
524
525// ------------------------------------------------------------------ writing
526
527fn head_bytes(start: &str, h: &Headers) -> Vec<u8> {
528    let mut s = String::with_capacity(256);
529    s.push_str(start);
530    s.push_str("\r\n");
531    let token = |b: u8| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b);
532    for (k, v) in &h.0 {
533        // no header injection: a name that is not a token, a value with a control character
534        // (CR, LF, NUL; a tab is fine) is dropped
535        if k.is_empty() || !k.bytes().all(token) || v.bytes().any(|b| (b < b' ' && b != b'\t') || b == 0x7f) {
536            continue;
537        }
538        s.push_str(k);
539        s.push_str(": ");
540        s.push_str(v);
541        s.push_str("\r\n");
542    }
543    s.push_str("\r\n");
544    s.into_bytes()
545}
546
547/// send a response; `head_only` for HEAD requests; false when the connection broke
548pub fn write_response(s: &dyn Stream, r: &mut Response, head_only: bool, keep_alive: bool) -> bool {
549    let mut h = core::mem::take(&mut r.headers);
550    h.set("Connection", if keep_alive { "keep-alive" } else { "close" });
551    let chunked = match &r.body {
552        Body::Empty | Body::Upgrade(_) => {
553            if r.status >= 200 && r.status != 204 && r.status != 304 {
554                h.set("Content-Length", "0");
555            }
556            false
557        }
558        Body::Bytes(b) => {
559            h.set("Content-Length", &format!("{}", b.len()));
560            false
561        }
562        Body::Stream { len: Some(n), .. } => {
563            h.set("Content-Length", &format!("{}", n));
564            false
565        }
566        Body::Stream { len: None, .. } => {
567            h.set("Transfer-Encoding", "chunked");
568            true
569        }
570    };
571    let start = format!("HTTP/1.1 {} {}", r.status, reason(r.status));
572    let head = head_bytes(&start, &h);
573    r.headers = h;
574    match &mut r.body {
575        Body::Bytes(b) if !head_only && b.len() <= 64 * 1024 => {
576            // one write for small answers
577            let mut all = head;
578            all.extend_from_slice(b);
579            s.write_all(&all).is_ok()
580        }
581        Body::Bytes(b) => s.write_all(&head).is_ok() && (head_only || s.write_all(b).is_ok()),
582        Body::Empty | Body::Upgrade(_) => s.write_all(&head).is_ok(),
583        Body::Stream { next, .. } => {
584            if s.write_all(&head).is_err() {
585                return false;
586            }
587            if head_only {
588                return true;
589            }
590            let mut piece = Vec::with_capacity(256 * 1024);
591            loop {
592                piece.clear();
593                let more = next(&mut piece);
594                if !piece.is_empty() {
595                    let ok = if chunked {
596                        let mut frame = format!("{:x}\r\n", piece.len()).into_bytes();
597                        frame.extend_from_slice(&piece);
598                        frame.extend_from_slice(b"\r\n");
599                        s.write_all(&frame).is_ok()
600                    } else {
601                        s.write_all(&piece).is_ok()
602                    };
603                    if !ok {
604                        return false;
605                    }
606                }
607                if !more {
608                    break;
609                }
610            }
611            !chunked || s.write_all(b"0\r\n\r\n").is_ok()
612        }
613    }
614}
615
616/// (G7d) send the head of a `101 Switching Protocols` answer as the handler built it (Connection,
617/// Upgrade and the protocol's headers; no length, no body); false when the connection broke
618pub fn write_switch(s: &dyn Stream, r: &Response) -> bool {
619    s.write_all(&head_bytes(&format!("HTTP/1.1 {} {}", r.status, reason(r.status)), &r.headers)).is_ok()
620}
621
622/// send a request (the body as Content-Length)
623pub fn write_request(s: &dyn Stream, method: &str, target: &str, h: &Headers, body: &[u8]) -> bool {
624    let token = |b: u8| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b);
625    if method.is_empty() || !method.bytes().all(token) || target.is_empty() || target.bytes().any(|b| b <= b' ' || b == 0x7f) {
626        return false;
627    }
628    let mut h = h.clone();
629    if !body.is_empty() || matches!(method, "POST" | "PUT" | "PATCH") {
630        h.set("Content-Length", &format!("{}", body.len()));
631    }
632    let mut all = head_bytes(&format!("{} {} HTTP/1.1", method, target), &h);
633    all.extend_from_slice(body);
634    s.write_all(&all).is_ok()
635}