| @@ -0,0 +1,433 @@ |
| 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 and two |
| 16 | +//! that differ; `std/http` rejects a request with both `Content-Length` |
| 17 | +//! and `Transfer-Encoding` (400) and any coding other than `chunked` |
| 18 | +//! (501), and closes the connection after every rejected request. |
| 19 | + |
| 20 | +use crate::abi::{Ctx, Value, int}; |
| 21 | +use crate::int::saturating; |
| 22 | +use crate::values::{bytes_of, cell, list, string}; |
| 23 | + |
| 24 | +/// Headers a request may have; a request with more is invalid. |
| 25 | +const MAX_HEADERS: usize = 64; |
| 26 | +/// Lengths become `Int`s, which must stay small (63 bits). |
| 27 | +const MAX_LENGTH: u64 = 1 << 62; |
| 28 | + |
| 29 | +// Constructor tags of `Head` and `Chunk` (`std/http.til`). |
| 30 | +const HEAD_PARTIAL: i64 = 0; |
| 31 | +const HEAD_INVALID: u16 = 1; |
| 32 | +const HEAD_COMPLETE: u16 = 2; |
| 33 | +const CHUNK_PARTIAL: i64 = 0; |
| 34 | +const CHUNK_INVALID: u16 = 1; |
| 35 | +const CHUNK_DATA: u16 = 2; |
| 36 | +const CHUNK_END: u16 = 3; |
| 37 | + |
| 38 | +/// The head of a request, parsed from an offset of a buffer. |
| 39 | +#[derive(Debug, PartialEq)] |
| 40 | +pub(crate) enum Head<'a> { |
| 41 | + /// More bytes are needed. |
| 42 | + Partial, |
| 43 | + Invalid(String), |
| 44 | + Complete(Request<'a>), |
| 45 | +} |
| 46 | + |
| 47 | +/// A complete request head (borrowed from the buffer). |
| 48 | +#[derive(Debug, PartialEq)] |
| 49 | +pub(crate) struct Request<'a> { |
| 50 | + pub method: &'a str, |
| 51 | + pub path: &'a str, |
| 52 | + /// The minor version (`HTTP/1.version`). |
| 53 | + pub version: u8, |
| 54 | + /// Names and raw values, in order. |
| 55 | + pub headers: Vec<(&'a str, &'a [u8])>, |
| 56 | + /// The offset in the buffer where the head ends. |
| 57 | + pub end: usize, |
| 58 | + pub content_length: Option<i64>, |
| 59 | +} |
| 60 | + |
| 61 | +/// Parse the head of the request that starts at offset `at` of `buffer` |
| 62 | +/// (an offset past the end is the end). |
| 63 | +/// |
| 64 | +/// A `Content-Length` must be decimal digits (surrounding whitespace |
| 65 | +/// aside) below 2^62, and repeating it is allowed only with the same |
| 66 | +/// value. |
| 67 | +pub(crate) fn parse_head(buffer: &[u8], at: usize) -> Head<'_> { |
| 68 | + let at = at.min(buffer.len()); |
| 69 | + let mut headers = [httparse::EMPTY_HEADER; MAX_HEADERS]; |
| 70 | + let mut req = httparse::Request::new(&mut headers); |
| 71 | + let consumed = match req.parse(&buffer[at..]) { |
| 72 | + Ok(httparse::Status::Partial) => return Head::Partial, |
| 73 | + Ok(httparse::Status::Complete(n)) => n, |
| 74 | + Err(e) => return Head::Invalid(e.to_string()), |
| 75 | + }; |
| 76 | + let mut content_length = None; |
| 77 | + for h in req.headers.iter() { |
| 78 | + if h.name.eq_ignore_ascii_case("content-length") { |
| 79 | + match (decimal_length(h.value), content_length) { |
| 80 | + (Some(n), None) => content_length = Some(n), |
| 81 | + (Some(n), Some(m)) if n == m => {} |
| 82 | + _ => return Head::Invalid("invalid Content-Length".into()), |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + Head::Complete(Request { |
| 87 | + method: req.method.unwrap_or(""), |
| 88 | + path: req.path.unwrap_or(""), |
| 89 | + version: req.version.unwrap_or(1), |
| 90 | + headers: req.headers.iter().map(|h| (h.name, h.value)).collect(), |
| 91 | + end: at + consumed, |
| 92 | + content_length, |
| 93 | + }) |
| 94 | +} |
| 95 | + |
| 96 | +/// A `Content-Length` value: decimal digits only (no sign), below 2^62, |
| 97 | +/// once surrounding whitespace is trimmed. |
| 98 | +fn decimal_length(value: &[u8]) -> Option<i64> { |
| 99 | + let value = std::str::from_utf8(value).unwrap_or("").trim(); |
| 100 | + if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { |
| 101 | + return None; |
| 102 | + } |
| 103 | + value.parse::<i64>().ok().filter(|n| *n < MAX_LENGTH as i64) |
| 104 | +} |
| 105 | + |
| 106 | +/// One chunk of a chunked body, parsed from an offset of a buffer. |
| 107 | +#[derive(Debug, PartialEq)] |
| 108 | +pub(crate) enum Chunk { |
| 109 | + /// The size line, or for the last chunk its trailers, is incomplete. |
| 110 | + Partial, |
| 111 | + Invalid(String), |
| 112 | + /// `size` bytes of data start at offset `start`, then a CRLF (both |
| 113 | + /// may extend past the buffer). |
| 114 | + Data { |
| 115 | + start: usize, |
| 116 | + size: i64, |
| 117 | + }, |
| 118 | + /// The last chunk, whose trailers (ignored) end at offset `end`. |
| 119 | + End { |
| 120 | + end: usize, |
| 121 | + }, |
| 122 | +} |
| 123 | + |
| 124 | +/// Parse the chunk that starts at offset `at` of `buffer` (an offset past |
| 125 | +/// the end is the end). |
| 126 | +pub(crate) fn parse_chunk(buffer: &[u8], at: usize) -> Chunk { |
| 127 | + let at = at.min(buffer.len()); |
| 128 | + let (line, size) = match httparse::parse_chunk_size(&buffer[at..]) { |
| 129 | + Ok(httparse::Status::Partial) => return Chunk::Partial, |
| 130 | + Ok(httparse::Status::Complete(found)) => found, |
| 131 | + Err(_) => return Chunk::Invalid("invalid chunk size".into()), |
| 132 | + }; |
| 133 | + let start = at + line; |
| 134 | + if size > 0 { |
| 135 | + return if size < MAX_LENGTH { |
| 136 | + Chunk::Data { |
| 137 | + start, |
| 138 | + size: size as i64, |
| 139 | + } |
| 140 | + } else { |
| 141 | + Chunk::Invalid("chunk too large".into()) |
| 142 | + }; |
| 143 | + } |
| 144 | + let mut trailers = [httparse::EMPTY_HEADER; MAX_HEADERS]; |
| 145 | + match httparse::parse_headers(&buffer[start..], &mut trailers) { |
| 146 | + Ok(httparse::Status::Partial) => Chunk::Partial, |
| 147 | + Ok(httparse::Status::Complete((n, _))) => Chunk::End { end: start + n }, |
| 148 | + Err(e) => Chunk::Invalid(e.to_string()), |
| 149 | + } |
| 150 | +} |
| 151 | + |
| 152 | +/// An offset argument: a negative one is 0. |
| 153 | +/// |
| 154 | +/// # Safety |
| 155 | +/// `at` must be a live `Int`. |
| 156 | +unsafe fn offset(at: Value) -> usize { |
| 157 | + // SAFETY: forwarded caller guarantee. |
| 158 | + usize::try_from(unsafe { saturating(at) }).unwrap_or(0) |
| 159 | +} |
| 160 | + |
| 161 | +/// `parse_head(buffer, at)` (`std/http`): [`parse_head`] as a `Head`: |
| 162 | +/// `Partial`, `Invalid(reason)`, or `Complete(method, path, version, |
| 163 | +/// headers, end, content_length)`, where `content_length` is -1 when |
| 164 | +/// absent. Header values that are not UTF-8 have invalid bytes replaced. |
| 165 | +/// |
| 166 | +/// # Safety |
| 167 | +/// `buffer` must be live `Bytes`; `at` a live `Int`. |
| 168 | +#[unsafe(no_mangle)] |
| 169 | +pub unsafe extern "C" fn tl_http_parse_request(ctx: *mut Ctx, buffer: Value, at: Value) -> Value { |
| 170 | + // SAFETY: caller guarantees live `Bytes` and a live Int. |
| 171 | + let (bytes, at) = unsafe { (bytes_of(buffer), offset(at)) }; |
| 172 | + match parse_head(bytes, at) { |
| 173 | + Head::Partial => int(HEAD_PARTIAL), |
| 174 | + Head::Invalid(reason) => cell(ctx, HEAD_INVALID, &[string(ctx, &reason)]), |
| 175 | + Head::Complete(req) => { |
| 176 | + let headers = list( |
| 177 | + ctx, |
| 178 | + req.headers.iter().map(|(name, value)| { |
| 179 | + let value = String::from_utf8_lossy(value); |
| 180 | + cell(ctx, 0, &[string(ctx, name), string(ctx, &value)]) |
| 181 | + }), |
| 182 | + ); |
| 183 | + cell( |
| 184 | + ctx, |
| 185 | + HEAD_COMPLETE, |
| 186 | + &[ |
| 187 | + string(ctx, req.method), |
| 188 | + string(ctx, req.path), |
| 189 | + int(i64::from(req.version)), |
| 190 | + headers, |
| 191 | + int(req.end as i64), |
| 192 | + int(req.content_length.unwrap_or(-1)), |
| 193 | + ], |
| 194 | + ) |
| 195 | + } |
| 196 | + } |
| 197 | +} |
| 198 | + |
| 199 | +/// `parse_chunk(buffer, at)` (`std/http`): [`parse_chunk`] as a `Chunk`: |
| 200 | +/// `ChunkPartial`, `ChunkInvalid(reason)`, `ChunkData(start, size)` or |
| 201 | +/// `ChunkEnd(end)`. |
| 202 | +/// |
| 203 | +/// # Safety |
| 204 | +/// `buffer` must be live `Bytes`; `at` a live `Int`. |
| 205 | +#[unsafe(no_mangle)] |
| 206 | +pub unsafe extern "C" fn tl_http_parse_chunk(ctx: *mut Ctx, buffer: Value, at: Value) -> Value { |
| 207 | + // SAFETY: caller guarantees live `Bytes` and a live Int. |
| 208 | + let (bytes, at) = unsafe { (bytes_of(buffer), offset(at)) }; |
| 209 | + match parse_chunk(bytes, at) { |
| 210 | + Chunk::Partial => int(CHUNK_PARTIAL), |
| 211 | + Chunk::Invalid(reason) => cell(ctx, CHUNK_INVALID, &[string(ctx, &reason)]), |
| 212 | + Chunk::Data { start, size } => cell(ctx, CHUNK_DATA, &[int(start as i64), int(size)]), |
| 213 | + Chunk::End { end } => cell(ctx, CHUNK_END, &[int(end as i64)]), |
| 214 | + } |
| 215 | +} |
| 216 | + |
| 217 | +#[cfg(test)] |
| 218 | +mod tests { |
| 219 | + use super::*; |
| 220 | + |
| 221 | + fn head(text: &str) -> Head<'_> { |
| 222 | + parse_head(text.as_bytes(), 0) |
| 223 | + } |
| 224 | + |
| 225 | + fn complete(text: &str) -> Request<'_> { |
| 226 | + match head(text) { |
| 227 | + Head::Complete(req) => req, |
| 228 | + other => panic!("{text:?}: {other:?}"), |
| 229 | + } |
| 230 | + } |
| 231 | + |
| 232 | + fn invalid(text: &str) -> String { |
| 233 | + match head(text) { |
| 234 | + Head::Invalid(reason) => reason, |
| 235 | + other => panic!("{text:?} was accepted: {other:?}"), |
| 236 | + } |
| 237 | + } |
| 238 | + |
| 239 | + #[test] |
| 240 | + fn a_complete_head_and_where_it_ends() { |
| 241 | + let text = "POST /a?b=1 HTTP/1.0\r\nHost: x\r\nContent-Length: 5\r\n\r\nhello"; |
| 242 | + let req = complete(text); |
| 243 | + assert_eq!((req.method, req.path, req.version), ("POST", "/a?b=1", 0)); |
| 244 | + assert_eq!( |
| 245 | + req.headers, |
| 246 | + [("Host", &b"x"[..]), ("Content-Length", &b"5"[..])] |
| 247 | + ); |
| 248 | + assert_eq!((req.end, req.content_length), (text.len() - 5, Some(5))); |
| 249 | + assert_eq!(complete("GET / HTTP/1.1\r\n\r\n").content_length, None); |
| 250 | + } |
| 251 | + |
| 252 | + #[test] |
| 253 | + fn a_head_is_read_from_an_offset() { |
| 254 | + let first = "GET /1 HTTP/1.1\r\n\r\n"; |
| 255 | + let both = format!("{first}GET /2 HTTP/1.1\r\nHost: x\r\n\r\n"); |
| 256 | + let Head::Complete(req) = parse_head(both.as_bytes(), first.len()) else { |
| 257 | + panic!("the second request"); |
| 258 | + }; |
| 259 | + assert_eq!((req.path, req.end), ("/2", both.len())); |
| 260 | + // At the end, or past it: nothing yet. |
| 261 | + assert_eq!(parse_head(both.as_bytes(), both.len()), Head::Partial); |
| 262 | + assert_eq!(parse_head(both.as_bytes(), usize::MAX), Head::Partial); |
| 263 | + } |
| 264 | + |
| 265 | + #[test] |
| 266 | + fn an_incomplete_head_needs_more() { |
| 267 | + for text in [ |
| 268 | + "", |
| 269 | + "GET", |
| 270 | + "GET / HTTP/1.1\r\n", |
| 271 | + "GET / HTTP/1.1\r\nHost: x\r\n", |
| 272 | + ] { |
| 273 | + assert_eq!(head(text), Head::Partial, "{text:?}"); |
| 274 | + } |
| 275 | + } |
| 276 | + |
| 277 | + #[test] |
| 278 | + fn malformed_heads_are_invalid() { |
| 279 | + for text in [ |
| 280 | + "GET / HTTP/2.0\r\n\r\n", |
| 281 | + "GET / HTTP/1.1\r\n\r\n", |
| 282 | + "GET / HTTP/1.1\r\nNo colon\r\n\r\n", |
| 283 | + "GET / HTTP/1.1\r\nBad\x01Name: x\r\n\r\n", |
| 284 | + // Whitespace before the colon: proxies disagree on what it |
| 285 | + // means, so it is refused. |
| 286 | + "GET / HTTP/1.1\r\nContent-Length : 5\r\n\r\n", |
| 287 | + ] { |
| 288 | + invalid(text); |
| 289 | + } |
| 290 | + let many = format!( |
| 291 | + "GET / HTTP/1.1\r\n{}\r\n", |
| 292 | + "X: 1\r\n".repeat(MAX_HEADERS + 1) |
| 293 | + ); |
| 294 | + assert_eq!(invalid(&many), "too many headers"); |
| 295 | + let enough = format!("GET / HTTP/1.1\r\n{}\r\n", "X: 1\r\n".repeat(MAX_HEADERS)); |
| 296 | + assert_eq!(complete(&enough).headers.len(), MAX_HEADERS); |
| 297 | + } |
| 298 | + |
| 299 | + #[test] |
| 300 | + fn content_length_must_be_decimal() { |
| 301 | + for value in [ |
| 302 | + "", |
| 303 | + "-1", |
| 304 | + "+5", |
| 305 | + "0x10", |
| 306 | + "5 5", |
| 307 | + "5,5", |
| 308 | + "1e3", |
| 309 | + "٣", |
| 310 | + // 2^62 and beyond: not a small Int. |
| 311 | + "4611686018427387904", |
| 312 | + "99999999999999999999999", |
| 313 | + ] { |
| 314 | + let text = format!("POST / HTTP/1.1\r\nContent-Length: {value}\r\n\r\n"); |
| 315 | + assert_eq!(invalid(&text), "invalid Content-Length", "{value:?}"); |
| 316 | + } |
| 317 | + for (value, n) in [("0", 0), ("007", 7), ("4611686018427387903", (1 << 62) - 1)] { |
| 318 | + let text = format!("POST / HTTP/1.1\r\ncontent-LENGTH: {value}\r\n\r\n"); |
| 319 | + assert_eq!(complete(&text).content_length, Some(n), "{value:?}"); |
| 320 | + } |
| 321 | + let text = "POST / HTTP/1.1\r\nContent-Length: \t 12 \r\n\r\n"; |
| 322 | + assert_eq!(complete(text).content_length, Some(12)); |
| 323 | + let text = b"POST / HTTP/1.1\r\nContent-Length: 1\xff\r\n\r\n"; |
| 324 | + assert!(matches!(parse_head(text, 0), Head::Invalid(_))); |
| 325 | + } |
| 326 | + |
| 327 | + /// Two lengths that disagree would let the server and a proxy in |
| 328 | + /// front of it split the stream differently. |
| 329 | + #[test] |
| 330 | + fn repeated_content_lengths_must_agree() { |
| 331 | + let same = "POST / HTTP/1.1\r\nContent-Length: 5\r\ncontent-length: 05\r\n\r\n"; |
| 332 | + assert_eq!(complete(same).content_length, Some(5)); |
| 333 | + for text in [ |
| 334 | + "POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: 6\r\n\r\n", |
| 335 | + "POST / HTTP/1.1\r\nContent-Length: 5\r\nContent-Length: x\r\n\r\n", |
| 336 | + "POST / HTTP/1.1\r\nContent-Length: 0\r\nContent-Length: \r\n\r\n", |
| 337 | + ] { |
| 338 | + assert_eq!(invalid(text), "invalid Content-Length", "{text:?}"); |
| 339 | + } |
| 340 | + } |
| 341 | + |
| 342 | + /// Both framings are reported as they are: `std/http` refuses the |
| 343 | + /// request (400). |
| 344 | + #[test] |
| 345 | + fn transfer_encoding_is_left_to_std_http() { |
| 346 | + let text = "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\nContent-Length: 3\r\n\r\n"; |
| 347 | + let req = complete(text); |
| 348 | + assert_eq!(req.content_length, Some(3)); |
| 349 | + assert_eq!(req.headers[0], ("Transfer-Encoding", &b"chunked"[..])); |
| 350 | + } |
| 351 | + |
| 352 | + #[test] |
| 353 | + fn header_values_keep_their_bytes() { |
| 354 | + let text = b"GET / HTTP/1.1\r\nX: caf\xc3\xa9 \xff\r\n\r\n"; |
| 355 | + let Head::Complete(req) = parse_head(text, 0) else { |
| 356 | + panic!("a valid head"); |
| 357 | + }; |
| 358 | + assert_eq!(req.headers, [("X", &b"caf\xc3\xa9 \xff"[..])]); |
| 359 | + } |
| 360 | + |
| 361 | + #[test] |
| 362 | + fn chunks_of_data_and_where_they_start() { |
| 363 | + assert_eq!( |
| 364 | + parse_chunk(b"5\r\nhello\r\n", 0), |
| 365 | + Chunk::Data { start: 3, size: 5 } |
| 366 | + ); |
| 367 | + // An extension is skipped; sizes are hexadecimal, in any case. |
| 368 | + assert_eq!( |
| 369 | + parse_chunk(b"xx1aF;name=value\r\n", 2), |
| 370 | + Chunk::Data { |
| 371 | + start: 18, |
| 372 | + size: 0x1af |
| 373 | + } |
| 374 | + ); |
| 375 | + // The data may extend past the buffer. |
| 376 | + assert_eq!( |
| 377 | + parse_chunk(b"ff\r\n", 0), |
| 378 | + Chunk::Data { |
| 379 | + start: 4, |
| 380 | + size: 255 |
| 381 | + } |
| 382 | + ); |
| 383 | + } |
| 384 | + |
| 385 | + #[test] |
| 386 | + fn the_last_chunk_ends_after_its_trailers() { |
| 387 | + assert_eq!(parse_chunk(b"0\r\n\r\nGET", 0), Chunk::End { end: 5 }); |
| 388 | + let trailed = b"0\r\nX-Sum: 1\r\n\r\n"; |
| 389 | + assert_eq!(parse_chunk(trailed, 0), Chunk::End { end: trailed.len() }); |
| 390 | + assert_eq!(parse_chunk(b"0\r\n", 0), Chunk::Partial); |
| 391 | + assert_eq!(parse_chunk(b"0\r\nX-Sum: 1\r\n", 0), Chunk::Partial); |
| 392 | + assert!(matches!( |
| 393 | + parse_chunk(b"0\r\nbad trailer\r\n\r\n", 0), |
| 394 | + Chunk::Invalid(_) |
| 395 | + )); |
| 396 | + } |
| 397 | + |
| 398 | + #[test] |
| 399 | + fn incomplete_and_invalid_chunk_sizes() { |
| 400 | + for text in [&b""[..], b"5", b"5\r", b"5;ext"] { |
| 401 | + assert_eq!(parse_chunk(text, 0), Chunk::Partial, "{text:?}"); |
| 402 | + } |
| 403 | + assert_eq!(parse_chunk(b"5\r\n", 3), Chunk::Partial); |
| 404 | + assert_eq!(parse_chunk(b"5\r\n", 99), Chunk::Partial); |
| 405 | + for text in [ |
| 406 | + &b"x\r\n"[..], |
| 407 | + b"-5\r\n", |
| 408 | + b" 5\r\n", |
| 409 | + b"5\n\n", |
| 410 | + b"ffffffffffffffffff\r\n", |
| 411 | + ] { |
| 412 | + assert_eq!( |
| 413 | + parse_chunk(text, 0), |
| 414 | + Chunk::Invalid("invalid chunk size".into()), |
| 415 | + "{text:?}" |
| 416 | + ); |
| 417 | + } |
| 418 | + // 2^62 and beyond: not a small Int. |
| 419 | + for text in [&b"4000000000000000\r\n"[..], b"ffffffffffffffff\r\n"] { |
| 420 | + assert_eq!( |
| 421 | + parse_chunk(text, 0), |
| 422 | + Chunk::Invalid("chunk too large".into()) |
| 423 | + ); |
| 424 | + } |
| 425 | + assert_eq!( |
| 426 | + parse_chunk(b"3fffffffffffffff\r\n", 0), |
| 427 | + Chunk::Data { |
| 428 | + start: 18, |
| 429 | + size: (1 << 62) - 1 |
| 430 | + } |
| 431 | + ); |
| 432 | + } |
| 433 | +} |