//! HTTP/1.x framing for `std/http`: request heads and the sizes of //! chunked bodies, parsed by httparse (a port of picohttpparser). //! //! Both parsers read a buffer from an offset and return offsets, so a //! buffer holding several pipelined requests or many small chunks is never //! copied per item (`std/http` slices what it keeps). //! //! The parsing is plain Rust over `&[u8]` (`parse_head`, `parse_chunk`, //! unit-tested below). The externs only turn its result into `std/http`'s //! `Head` and `Chunk` values, whose constructor order the `HEAD_*` and //! `CHUNK_*` constants follow. //! //! **Request smuggling.** On a kept-alive connection, a misread body //! length makes the server read part of a body as the next request. This //! module rejects a `Content-Length` that is not a decimal number, two //! that differ, and more than one `Transfer-Encoding` (a proxy reading the //! last one would frame the request differently; issue #220); `std/http` //! rejects a request with both `Content-Length` and `Transfer-Encoding` //! (400) and any coding other than `chunked` (501), and closes the //! connection after every rejected request. //! //! **A head arriving in pieces** is scanned for its end once //! ([`head_end`]), and parsed once that is found, instead of parsed again //! from its start on every read (ADR 0012, Revision 2). use louise_rt_prims::SMALL_INT; use std::sync::OnceLock; use crate::abi::{Ctx, Value, int}; use crate::int::saturating; use crate::values::{bytes_of, cell, immortal_string, list, string, text}; /// Headers a request may have; a request with more is invalid. const MAX_HEADERS: usize = 64; // Constructor tags of `Head` and `Chunk` (`std/http.lse`). const HEAD_PARTIAL: i64 = 0; const HEAD_INVALID: u16 = 1; const HEAD_COMPLETE: u16 = 2; const CHUNK_PARTIAL: i64 = 0; const CHUNK_INVALID: u16 = 1; const CHUNK_DATA: u16 = 2; const CHUNK_END: u16 = 3; /// The head of a request, parsed from an offset of a buffer. #[derive(Debug, PartialEq)] pub(crate) enum Head<'a> { /// More bytes are needed. Partial, Invalid(String), Complete(Request<'a>), } /// A complete request head (borrowed from the buffer). #[derive(Debug, PartialEq)] pub(crate) struct Request<'a> { pub method: &'a str, pub path: &'a str, /// The minor version (`HTTP/1.version`). pub version: u8, /// Names and raw values, in order. pub headers: Vec<(&'a str, &'a [u8])>, /// The offset in the buffer where the head ends. pub end: usize, pub content_length: Option, } /// Parse the head of the request that starts at offset `at` of `buffer` /// (an offset past the end is the end). /// /// A `Content-Length` must be decimal digits (surrounding whitespace /// aside) below 2^62, and repeating it is allowed only with the same /// value. pub(crate) fn parse_head(buffer: &[u8], at: usize) -> Head<'_> { let at = at.min(buffer.len()); let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; let mut req = httparse::Request::new(&mut headers); let consumed = match req.parse(&buffer[at..]) { Ok(httparse::Status::Partial) => return Head::Partial, Ok(httparse::Status::Complete(n)) => n, Err(e) => return Head::Invalid(e.to_string()), }; let mut content_length = None; for h in req.headers.iter() { if h.name.eq_ignore_ascii_case("content-length") { match (decimal_length(h.value), content_length) { (Some(n), None) => content_length = Some(n), (Some(n), Some(m)) if n == m => {} _ => return Head::Invalid("invalid Content-Length".into()), } } } let codings = req .headers .iter() .filter(|h| h.name.eq_ignore_ascii_case("transfer-encoding")) .count(); if codings > 1 { return Head::Invalid("more than one Transfer-Encoding".into()); } Head::Complete(Request { method: req.method.unwrap_or(""), path: req.path.unwrap_or(""), version: req.version.unwrap_or(1), headers: req.headers.iter().map(|h| (h.name, h.value)).collect(), end: at + consumed, content_length, }) } /// Where the head in `buffer` ends, if its end is at or after `from`: the /// offset just past the empty line that ends it. Lines end in CRLF or in /// a bare LF, as httparse accepts them. A caller scanning what arrives /// piece by piece passes the last 3 bytes it scanned before the new piece, /// so that an end split between two pieces is found. pub(crate) fn head_end(buffer: &[u8], from: usize) -> Option { let from = from.min(buffer.len()); buffer[from..].iter().enumerate().find_map(|(i, &b)| { let i = from + i; if b != b'\n' { return None; } match &buffer[i + 1..] { [b'\n', ..] => Some(i + 2), [b'\r', b'\n', ..] => Some(i + 3), _ => None, } }) } /// A `Content-Length` value: decimal digits only (no sign), a small `Int`, /// once surrounding spaces and tabs are trimmed. Only those (RFC 9110's /// optional whitespace): trimming Unicode whitespace too would read /// `\u{a0}5` as 5, where a proxy in front may not (request smuggling). fn decimal_length(value: &[u8]) -> Option { let value = std::str::from_utf8(value) .unwrap_or("") .trim_matches([' ', '\t']); if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { return None; } // An offset or a length is a small `Int`. value.parse::().ok().filter(|n| SMALL_INT.contains(n)) } /// One chunk of a chunked body, parsed from an offset of a buffer. #[derive(Debug, PartialEq)] pub(crate) enum Chunk { /// The size line, or for the last chunk its trailers, is incomplete. Partial, Invalid(String), /// `size` bytes of data start at offset `start`, then a CRLF (both /// may extend past the buffer). Data { start: usize, size: i64, }, /// The last chunk, whose trailers (ignored) end at offset `end`. End { end: usize, }, } /// Parse the chunk that starts at offset `at` of `buffer` (an offset past /// the end is the end). pub(crate) fn parse_chunk(buffer: &[u8], at: usize) -> Chunk { let at = at.min(buffer.len()); let (line, size) = match httparse::parse_chunk_size(&buffer[at..]) { Ok(httparse::Status::Partial) => return Chunk::Partial, Ok(httparse::Status::Complete(found)) => found, Err(_) => return Chunk::Invalid("invalid chunk size".into()), }; let start = at + line; if size > 0 { return match i64::try_from(size) { Ok(size) if SMALL_INT.contains(&size) => Chunk::Data { start, size }, _ => Chunk::Invalid("chunk too large".into()), }; } let mut trailers = [httparse::EMPTY_HEADER; MAX_HEADERS]; match httparse::parse_headers(&buffer[start..], &mut trailers) { Ok(httparse::Status::Partial) => Chunk::Partial, Ok(httparse::Status::Complete((n, _))) => Chunk::End { end: start + n }, Err(e) => Chunk::Invalid(e.to_string()), } } /// An offset argument: a negative one is 0. /// /// # Safety /// `at` must be a live `Int`. unsafe fn offset(at: Value) -> usize { // SAFETY: forwarded caller guarantee. usize::try_from(unsafe { saturating(at) }).unwrap_or(0) } /// The request header names virtually every request carries, in both /// spellings seen in practice (browsers and curl capitalise; many /// clients, and HTTP/2, lowercase), sorted for the binary search in /// [`interned`]. const COMMON_HEADER_NAMES: [&str; 66] = [ "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Authorization", "Cache-Control", "Connection", "Content-Length", "Content-Type", "Cookie", "DNT", "Date", "Expect", "Forwarded", "Host", "If-Modified-Since", "If-None-Match", "Last-Event-ID", "Origin", "Pragma", "Range", "Referer", "Sec-Fetch-Dest", "Sec-Fetch-Mode", "Sec-Fetch-Site", "Sec-Fetch-User", "TE", "Trailer", "Transfer-Encoding", "Upgrade-Insecure-Requests", "User-Agent", "Via", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "X-Real-Ip", "X-Request-Id", "X-Requested-With", "accept", "accept-encoding", "accept-language", "authorization", "cache-control", "connection", "content-length", "content-type", "cookie", "dnt", "expect", "forwarded", "host", "if-modified-since", "if-none-match", "last-event-id", "origin", "pragma", "range", "referer", "te", "trailer", "transfer-encoding", "user-agent", "via", "x-forwarded-for", "x-request-id", "x-requested-with", ]; /// The index of `name` in [`COMMON_HEADER_NAMES`], if it is one. A /// `match` compiles to a length switch and a few byte compares: cheaper /// than the allocation a hit saves. fn interned_index(name: &str) -> Option { Some(match name { "Accept" => 0, "Accept-Charset" => 1, "Accept-Encoding" => 2, "Accept-Language" => 3, "Authorization" => 4, "Cache-Control" => 5, "Connection" => 6, "Content-Length" => 7, "Content-Type" => 8, "Cookie" => 9, "DNT" => 10, "Date" => 11, "Expect" => 12, "Forwarded" => 13, "Host" => 14, "If-Modified-Since" => 15, "If-None-Match" => 16, "Last-Event-ID" => 17, "Origin" => 18, "Pragma" => 19, "Range" => 20, "Referer" => 21, "Sec-Fetch-Dest" => 22, "Sec-Fetch-Mode" => 23, "Sec-Fetch-Site" => 24, "Sec-Fetch-User" => 25, "TE" => 26, "Trailer" => 27, "Transfer-Encoding" => 28, "Upgrade-Insecure-Requests" => 29, "User-Agent" => 30, "Via" => 31, "X-Forwarded-For" => 32, "X-Forwarded-Host" => 33, "X-Forwarded-Proto" => 34, "X-Real-Ip" => 35, "X-Request-Id" => 36, "X-Requested-With" => 37, "accept" => 38, "accept-encoding" => 39, "accept-language" => 40, "authorization" => 41, "cache-control" => 42, "connection" => 43, "content-length" => 44, "content-type" => 45, "cookie" => 46, "dnt" => 47, "expect" => 48, "forwarded" => 49, "host" => 50, "if-modified-since" => 51, "if-none-match" => 52, "last-event-id" => 53, "origin" => 54, "pragma" => 55, "range" => 56, "referer" => 57, "te" => 58, "trailer" => 59, "transfer-encoding" => 60, "user-agent" => 61, "via" => 62, "x-forwarded-for" => 63, "x-request-id" => 64, "x-requested-with" => 65, _ => return None, }) } /// `name` as a Louise string: a shared immortal one when it is a common /// name spelled a common way (no allocation), else a fresh string. The /// string holds the name's bytes exactly as received either way. fn header_name(ctx: *mut Ctx, name: &str) -> Value { static NAMES: OnceLock> = OnceLock::new(); let names = NAMES.get_or_init(|| { COMMON_HEADER_NAMES .iter() .map(|n| immortal_string(n)) .collect() }); match interned_index(name) { Some(i) => names[i], None => string(ctx, name), } } /// `parse_head(buffer, at)` (`std/http`): the Rust `parse_head` as a /// `Head`: `Partial`, `Invalid(reason)`, or `Complete(method, path, /// version, headers, end, content_length)`, where `content_length` is -1 /// when absent. Header values that are not UTF-8 have invalid bytes /// replaced. /// /// # Safety /// `buffer` must be live `Bytes`; `at` a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_http_parse_request(ctx: *mut Ctx, buffer: Value, at: Value) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let (bytes, at) = unsafe { (bytes_of(buffer), offset(at)) }; match parse_head(bytes, at) { Head::Partial => int(HEAD_PARTIAL), Head::Invalid(reason) => cell(ctx, HEAD_INVALID, &[string(ctx, &reason)]), Head::Complete(req) => { let headers = list( ctx, req.headers.iter().map(|(name, value)| { let value = String::from_utf8_lossy(value); cell(ctx, 0, &[header_name(ctx, name), string(ctx, &value)]) }), ); cell( ctx, HEAD_COMPLETE, &[ string(ctx, req.method), string(ctx, req.path), int(i64::from(req.version)), headers, int(req.end as i64), int(req.content_length.unwrap_or(-1)), ], ) } } } /// `parse_head_end(buffer, from)` (`std/http`): the Rust [`head_end`], or /// -1 when the end is not there yet. /// /// # Safety /// `buffer` must be live `Bytes`; `from` a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_http_parse_head_end( _ctx: *mut Ctx, buffer: Value, from: Value, ) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let (bytes, from) = unsafe { (bytes_of(buffer), offset(from)) }; int(head_end(bytes, from).map_or(-1, |end| end as i64)) } /// `parse_chunk(buffer, at)` (`std/http`): the Rust `parse_chunk` as a /// `Chunk`: `ChunkPartial`, `ChunkInvalid(reason)`, `ChunkData(start, /// size)` or `ChunkEnd(end)`. /// /// # Safety /// `buffer` must be live `Bytes`; `at` a live `Int`. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_http_parse_chunk(ctx: *mut Ctx, buffer: Value, at: Value) -> Value { // SAFETY: caller guarantees live `Bytes` and a live Int. let (bytes, at) = unsafe { (bytes_of(buffer), offset(at)) }; match parse_chunk(bytes, at) { Chunk::Partial => int(CHUNK_PARTIAL), Chunk::Invalid(reason) => cell(ctx, CHUNK_INVALID, &[string(ctx, &reason)]), Chunk::Data { start, size } => cell(ctx, CHUNK_DATA, &[int(start as i64), int(size)]), Chunk::End { end } => cell(ctx, CHUNK_END, &[int(end as i64)]), } } /// `form(body)` (`std/http`): the fields of a form-encoded body or query /// string, parsed in one pass (`louise_rt_prims::query_params`). /// /// # Safety /// `s` must be a live string. #[unsafe(no_mangle)] pub unsafe extern "C" fn tl_http_parse_query(ctx: *mut Ctx, s: Value) -> Value { // SAFETY: caller guarantees a live string. let pairs = louise_rt_prims::query_params(unsafe { text(s) }); list( ctx, pairs .iter() .map(|(k, v)| cell(ctx, 0, &[string(ctx, k), string(ctx, v)])), ) } #[cfg(test)] mod tests { use super::*; fn head(text: &str) -> Head<'_> { parse_head(text.as_bytes(), 0) } fn complete(text: &str) -> Request<'_> { match head(text) { Head::Complete(req) => req, other => panic!("{text:?}: {other:?}"), } } fn invalid(text: &str) -> String { match head(text) { Head::Invalid(reason) => reason, other => panic!("{text:?} was accepted: {other:?}"), } } #[test] fn a_complete_head_and_where_it_ends() { let text = "POST /a?b=1 HTTP/1.0\r\nHost: x\r\nContent-Length: 5\r\n\r\nhello"; let req = complete(text); assert_eq!((req.method, req.path, req.version), ("POST", "/a?b=1", 0)); assert_eq!( req.headers, [("Host", &b"x"[..]), ("Content-Length", &b"5"[..])] ); assert_eq!((req.end, req.content_length), (text.len() - 5, Some(5))); assert_eq!(complete("GET / HTTP/1.1\r\n\r\n").content_length, None); } #[test] fn a_head_is_read_from_an_offset() { let first = "GET /1 HTTP/1.1\r\n\r\n"; let both = format!("{first}GET /2 HTTP/1.1\r\nHost: x\r\n\r\n"); let Head::Complete(req) = parse_head(both.as_bytes(), first.len()) else { panic!("the second request"); }; assert_eq!((req.path, req.end), ("/2", both.len())); // At the end, or past it: nothing yet. assert_eq!(parse_head(both.as_bytes(), both.len()), Head::Partial); assert_eq!(parse_head(both.as_bytes(), usize::MAX), Head::Partial); } #[test] fn an_incomplete_head_needs_more() { for text in [ "", "GET", "GET / HTTP/1.1\r\n", "GET / HTTP/1.1\r\nHost: x\r\n", ] { assert_eq!(head(text), Head::Partial, "{text:?}"); } } #[test] fn malformed_heads_are_invalid() { for text in [ "GET / HTTP/2.0\r\n\r\n", "GET / HTTP/1.1\r\n\r\n", "GET / HTTP/1.1\r\nNo colon\r\n\r\n", "GET / HTTP/1.1\r\nBad\x01Name: x\r\n\r\n", // Whitespace before the colon: proxies disagree on what it // means, so it is refused. "GET / HTTP/1.1\r\nContent-Length : 5\r\n\r\n", ] { invalid(text); } let many = format!( "GET / HTTP/1.1\r\n{}\r\n", "X: 1\r\n".repeat(MAX_HEADERS + 1) ); assert_eq!(invalid(&many), "too many headers"); let enough = format!("GET / HTTP/1.1\r\n{}\r\n", "X: 1\r\n".repeat(MAX_HEADERS)); assert_eq!(complete(&enough).headers.len(), MAX_HEADERS); } #[test] fn content_length_must_be_decimal() { for value in [ "", "-1", "+5", "0x10", "5 5", "5,5", "1e3", "٣", // Whitespace other than spaces and tabs: a no-break space. "\u{a0}5", "5\u{a0}", // 2^62 and beyond: not a small Int. "4611686018427387904", "99999999999999999999999", ] { let text = format!("POST / HTTP/1.1\r\nContent-Length: {value}\r\n\r\n"); assert_eq!(invalid(&text), "invalid Content-Length", "{value:?}"); } for (value, n) in [("0", 0), ("007", 7), ("4611686018427387903", (1 << 62) - 1)] { let text = format!("POST / HTTP/1.1\r\ncontent-LENGTH: {value}\r\n\r\n"); assert_eq!(complete(&text).content_length, Some(n), "{value:?}"); } let text = "POST / HTTP/1.1\r\nContent-Length: \t 12 \r\n\r\n"; assert_eq!(complete(text).content_length, Some(12)); let text = b"POST / HTTP/1.1\r\nContent-Length: 1\xff\r\n\r\n"; assert!(matches!(parse_head(text, 0), Head::Invalid(_))); // Control characters (a form feed, a vertical tab) never get this // far: httparse rejects the header value. for value in ["\u{c}5", "\u{b}5"] { let text = format!("POST / HTTP/1.1\r\nContent-Length: {value}\r\n\r\n"); assert!( matches!(parse_head(text.as_bytes(), 0), Head::Invalid(_)), "{value:?}" ); } } /// Two lengths that disagree would let the server and a proxy in /// front of it split the stream differently. #[test] fn repeated_content_lengths_must_agree() { let same = "POST / HTTP/1.1\r\nContent-Length: 5\r\ncontent-length: 05\r\n\r\n"; assert_eq!(complete(same).content_length, Some(5)); for text in [ "POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: 6\r\n\r\n", "POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: x\r\n\r\n", "POST / HTTP/1.1\r\nContent-Length: 0\r\nContent-Length: \r\n\r\n", ] { assert_eq!(invalid(text), "invalid Content-Length", "{text:?}"); } } /// Both framings are reported as they are: `std/http` refuses the /// request (400). #[test] fn transfer_encoding_is_left_to_std_http() { let text = "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n"; let req = complete(text); assert_eq!(req.content_length, Some(3)); assert_eq!(req.headers[0], ("Transfer-Encoding", &b"chunked"[..])); } /// A proxy that reads the last `Transfer-Encoding` would frame this /// request differently from one that reads the first (issue #220). #[test] fn repeated_transfer_encodings_are_invalid() { let text = "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\ntransfer-encoding: identity\r\n\r\n"; assert_eq!(invalid(text), "more than one Transfer-Encoding"); } #[test] fn the_end_of_a_head_is_found_from_an_offset() { assert_eq!( head_end(b"GET / HTTP/1.1\r\nHost: x\r\n\r\nbody", 0), Some(27) ); assert_eq!(head_end(b"GET / HTTP/1.1\nHost: x\n\nbody", 0), Some(24)); // Mixed line ends, as httparse reads them. assert_eq!(head_end(b"GET / HTTP/1.1\nHost: x\r\n\n", 0), Some(25)); assert_eq!(head_end(b"GET / HTTP/1.1\r\nHost: x\r\n", 0), None); assert_eq!(head_end(b"", 0), None); // An end split between two pieces: the caller scans the last 3 // bytes of the first with the second. let piece = b"Host: x\r\n\r"; let next = b"\nbody"; let mut window = piece[piece.len() - 3..].to_vec(); window.extend_from_slice(next); assert_eq!(head_end(&window, 0), Some(4)); // From an offset: an end before it is not found. assert_eq!(head_end(b"a\n\nb\n\n", 3), Some(6)); assert_eq!(head_end(b"a\n\n", 9), None); // Each head ends where httparse says it does. for text in [ "GET / HTTP/1.1\r\nHost: x\r\n\r\n", "GET / HTTP/1.1\nA: b\n\n", ] { assert_eq!(head_end(text.as_bytes(), 0), Some(complete(text).end)); } } #[test] fn header_values_keep_their_bytes() { let text = b"GET / HTTP/1.1\r\nX: caf\xc3\xa9 \xff\r\n\r\n"; let Head::Complete(req) = parse_head(text, 0) else { panic!("a valid head"); }; assert_eq!(req.headers, [("X", &b"caf\xc3\xa9 \xff"[..])]); } #[test] fn the_common_header_names_table_is_sorted() { assert!(COMMON_HEADER_NAMES.is_sorted()); assert!( COMMON_HEADER_NAMES .iter() .all(|n| n.bytes().all(|b| b.is_ascii_graphic())) ); } #[test] fn chunks_of_data_and_where_they_start() { assert_eq!( parse_chunk(b"5\r\nhello\r\n", 0), Chunk::Data { start: 3, size: 5 } ); // An extension is skipped; sizes are hexadecimal, in any case. assert_eq!( parse_chunk(b"xx1aF;name=value\r\n", 2), Chunk::Data { start: 18, size: 0x1af } ); // The data may extend past the buffer. assert_eq!( parse_chunk(b"ff\r\n", 0), Chunk::Data { start: 4, size: 255 } ); } #[test] fn the_last_chunk_ends_after_its_trailers() { assert_eq!(parse_chunk(b"0\r\n\r\nGET", 0), Chunk::End { end: 5 }); let trailed = b"0\r\nX-Sum: 1\r\n\r\n"; assert_eq!(parse_chunk(trailed, 0), Chunk::End { end: trailed.len() }); assert_eq!(parse_chunk(b"0\r\n", 0), Chunk::Partial); assert_eq!(parse_chunk(b"0\r\nX-Sum: 1\r\n", 0), Chunk::Partial); assert!(matches!( parse_chunk(b"0\r\nbad trailer\r\n\r\n", 0), Chunk::Invalid(_) )); } #[test] fn incomplete_and_invalid_chunk_sizes() { for text in [&b""[..], b"5", b"5\r", b"5;ext"] { assert_eq!(parse_chunk(text, 0), Chunk::Partial, "{text:?}"); } assert_eq!(parse_chunk(b"5\r\n", 3), Chunk::Partial); assert_eq!(parse_chunk(b"5\r\n", 99), Chunk::Partial); for text in [ &b"x\r\n"[..], b"-5\r\n", b" 5\r\n", b"5\n\n", b"ffffffffffffffffff\r\n", ] { assert_eq!( parse_chunk(text, 0), Chunk::Invalid("invalid chunk size".into()), "{text:?}" ); } // 2^62 and beyond: not a small Int. for text in [&b"4000000000000000\r\n"[..], b"ffffffffffffffff\r\n"] { assert_eq!( parse_chunk(text, 0), Chunk::Invalid("chunk too large".into()) ); } assert_eq!( parse_chunk(b"3fffffffffffffff\r\n", 0), Chunk::Data { start: 18, size: (1 << 62) - 1 } ); } /// The externs build `std/http`'s `Head` and `Chunk` values. unsafe extern "C" fn builds_std_http_values(ctx: *mut Ctx) -> Value { use crate::abi::{Block, UNIT, int_get}; use crate::heap::drop_value; use crate::values::{bytes_from, list_items, text}; let field = |v: Value, i: usize| { // SAFETY: the test reads fields of the cells the externs made. unsafe { *Block::fields_ptr(v as *mut Block).add(i) } }; // SAFETY: as above. let tag = |v: Value| unsafe { (*(v as *mut Block)).header.tag }; // SAFETY: every value is owned by this test. unsafe { let head = bytes_from(ctx, b"GET /x HTTP/1.1\r\nA: b\xff\r\n\r\n"); let complete = tl_http_parse_request(ctx, head, int(0)); assert_eq!(tag(complete), HEAD_COMPLETE); assert_eq!( (text(field(complete, 0)), text(field(complete, 1))), ("GET", "/x") ); assert_eq!(int_get(field(complete, 2)), 1); let header = list_items(field(complete, 3)).next().unwrap(); assert_eq!((tag(header), text(field(header, 1))), (0, "b\u{fffd}")); assert_eq!(field(complete, 4), int(26)); assert_eq!(field(complete, 5), int(-1)); // A negative offset is 0; one past the end is the end. let again = tl_http_parse_request(ctx, head, int(-5)); assert_eq!(field(again, 4), int(26)); let bad = tl_http_parse_request(ctx, head, int(3)); assert_eq!(tag(bad), HEAD_INVALID); assert_eq!(tl_http_parse_request(ctx, head, int(99)), int(HEAD_PARTIAL)); let chunks = bytes_from(ctx, b"5\r\nhello\r\n0\r\n\r\n"); let data = tl_http_parse_chunk(ctx, chunks, int(0)); assert_eq!(tag(data), CHUNK_DATA); assert_eq!((field(data, 0), field(data, 1)), (int(3), int(5))); let end = tl_http_parse_chunk(ctx, chunks, int(10)); assert_eq!((tag(end), field(end, 0)), (CHUNK_END, int(15))); let invalid = tl_http_parse_chunk(ctx, chunks, int(4)); assert_eq!(tag(invalid), CHUNK_INVALID); let partial = tl_http_parse_chunk(ctx, chunks, int(99)); assert_eq!(partial, int(CHUNK_PARTIAL)); // A common name is the same immortal string on every parse; // an uncommon one is fresh each time, its bytes exact. let common = bytes_from(ctx, b"GET / HTTP/1.1\r\nHost: a\r\nX-Weird: b\r\n\r\n"); let first = tl_http_parse_request(ctx, common, int(0)); let second = tl_http_parse_request(ctx, common, int(0)); let name = |v: Value, i: usize| { let mut items = list_items(field(v, 3)); let pair = items.nth(i).unwrap(); field(pair, 0) }; assert_eq!(name(first, 0), name(second, 0)); assert_eq!(text(name(first, 0)), "Host"); assert_ne!(name(first, 1), name(second, 1)); assert_eq!(text(name(first, 1)), "X-Weird"); for v in [ head, complete, again, bad, chunks, data, end, invalid, common, first, second, ] { drop_value(ctx, v); } } assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); UNIT } #[test] fn externs_build_std_http_values() { // SAFETY: the test follows the generated-code convention. let code = unsafe { crate::sched::run_test_actor(builds_std_http_values) }; assert_eq!(code, 0); } }