
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1201 · main · 9 min 57 s
1Étoiles
0Forks
0Issues
| 1 | //! HTTP/1.x framing for `std/http`: request heads and the sizes of |
| 2 | //! chunked bodies, parsed by httparse (a port of picohttpparser). |
| 3 | //! |
| 4 | //! Both parsers read a buffer from an offset and return offsets, so a |
| 5 | //! buffer holding several pipelined requests or many small chunks is never |
| 6 | //! copied per item (`std/http` slices what it keeps). |
| 7 | //! |
| 8 | //! The parsing is plain Rust over `&[u8]` (`parse_head`, `parse_chunk`, |
| 9 | //! unit-tested below). The externs only turn its result into `std/http`'s |
| 10 | //! `Head` and `Chunk` values, whose constructor order the `HEAD_*` and |
| 11 | //! `CHUNK_*` constants follow. |
| 12 | //! |
| 13 | //! **Request smuggling.** On a kept-alive connection, a misread body |
| 14 | //! length makes the server read part of a body as the next request. This |
| 15 | //! module rejects a `Content-Length` that is not a decimal number, two |
| 16 | //! that differ, and more than one `Transfer-Encoding` (a proxy reading the |
| 17 | //! last one would frame the request differently; issue #220); `std/http` |
| 18 | //! rejects a request with both `Content-Length` and `Transfer-Encoding` |
| 19 | //! (400) and any coding other than `chunked` (501), and closes the |
| 20 | //! connection after every rejected request. |
| 21 | //! |
| 22 | //! **A head arriving in pieces** is scanned for its end once |
| 23 | //! ([`head_end`]), and parsed once that is found, instead of parsed again |
| 24 | //! from its start on every read (ADR 0012, Revision 2). |
| 25 | |
| 26 | use louise_rt_prims::SMALL_INT; |
| 27 | |
| 28 | use std::sync::OnceLock; |
| 29 | |
| 30 | use crate::abi::{Ctx, Value, int}; |
| 31 | use crate::int::saturating; |
| 32 | use crate::values::{bytes_of, cell, immortal_string, list, string, text}; |
| 33 | |
| 34 | /// Headers a request may have; a request with more is invalid. |
| 35 | const MAX_HEADERS: usize = 64; |
| 36 | |
| 37 | // Constructor tags of `Head` and `Chunk` (`std/http.lse`). |
| 38 | const HEAD_PARTIAL: i64 = 0; |
| 39 | const HEAD_INVALID: u16 = 1; |
| 40 | const HEAD_COMPLETE: u16 = 2; |
| 41 | const CHUNK_PARTIAL: i64 = 0; |
| 42 | const CHUNK_INVALID: u16 = 1; |
| 43 | const CHUNK_DATA: u16 = 2; |
| 44 | const CHUNK_END: u16 = 3; |
| 45 | |
| 46 | /// The head of a request, parsed from an offset of a buffer. |
| 47 | #[derive(Debug, PartialEq)] |
| 48 | pub(crate) enum Head<'a> { |
| 49 | /// More bytes are needed. |
| 50 | Partial, |
| 51 | Invalid(String), |
| 52 | Complete(Request<'a>), |
| 53 | } |
| 54 | |
| 55 | /// A complete request head (borrowed from the buffer). |
| 56 | #[derive(Debug, PartialEq)] |
| 57 | pub(crate) struct Request<'a> { |
| 58 | pub method: &'a str, |
| 59 | pub path: &'a str, |
| 60 | /// The minor version (`HTTP/1.version`). |
| 61 | pub version: u8, |
| 62 | /// Names and raw values, in order. |
| 63 | pub headers: Vec<(&'a str, &'a [u8])>, |
| 64 | /// The offset in the buffer where the head ends. |
| 65 | pub end: usize, |
| 66 | pub content_length: Option<i64>, |
| 67 | } |
| 68 | |
| 69 | /// Parse the head of the request that starts at offset `at` of `buffer` |
| 70 | /// (an offset past the end is the end). |
| 71 | /// |
| 72 | /// A `Content-Length` must be decimal digits (surrounding whitespace |
| 73 | /// aside) below 2^62, and repeating it is allowed only with the same |
| 74 | /// value. |
| 75 | pub(crate) fn parse_head(buffer: &[u8], at: usize) -> Head<'_> { |
| 76 | let at = at.min(buffer.len()); |
| 77 | let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; |
| 78 | let mut req = httparse::Request::new(&mut headers); |
| 79 | let consumed = match req.parse(&buffer[at..]) { |
| 80 | Ok(httparse::Status::Partial) => return Head::Partial, |
| 81 | Ok(httparse::Status::Complete(n)) => n, |
| 82 | Err(e) => return Head::Invalid(e.to_string()), |
| 83 | }; |
| 84 | let mut content_length = None; |
| 85 | for h in req.headers.iter() { |
| 86 | if h.name.eq_ignore_ascii_case("content-length") { |
| 87 | match (decimal_length(h.value), content_length) { |
| 88 | (Some(n), None) => content_length = Some(n), |
| 89 | (Some(n), Some(m)) if n == m => {} |
| 90 | _ => return Head::Invalid("invalid Content-Length".into()), |
| 91 | } |
| 92 | } |
| 93 | } |
| 94 | let codings = req |
| 95 | .headers |
| 96 | .iter() |
| 97 | .filter(|h| h.name.eq_ignore_ascii_case("transfer-encoding")) |
| 98 | .count(); |
| 99 | if codings > 1 { |
| 100 | return Head::Invalid("more than one Transfer-Encoding".into()); |
| 101 | } |
| 102 | Head::Complete(Request { |
| 103 | method: req.method.unwrap_or(""), |
| 104 | path: req.path.unwrap_or(""), |
| 105 | version: req.version.unwrap_or(1), |
| 106 | headers: req.headers.iter().map(|h| (h.name, h.value)).collect(), |
| 107 | end: at + consumed, |
| 108 | content_length, |
| 109 | }) |
| 110 | } |
| 111 | |
| 112 | /// Where the head in `buffer` ends, if its end is at or after `from`: the |
| 113 | /// offset just past the empty line that ends it. Lines end in CRLF or in |
| 114 | /// a bare LF, as httparse accepts them. A caller scanning what arrives |
| 115 | /// piece by piece passes the last 3 bytes it scanned before the new piece, |
| 116 | /// so that an end split between two pieces is found. |
| 117 | pub(crate) fn head_end(buffer: &[u8], from: usize) -> Option<usize> { |
| 118 | let from = from.min(buffer.len()); |
| 119 | buffer[from..].iter().enumerate().find_map(|(i, &b)| { |
| 120 | let i = from + i; |
| 121 | if b != b'\n' { |
| 122 | return None; |
| 123 | } |
| 124 | match &buffer[i + 1..] { |
| 125 | [b'\n', ..] => Some(i + 2), |
| 126 | [b'\r', b'\n', ..] => Some(i + 3), |
| 127 | _ => None, |
| 128 | } |
| 129 | }) |
| 130 | } |
| 131 | |
| 132 | /// A `Content-Length` value: decimal digits only (no sign), a small `Int`, |
| 133 | /// once surrounding spaces and tabs are trimmed. Only those (RFC 9110's |
| 134 | /// optional whitespace): trimming Unicode whitespace too would read |
| 135 | /// `\u{a0}5` as 5, where a proxy in front may not (request smuggling). |
| 136 | fn decimal_length(value: &[u8]) -> Option<i64> { |
| 137 | let value = std::str::from_utf8(value) |
| 138 | .unwrap_or("") |
| 139 | .trim_matches([' ', '\t']); |
| 140 | if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { |
| 141 | return None; |
| 142 | } |
| 143 | // An offset or a length is a small `Int`. |
| 144 | value.parse::<i64>().ok().filter(|n| SMALL_INT.contains(n)) |
| 145 | } |
| 146 | |
| 147 | /// One chunk of a chunked body, parsed from an offset of a buffer. |
| 148 | #[derive(Debug, PartialEq)] |
| 149 | pub(crate) enum Chunk { |
| 150 | /// The size line, or for the last chunk its trailers, is incomplete. |
| 151 | Partial, |
| 152 | Invalid(String), |
| 153 | /// `size` bytes of data start at offset `start`, then a CRLF (both |
| 154 | /// may extend past the buffer). |
| 155 | Data { |
| 156 | start: usize, |
| 157 | size: i64, |
| 158 | }, |
| 159 | /// The last chunk, whose trailers (ignored) end at offset `end`. |
| 160 | End { |
| 161 | end: usize, |
| 162 | }, |
| 163 | } |
| 164 | |
| 165 | /// Parse the chunk that starts at offset `at` of `buffer` (an offset past |
| 166 | /// the end is the end). |
| 167 | pub(crate) fn parse_chunk(buffer: &[u8], at: usize) -> Chunk { |
| 168 | let at = at.min(buffer.len()); |
| 169 | let (line, size) = match httparse::parse_chunk_size(&buffer[at..]) { |
| 170 | Ok(httparse::Status::Partial) => return Chunk::Partial, |
| 171 | Ok(httparse::Status::Complete(found)) => found, |
| 172 | Err(_) => return Chunk::Invalid("invalid chunk size".into()), |
| 173 | }; |
| 174 | let start = at + line; |
| 175 | if size > 0 { |
| 176 | return match i64::try_from(size) { |
| 177 | Ok(size) if SMALL_INT.contains(&size) => Chunk::Data { start, size }, |
| 178 | _ => Chunk::Invalid("chunk too large".into()), |
| 179 | }; |
| 180 | } |
| 181 | let mut trailers = [httparse::EMPTY_HEADER; MAX_HEADERS]; |
| 182 | match httparse::parse_headers(&buffer[start..], &mut trailers) { |
| 183 | Ok(httparse::Status::Partial) => Chunk::Partial, |
| 184 | Ok(httparse::Status::Complete((n, _))) => Chunk::End { end: start + n }, |
| 185 | Err(e) => Chunk::Invalid(e.to_string()), |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | /// An offset argument: a negative one is 0. |
| 190 | /// |
| 191 | /// # Safety |
| 192 | /// `at` must be a live `Int`. |
| 193 | unsafe fn offset(at: Value) -> usize { |
| 194 | // SAFETY: forwarded caller guarantee. |
| 195 | usize::try_from(unsafe { saturating(at) }).unwrap_or(0) |
| 196 | } |
| 197 | |
| 198 | /// The request header names virtually every request carries, in both |
| 199 | /// spellings seen in practice (browsers and curl capitalise; many |
| 200 | /// clients, and HTTP/2, lowercase), sorted for the binary search in |
| 201 | /// [`interned`]. |
| 202 | const COMMON_HEADER_NAMES: [&str; 66] = [ |
| 203 | "Accept", |
| 204 | "Accept-Charset", |
| 205 | "Accept-Encoding", |
| 206 | "Accept-Language", |
| 207 | "Authorization", |
| 208 | "Cache-Control", |
| 209 | "Connection", |
| 210 | "Content-Length", |
| 211 | "Content-Type", |
| 212 | "Cookie", |
| 213 | "DNT", |
| 214 | "Date", |
| 215 | "Expect", |
| 216 | "Forwarded", |
| 217 | "Host", |
| 218 | "If-Modified-Since", |
| 219 | "If-None-Match", |
| 220 | "Last-Event-ID", |
| 221 | "Origin", |
| 222 | "Pragma", |
| 223 | "Range", |
| 224 | "Referer", |
| 225 | "Sec-Fetch-Dest", |
| 226 | "Sec-Fetch-Mode", |
| 227 | "Sec-Fetch-Site", |
| 228 | "Sec-Fetch-User", |
| 229 | "TE", |
| 230 | "Trailer", |
| 231 | "Transfer-Encoding", |
| 232 | "Upgrade-Insecure-Requests", |
| 233 | "User-Agent", |
| 234 | "Via", |
| 235 | "X-Forwarded-For", |
| 236 | "X-Forwarded-Host", |
| 237 | "X-Forwarded-Proto", |
| 238 | "X-Real-Ip", |
| 239 | "X-Request-Id", |
| 240 | "X-Requested-With", |
| 241 | "accept", |
| 242 | "accept-encoding", |
| 243 | "accept-language", |
| 244 | "authorization", |
| 245 | "cache-control", |
| 246 | "connection", |
| 247 | "content-length", |
| 248 | "content-type", |
| 249 | "cookie", |
| 250 | "dnt", |
| 251 | "expect", |
| 252 | "forwarded", |
| 253 | "host", |
| 254 | "if-modified-since", |
| 255 | "if-none-match", |
| 256 | "last-event-id", |
| 257 | "origin", |
| 258 | "pragma", |
| 259 | "range", |
| 260 | "referer", |
| 261 | "te", |
| 262 | "trailer", |
| 263 | "transfer-encoding", |
| 264 | "user-agent", |
| 265 | "via", |
| 266 | "x-forwarded-for", |
| 267 | "x-request-id", |
| 268 | "x-requested-with", |
| 269 | ]; |
| 270 | |
| 271 | /// The index of `name` in [`COMMON_HEADER_NAMES`], if it is one. A |
| 272 | /// `match` compiles to a length switch and a few byte compares: cheaper |
| 273 | /// than the allocation a hit saves. |
| 274 | fn interned_index(name: &str) -> Option<usize> { |
| 275 | Some(match name { |
| 276 | "Accept" => 0, |
| 277 | "Accept-Charset" => 1, |
| 278 | "Accept-Encoding" => 2, |
| 279 | "Accept-Language" => 3, |
| 280 | "Authorization" => 4, |
| 281 | "Cache-Control" => 5, |
| 282 | "Connection" => 6, |
| 283 | "Content-Length" => 7, |
| 284 | "Content-Type" => 8, |
| 285 | "Cookie" => 9, |
| 286 | "DNT" => 10, |
| 287 | "Date" => 11, |
| 288 | "Expect" => 12, |
| 289 | "Forwarded" => 13, |
| 290 | "Host" => 14, |
| 291 | "If-Modified-Since" => 15, |
| 292 | "If-None-Match" => 16, |
| 293 | "Last-Event-ID" => 17, |
| 294 | "Origin" => 18, |
| 295 | "Pragma" => 19, |
| 296 | "Range" => 20, |
| 297 | "Referer" => 21, |
| 298 | "Sec-Fetch-Dest" => 22, |
| 299 | "Sec-Fetch-Mode" => 23, |
| 300 | "Sec-Fetch-Site" => 24, |
| 301 | "Sec-Fetch-User" => 25, |
| 302 | "TE" => 26, |
| 303 | "Trailer" => 27, |
| 304 | "Transfer-Encoding" => 28, |
| 305 | "Upgrade-Insecure-Requests" => 29, |
| 306 | "User-Agent" => 30, |
| 307 | "Via" => 31, |
| 308 | "X-Forwarded-For" => 32, |
| 309 | "X-Forwarded-Host" => 33, |
| 310 | "X-Forwarded-Proto" => 34, |
| 311 | "X-Real-Ip" => 35, |
| 312 | "X-Request-Id" => 36, |
| 313 | "X-Requested-With" => 37, |
| 314 | "accept" => 38, |
| 315 | "accept-encoding" => 39, |
| 316 | "accept-language" => 40, |
| 317 | "authorization" => 41, |
| 318 | "cache-control" => 42, |
| 319 | "connection" => 43, |
| 320 | "content-length" => 44, |
| 321 | "content-type" => 45, |
| 322 | "cookie" => 46, |
| 323 | "dnt" => 47, |
| 324 | "expect" => 48, |
| 325 | "forwarded" => 49, |
| 326 | "host" => 50, |
| 327 | "if-modified-since" => 51, |
| 328 | "if-none-match" => 52, |
| 329 | "last-event-id" => 53, |
| 330 | "origin" => 54, |
| 331 | "pragma" => 55, |
| 332 | "range" => 56, |
| 333 | "referer" => 57, |
| 334 | "te" => 58, |
| 335 | "trailer" => 59, |
| 336 | "transfer-encoding" => 60, |
| 337 | "user-agent" => 61, |
| 338 | "via" => 62, |
| 339 | "x-forwarded-for" => 63, |
| 340 | "x-request-id" => 64, |
| 341 | "x-requested-with" => 65, |
| 342 | _ => return None, |
| 343 | }) |
| 344 | } |
| 345 | |
| 346 | /// `name` as a Louise string: a shared immortal one when it is a common |
| 347 | /// name spelled a common way (no allocation), else a fresh string. The |
| 348 | /// string holds the name's bytes exactly as received either way. |
| 349 | fn header_name(ctx: *mut Ctx, name: &str) -> Value { |
| 350 | static NAMES: OnceLock<Vec<Value>> = OnceLock::new(); |
| 351 | let names = NAMES.get_or_init(|| { |
| 352 | COMMON_HEADER_NAMES |
| 353 | .iter() |
| 354 | .map(|n| immortal_string(n)) |
| 355 | .collect() |
| 356 | }); |
| 357 | match interned_index(name) { |
| 358 | Some(i) => names[i], |
| 359 | None => string(ctx, name), |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | /// `parse_head(buffer, at)` (`std/http`): the Rust `parse_head` as a |
| 364 | /// `Head`: `Partial`, `Invalid(reason)`, or `Complete(method, path, |
| 365 | /// version, headers, end, content_length)`, where `content_length` is -1 |
| 366 | /// when absent. Header values that are not UTF-8 have invalid bytes |
| 367 | /// replaced. |
| 368 | /// |
| 369 | /// # Safety |
| 370 | /// `buffer` must be live `Bytes`; `at` a live `Int`. |
| 371 | #[unsafe(no_mangle)] |
| 372 | pub unsafe extern "C" fn tl_http_parse_request(ctx: *mut Ctx, buffer: Value, at: Value) -> Value { |
| 373 | // SAFETY: caller guarantees live `Bytes` and a live Int. |
| 374 | let (bytes, at) = unsafe { (bytes_of(buffer), offset(at)) }; |
| 375 | match parse_head(bytes, at) { |
| 376 | Head::Partial => int(HEAD_PARTIAL), |
| 377 | Head::Invalid(reason) => cell(ctx, HEAD_INVALID, &[string(ctx, &reason)]), |
| 378 | Head::Complete(req) => { |
| 379 | let headers = list( |
| 380 | ctx, |
| 381 | req.headers.iter().map(|(name, value)| { |
| 382 | let value = String::from_utf8_lossy(value); |
| 383 | cell(ctx, 0, &[header_name(ctx, name), string(ctx, &value)]) |
| 384 | }), |
| 385 | ); |
| 386 | cell( |
| 387 | ctx, |
| 388 | HEAD_COMPLETE, |
| 389 | &[ |
| 390 | string(ctx, req.method), |
| 391 | string(ctx, req.path), |
| 392 | int(i64::from(req.version)), |
| 393 | headers, |
| 394 | int(req.end as i64), |
| 395 | int(req.content_length.unwrap_or(-1)), |
| 396 | ], |
| 397 | ) |
| 398 | } |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | /// `parse_head_end(buffer, from)` (`std/http`): the Rust [`head_end`], or |
| 403 | /// -1 when the end is not there yet. |
| 404 | /// |
| 405 | /// # Safety |
| 406 | /// `buffer` must be live `Bytes`; `from` a live `Int`. |
| 407 | #[unsafe(no_mangle)] |
| 408 | pub unsafe extern "C" fn tl_http_parse_head_end( |
| 409 | _ctx: *mut Ctx, |
| 410 | buffer: Value, |
| 411 | from: Value, |
| 412 | ) -> Value { |
| 413 | // SAFETY: caller guarantees live `Bytes` and a live Int. |
| 414 | let (bytes, from) = unsafe { (bytes_of(buffer), offset(from)) }; |
| 415 | int(head_end(bytes, from).map_or(-1, |end| end as i64)) |
| 416 | } |
| 417 | |
| 418 | /// `parse_chunk(buffer, at)` (`std/http`): the Rust `parse_chunk` as a |
| 419 | /// `Chunk`: `ChunkPartial`, `ChunkInvalid(reason)`, `ChunkData(start, |
| 420 | /// size)` or `ChunkEnd(end)`. |
| 421 | /// |
| 422 | /// # Safety |
| 423 | /// `buffer` must be live `Bytes`; `at` a live `Int`. |
| 424 | #[unsafe(no_mangle)] |
| 425 | pub unsafe extern "C" fn tl_http_parse_chunk(ctx: *mut Ctx, buffer: Value, at: Value) -> Value { |
| 426 | // SAFETY: caller guarantees live `Bytes` and a live Int. |
| 427 | let (bytes, at) = unsafe { (bytes_of(buffer), offset(at)) }; |
| 428 | match parse_chunk(bytes, at) { |
| 429 | Chunk::Partial => int(CHUNK_PARTIAL), |
| 430 | Chunk::Invalid(reason) => cell(ctx, CHUNK_INVALID, &[string(ctx, &reason)]), |
| 431 | Chunk::Data { start, size } => cell(ctx, CHUNK_DATA, &[int(start as i64), int(size)]), |
| 432 | Chunk::End { end } => cell(ctx, CHUNK_END, &[int(end as i64)]), |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /// `form(body)` (`std/http`): the fields of a form-encoded body or query |
| 437 | /// string, parsed in one pass (`louise_rt_prims::query_params`). |
| 438 | /// |
| 439 | /// # Safety |
| 440 | /// `s` must be a live string. |
| 441 | #[unsafe(no_mangle)] |
| 442 | pub unsafe extern "C" fn tl_http_parse_query(ctx: *mut Ctx, s: Value) -> Value { |
| 443 | // SAFETY: caller guarantees a live string. |
| 444 | let pairs = louise_rt_prims::query_params(unsafe { text(s) }); |
| 445 | list( |
| 446 | ctx, |
| 447 | pairs |
| 448 | .iter() |
| 449 | .map(|(k, v)| cell(ctx, 0, &[string(ctx, k), string(ctx, v)])), |
| 450 | ) |
| 451 | } |
| 452 | |
| 453 | #[cfg(test)] |
| 454 | mod tests { |
| 455 | use super::*; |
| 456 | |
| 457 | fn head(text: &str) -> Head<'_> { |
| 458 | parse_head(text.as_bytes(), 0) |
| 459 | } |
| 460 | |
| 461 | fn complete(text: &str) -> Request<'_> { |
| 462 | match head(text) { |
| 463 | Head::Complete(req) => req, |
| 464 | other => panic!("{text:?}: {other:?}"), |
| 465 | } |
| 466 | } |
| 467 | |
| 468 | fn invalid(text: &str) -> String { |
| 469 | match head(text) { |
| 470 | Head::Invalid(reason) => reason, |
| 471 | other => panic!("{text:?} was accepted: {other:?}"), |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | #[test] |
| 476 | fn a_complete_head_and_where_it_ends() { |
| 477 | let text = "POST /a?b=1 HTTP/1.0\r\nHost: x\r\nContent-Length: 5\r\n\r\nhello"; |
| 478 | let req = complete(text); |
| 479 | assert_eq!((req.method, req.path, req.version), ("POST", "/a?b=1", 0)); |
| 480 | assert_eq!( |
| 481 | req.headers, |
| 482 | [("Host", &b"x"[..]), ("Content-Length", &b"5"[..])] |
| 483 | ); |
| 484 | assert_eq!((req.end, req.content_length), (text.len() - 5, Some(5))); |
| 485 | assert_eq!(complete("GET / HTTP/1.1\r\n\r\n").content_length, None); |
| 486 | } |
| 487 | |
| 488 | #[test] |
| 489 | fn a_head_is_read_from_an_offset() { |
| 490 | let first = "GET /1 HTTP/1.1\r\n\r\n"; |
| 491 | let both = format!("{first}GET /2 HTTP/1.1\r\nHost: x\r\n\r\n"); |
| 492 | let Head::Complete(req) = parse_head(both.as_bytes(), first.len()) else { |
| 493 | panic!("the second request"); |
| 494 | }; |
| 495 | assert_eq!((req.path, req.end), ("/2", both.len())); |
| 496 | // At the end, or past it: nothing yet. |
| 497 | assert_eq!(parse_head(both.as_bytes(), both.len()), Head::Partial); |
| 498 | assert_eq!(parse_head(both.as_bytes(), usize::MAX), Head::Partial); |
| 499 | } |
| 500 | |
| 501 | #[test] |
| 502 | fn an_incomplete_head_needs_more() { |
| 503 | for text in [ |
| 504 | "", |
| 505 | "GET", |
| 506 | "GET / HTTP/1.1\r\n", |
| 507 | "GET / HTTP/1.1\r\nHost: x\r\n", |
| 508 | ] { |
| 509 | assert_eq!(head(text), Head::Partial, "{text:?}"); |
| 510 | } |
| 511 | } |
| 512 | |
| 513 | #[test] |
| 514 | fn malformed_heads_are_invalid() { |
| 515 | for text in [ |
| 516 | "GET / HTTP/2.0\r\n\r\n", |
| 517 | "GET / HTTP/1.1\r\n\r\n", |
| 518 | "GET / HTTP/1.1\r\nNo colon\r\n\r\n", |
| 519 | "GET / HTTP/1.1\r\nBad\x01Name: x\r\n\r\n", |
| 520 | // Whitespace before the colon: proxies disagree on what it |
| 521 | // means, so it is refused. |
| 522 | "GET / HTTP/1.1\r\nContent-Length : 5\r\n\r\n", |
| 523 | ] { |
| 524 | invalid(text); |
| 525 | } |
| 526 | let many = format!( |
| 527 | "GET / HTTP/1.1\r\n{}\r\n", |
| 528 | "X: 1\r\n".repeat(MAX_HEADERS + 1) |
| 529 | ); |
| 530 | assert_eq!(invalid(&many), "too many headers"); |
| 531 | let enough = format!("GET / HTTP/1.1\r\n{}\r\n", "X: 1\r\n".repeat(MAX_HEADERS)); |
| 532 | assert_eq!(complete(&enough).headers.len(), MAX_HEADERS); |
| 533 | } |
| 534 | |
| 535 | #[test] |
| 536 | fn content_length_must_be_decimal() { |
| 537 | for value in [ |
| 538 | "", |
| 539 | "-1", |
| 540 | "+5", |
| 541 | "0x10", |
| 542 | "5 5", |
| 543 | "5,5", |
| 544 | "1e3", |
| 545 | "٣", |
| 546 | // Whitespace other than spaces and tabs: a no-break space. |
| 547 | "\u{a0}5", |
| 548 | "5\u{a0}", |
| 549 | // 2^62 and beyond: not a small Int. |
| 550 | "4611686018427387904", |
| 551 | "99999999999999999999999", |
| 552 | ] { |
| 553 | let text = format!("POST / HTTP/1.1\r\nContent-Length: {value}\r\n\r\n"); |
| 554 | assert_eq!(invalid(&text), "invalid Content-Length", "{value:?}"); |
| 555 | } |
| 556 | for (value, n) in [("0", 0), ("007", 7), ("4611686018427387903", (1 << 62) - 1)] { |
| 557 | let text = format!("POST / HTTP/1.1\r\ncontent-LENGTH: {value}\r\n\r\n"); |
| 558 | assert_eq!(complete(&text).content_length, Some(n), "{value:?}"); |
| 559 | } |
| 560 | let text = "POST / HTTP/1.1\r\nContent-Length: \t 12 \r\n\r\n"; |
| 561 | assert_eq!(complete(text).content_length, Some(12)); |
| 562 | let text = b"POST / HTTP/1.1\r\nContent-Length: 1\xff\r\n\r\n"; |
| 563 | assert!(matches!(parse_head(text, 0), Head::Invalid(_))); |
| 564 | // Control characters (a form feed, a vertical tab) never get this |
| 565 | // far: httparse rejects the header value. |
| 566 | for value in ["\u{c}5", "\u{b}5"] { |
| 567 | let text = format!("POST / HTTP/1.1\r\nContent-Length: {value}\r\n\r\n"); |
| 568 | assert!( |
| 569 | matches!(parse_head(text.as_bytes(), 0), Head::Invalid(_)), |
| 570 | "{value:?}" |
| 571 | ); |
| 572 | } |
| 573 | } |
| 574 | |
| 575 | /// Two lengths that disagree would let the server and a proxy in |
| 576 | /// front of it split the stream differently. |
| 577 | #[test] |
| 578 | fn repeated_content_lengths_must_agree() { |
| 579 | let same = "POST / HTTP/1.1\r\nContent-Length: 5\r\ncontent-length: 05\r\n\r\n"; |
| 580 | assert_eq!(complete(same).content_length, Some(5)); |
| 581 | for text in [ |
| 582 | "POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: 6\r\n\r\n", |
| 583 | "POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: x\r\n\r\n", |
| 584 | "POST / HTTP/1.1\r\nContent-Length: 0\r\nContent-Length: \r\n\r\n", |
| 585 | ] { |
| 586 | assert_eq!(invalid(text), "invalid Content-Length", "{text:?}"); |
| 587 | } |
| 588 | } |
| 589 | |
| 590 | /// Both framings are reported as they are: `std/http` refuses the |
| 591 | /// request (400). |
| 592 | #[test] |
| 593 | fn transfer_encoding_is_left_to_std_http() { |
| 594 | let text = "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n"; |
| 595 | let req = complete(text); |
| 596 | assert_eq!(req.content_length, Some(3)); |
| 597 | assert_eq!(req.headers[0], ("Transfer-Encoding", &b"chunked"[..])); |
| 598 | } |
| 599 | |
| 600 | /// A proxy that reads the last `Transfer-Encoding` would frame this |
| 601 | /// request differently from one that reads the first (issue #220). |
| 602 | #[test] |
| 603 | fn repeated_transfer_encodings_are_invalid() { |
| 604 | let text = |
| 605 | "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\ntransfer-encoding: identity\r\n\r\n"; |
| 606 | assert_eq!(invalid(text), "more than one Transfer-Encoding"); |
| 607 | } |
| 608 | |
| 609 | #[test] |
| 610 | fn the_end_of_a_head_is_found_from_an_offset() { |
| 611 | assert_eq!( |
| 612 | head_end(b"GET / HTTP/1.1\r\nHost: x\r\n\r\nbody", 0), |
| 613 | Some(27) |
| 614 | ); |
| 615 | assert_eq!(head_end(b"GET / HTTP/1.1\nHost: x\n\nbody", 0), Some(24)); |
| 616 | // Mixed line ends, as httparse reads them. |
| 617 | assert_eq!(head_end(b"GET / HTTP/1.1\nHost: x\r\n\n", 0), Some(25)); |
| 618 | assert_eq!(head_end(b"GET / HTTP/1.1\r\nHost: x\r\n", 0), None); |
| 619 | assert_eq!(head_end(b"", 0), None); |
| 620 | // An end split between two pieces: the caller scans the last 3 |
| 621 | // bytes of the first with the second. |
| 622 | let piece = b"Host: x\r\n\r"; |
| 623 | let next = b"\nbody"; |
| 624 | let mut window = piece[piece.len() - 3..].to_vec(); |
| 625 | window.extend_from_slice(next); |
| 626 | assert_eq!(head_end(&window, 0), Some(4)); |
| 627 | // From an offset: an end before it is not found. |
| 628 | assert_eq!(head_end(b"a\n\nb\n\n", 3), Some(6)); |
| 629 | assert_eq!(head_end(b"a\n\n", 9), None); |
| 630 | // Each head ends where httparse says it does. |
| 631 | for text in [ |
| 632 | "GET / HTTP/1.1\r\nHost: x\r\n\r\n", |
| 633 | "GET / HTTP/1.1\nA: b\n\n", |
| 634 | ] { |
| 635 | assert_eq!(head_end(text.as_bytes(), 0), Some(complete(text).end)); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn header_values_keep_their_bytes() { |
| 641 | let text = b"GET / HTTP/1.1\r\nX: caf\xc3\xa9 \xff\r\n\r\n"; |
| 642 | let Head::Complete(req) = parse_head(text, 0) else { |
| 643 | panic!("a valid head"); |
| 644 | }; |
| 645 | assert_eq!(req.headers, [("X", &b"caf\xc3\xa9 \xff"[..])]); |
| 646 | } |
| 647 | |
| 648 | #[test] |
| 649 | fn the_common_header_names_table_is_sorted() { |
| 650 | assert!(COMMON_HEADER_NAMES.is_sorted()); |
| 651 | assert!( |
| 652 | COMMON_HEADER_NAMES |
| 653 | .iter() |
| 654 | .all(|n| n.bytes().all(|b| b.is_ascii_graphic())) |
| 655 | ); |
| 656 | } |
| 657 | |
| 658 | #[test] |
| 659 | fn chunks_of_data_and_where_they_start() { |
| 660 | assert_eq!( |
| 661 | parse_chunk(b"5\r\nhello\r\n", 0), |
| 662 | Chunk::Data { start: 3, size: 5 } |
| 663 | ); |
| 664 | // An extension is skipped; sizes are hexadecimal, in any case. |
| 665 | assert_eq!( |
| 666 | parse_chunk(b"xx1aF;name=value\r\n", 2), |
| 667 | Chunk::Data { |
| 668 | start: 18, |
| 669 | size: 0x1af |
| 670 | } |
| 671 | ); |
| 672 | // The data may extend past the buffer. |
| 673 | assert_eq!( |
| 674 | parse_chunk(b"ff\r\n", 0), |
| 675 | Chunk::Data { |
| 676 | start: 4, |
| 677 | size: 255 |
| 678 | } |
| 679 | ); |
| 680 | } |
| 681 | |
| 682 | #[test] |
| 683 | fn the_last_chunk_ends_after_its_trailers() { |
| 684 | assert_eq!(parse_chunk(b"0\r\n\r\nGET", 0), Chunk::End { end: 5 }); |
| 685 | let trailed = b"0\r\nX-Sum: 1\r\n\r\n"; |
| 686 | assert_eq!(parse_chunk(trailed, 0), Chunk::End { end: trailed.len() }); |
| 687 | assert_eq!(parse_chunk(b"0\r\n", 0), Chunk::Partial); |
| 688 | assert_eq!(parse_chunk(b"0\r\nX-Sum: 1\r\n", 0), Chunk::Partial); |
| 689 | assert!(matches!( |
| 690 | parse_chunk(b"0\r\nbad trailer\r\n\r\n", 0), |
| 691 | Chunk::Invalid(_) |
| 692 | )); |
| 693 | } |
| 694 | |
| 695 | #[test] |
| 696 | fn incomplete_and_invalid_chunk_sizes() { |
| 697 | for text in [&b""[..], b"5", b"5\r", b"5;ext"] { |
| 698 | assert_eq!(parse_chunk(text, 0), Chunk::Partial, "{text:?}"); |
| 699 | } |
| 700 | assert_eq!(parse_chunk(b"5\r\n", 3), Chunk::Partial); |
| 701 | assert_eq!(parse_chunk(b"5\r\n", 99), Chunk::Partial); |
| 702 | for text in [ |
| 703 | &b"x\r\n"[..], |
| 704 | b"-5\r\n", |
| 705 | b" 5\r\n", |
| 706 | b"5\n\n", |
| 707 | b"ffffffffffffffffff\r\n", |
| 708 | ] { |
| 709 | assert_eq!( |
| 710 | parse_chunk(text, 0), |
| 711 | Chunk::Invalid("invalid chunk size".into()), |
| 712 | "{text:?}" |
| 713 | ); |
| 714 | } |
| 715 | // 2^62 and beyond: not a small Int. |
| 716 | for text in [&b"4000000000000000\r\n"[..], b"ffffffffffffffff\r\n"] { |
| 717 | assert_eq!( |
| 718 | parse_chunk(text, 0), |
| 719 | Chunk::Invalid("chunk too large".into()) |
| 720 | ); |
| 721 | } |
| 722 | assert_eq!( |
| 723 | parse_chunk(b"3fffffffffffffff\r\n", 0), |
| 724 | Chunk::Data { |
| 725 | start: 18, |
| 726 | size: (1 << 62) - 1 |
| 727 | } |
| 728 | ); |
| 729 | } |
| 730 | |
| 731 | /// The externs build `std/http`'s `Head` and `Chunk` values. |
| 732 | unsafe extern "C" fn builds_std_http_values(ctx: *mut Ctx) -> Value { |
| 733 | use crate::abi::{Block, UNIT, int_get}; |
| 734 | use crate::heap::drop_value; |
| 735 | use crate::values::{bytes_from, list_items, text}; |
| 736 | let field = |v: Value, i: usize| { |
| 737 | // SAFETY: the test reads fields of the cells the externs made. |
| 738 | unsafe { *Block::fields_ptr(v as *mut Block).add(i) } |
| 739 | }; |
| 740 | // SAFETY: as above. |
| 741 | let tag = |v: Value| unsafe { (*(v as *mut Block)).header.tag }; |
| 742 | // SAFETY: every value is owned by this test. |
| 743 | unsafe { |
| 744 | let head = bytes_from(ctx, b"GET /x HTTP/1.1\r\nA: b\xff\r\n\r\n"); |
| 745 | let complete = tl_http_parse_request(ctx, head, int(0)); |
| 746 | assert_eq!(tag(complete), HEAD_COMPLETE); |
| 747 | assert_eq!( |
| 748 | (text(field(complete, 0)), text(field(complete, 1))), |
| 749 | ("GET", "/x") |
| 750 | ); |
| 751 | assert_eq!(int_get(field(complete, 2)), 1); |
| 752 | let header = list_items(field(complete, 3)).next().unwrap(); |
| 753 | assert_eq!((tag(header), text(field(header, 1))), (0, "b\u{fffd}")); |
| 754 | assert_eq!(field(complete, 4), int(26)); |
| 755 | assert_eq!(field(complete, 5), int(-1)); |
| 756 | // A negative offset is 0; one past the end is the end. |
| 757 | let again = tl_http_parse_request(ctx, head, int(-5)); |
| 758 | assert_eq!(field(again, 4), int(26)); |
| 759 | let bad = tl_http_parse_request(ctx, head, int(3)); |
| 760 | assert_eq!(tag(bad), HEAD_INVALID); |
| 761 | assert_eq!(tl_http_parse_request(ctx, head, int(99)), int(HEAD_PARTIAL)); |
| 762 | |
| 763 | let chunks = bytes_from(ctx, b"5\r\nhello\r\n0\r\n\r\n"); |
| 764 | let data = tl_http_parse_chunk(ctx, chunks, int(0)); |
| 765 | assert_eq!(tag(data), CHUNK_DATA); |
| 766 | assert_eq!((field(data, 0), field(data, 1)), (int(3), int(5))); |
| 767 | let end = tl_http_parse_chunk(ctx, chunks, int(10)); |
| 768 | assert_eq!((tag(end), field(end, 0)), (CHUNK_END, int(15))); |
| 769 | let invalid = tl_http_parse_chunk(ctx, chunks, int(4)); |
| 770 | assert_eq!(tag(invalid), CHUNK_INVALID); |
| 771 | let partial = tl_http_parse_chunk(ctx, chunks, int(99)); |
| 772 | assert_eq!(partial, int(CHUNK_PARTIAL)); |
| 773 | // A common name is the same immortal string on every parse; |
| 774 | // an uncommon one is fresh each time, its bytes exact. |
| 775 | let common = bytes_from(ctx, b"GET / HTTP/1.1\r\nHost: a\r\nX-Weird: b\r\n\r\n"); |
| 776 | let first = tl_http_parse_request(ctx, common, int(0)); |
| 777 | let second = tl_http_parse_request(ctx, common, int(0)); |
| 778 | let name = |v: Value, i: usize| { |
| 779 | let mut items = list_items(field(v, 3)); |
| 780 | let pair = items.nth(i).unwrap(); |
| 781 | field(pair, 0) |
| 782 | }; |
| 783 | assert_eq!(name(first, 0), name(second, 0)); |
| 784 | assert_eq!(text(name(first, 0)), "Host"); |
| 785 | assert_ne!(name(first, 1), name(second, 1)); |
| 786 | assert_eq!(text(name(first, 1)), "X-Weird"); |
| 787 | for v in [ |
| 788 | head, complete, again, bad, chunks, data, end, invalid, common, first, second, |
| 789 | ] { |
| 790 | drop_value(ctx, v); |
| 791 | } |
| 792 | } |
| 793 | assert_eq!(crate::heap::stats::tl_stats_live_blocks(), 0); |
| 794 | UNIT |
| 795 | } |
| 796 | |
| 797 | #[test] |
| 798 | fn externs_build_std_http_values() { |
| 799 | // SAFETY: the test follows the generated-code convention. |
| 800 | let code = unsafe { crate::sched::run_test_actor(builds_std_http_values) }; |
| 801 | assert_eq!(code, 0); |
| 802 | } |
| 803 | } |