crates/edge/server/src/lib.rs 30.8 KiB 906 lines Raw
1 //! The HTTP/1.1 transport of the web.2 //!3 //! The server speaks one version, serves one request per connection, and4 //! closes. `Connection: close` is always sent, so no response carries a5 //! keep-alive that a client could reuse for request smuggling.6 //!7 //! The transport knows no routes, no auth, and no JSON shape. It parses a8 //! request under caller-supplied limits, hands it to a handler, and writes the9 //! handler's response. Sizes, timeouts, and the connection cap are fields of10 //! [`Limits`]; this crate has no defaults.11 12 pub mod app;13 pub mod auth;14 mod capability;15 mod multipart;16 pub mod route;17 pub mod stop;18 19 use std::fmt;20 use std::fs::File;21 use std::io::{self, BufRead, BufReader, Read, Seek, SeekFrom, Write};22 use std::net::TcpListener;23 use std::net::TcpStream;24 use std::os::unix::fs::OpenOptionsExt;25 use std::sync::Arc;26 use std::sync::atomic::{AtomicU64, Ordering};27 use std::thread;28 use std::time::{Duration, Instant};29 30 pub use stop::Stop;31 32 /// The request limits. The caller supplies every field; the code has no33 /// defaults.34 #[derive(Clone, Copy, PartialEq, Eq, Debug)]35 pub struct Limits {36     /// The largest request head, in bytes, including the empty line.37     pub max_head_bytes: usize,38     /// The largest request body that the transport buffers in memory.39     pub max_body_bytes: usize,40     /// The largest request body that the transport spools to a file. A body41     /// between the two limits arrives as [`Upload`], never as a `Vec`.42     pub max_upload_bytes: usize,43     /// The longest that one socket read may block. This bounds a body that44     /// stalls and an idle client that sends no request.45     pub read_timeout: Duration,46     /// The total time allowed to read one request line and its headers. The47     /// deadline is absolute: a client that drips one byte at a time cannot48     /// hold a thread past it.49     pub head_timeout: Duration,50     /// The longest that one socket write may block.51     pub write_timeout: Duration,52     /// The most connections that may be served at one time. Above this count53     /// a connection gets `503` and is closed.54     pub max_connections: usize,55 }56 57 /// The method of a request.58 #[derive(Clone, PartialEq, Eq, Debug)]59 pub enum Method {60     /// `GET`.61     Get,62     /// `POST`.63     Post,64     /// `DELETE`.65     Delete,66     /// Any other method token.67     Other(String),68 }69 70 /// The headers of a request. Names are matched ASCII case-insensitively and71 /// keep the order and the spelling they arrived in.72 #[derive(Clone, PartialEq, Eq, Debug, Default)]73 pub struct Headers(Vec<(String, String)>);74 75 impl Headers {76     /// No headers.77     pub fn new() -> Headers {78         Headers(Vec::new())79     }80 81     /// Appends a header.82     pub fn push(&mut self, name: &str, value: &str) {83         self.0.push((name.to_string(), value.to_string()));84     }85 86     /// The value of the first header with this name.87     pub fn get(&self, name: &str) -> Option<&str> {88         self.089             .iter()90             .find(|(n, _)| same_name(n, name))91             .map(|(_, v)| v.as_str())92     }93 94     /// The values of every header with this name, in arrival order.95     pub fn values(&self, name: &str) -> impl Iterator<Item = &str> {96         self.097             .iter()98             .filter(move |(n, _)| same_name(n, name))99             .map(|(_, v)| v.as_str())100     }101 102     /// Every header in arrival order.103     pub fn iter(&self) -> std::slice::Iter<'_, (String, String)> {104         self.0.iter()105     }106 107     /// How many headers there are.108     pub fn len(&self) -> usize {109         self.0.len()110     }111 112     /// True when there is no header.113     pub fn is_empty(&self) -> bool {114         self.0.is_empty()115     }116 }117 118 fn same_name(a: &str, b: &str) -> bool {119     a.eq_ignore_ascii_case(b)120 }121 122 /// A body that was too large to buffer, spooled to an unlinked file.123 #[derive(Debug)]124 pub struct Upload {125     /// The body as it arrived.126     pub file: File,127     /// The `Content-Length` that the body declared.128     pub len: u64,129 }130 131 /// A request read from the wire.132 #[derive(Debug)]133 pub struct Request {134     pub method: Method,135     /// The target as sent: path plus query, never decoded.136     pub target: String,137     /// The uid of the peer when the transport can know it. A Unix socket can;138     /// TCP cannot, and there the token is the credential.139     pub peer_uid: Option<u32>,140     pub headers: Headers,141     /// The buffered body, when it fit `Limits::max_body_bytes`.142     pub body: Vec<u8>,143     /// The spooled body, when it was larger than the buffer limit but within144     /// the upload limit. Exactly one of `body` and `upload` carries bytes.145     pub upload: Option<Upload>,146 }147 148 /// A request that this transport does not accept.149 #[derive(Debug)]150 pub enum ParseError {151     /// The request does not obey the HTTP/1.1 that this server speaks.152     BadRequest,153     /// The head or the body is above the limit in [`Limits`].154     TooLarge,155     /// The request uses a feature this server refuses: a chunked body.156     Unsupported,157     /// The request did not arrive inside a timeout.158     Timeout,159     /// The request names an `Expect` value that this server does not meet.160     Expectation,161     /// The reader failed.162     Io(io::Error),163 }164 165 impl fmt::Display for ParseError {166     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {167         match self {168             ParseError::BadRequest => write!(f, "the request does not obey HTTP/1.1"),169             ParseError::TooLarge => write!(f, "the request is above a size limit"),170             ParseError::Unsupported => write!(f, "the request uses a refused transfer coding"),171             ParseError::Timeout => write!(f, "the request did not arrive inside a timeout"),172             ParseError::Expectation => write!(f, "the request asks for an unmet expectation"),173             ParseError::Io(e) => write!(f, "io: {e}"),174         }175     }176 }177 178 impl std::error::Error for ParseError {}179 180 impl From<io::Error> for ParseError {181     fn from(e: io::Error) -> ParseError {182         ParseError::Io(e)183     }184 }185 186 /// An HTTP status code. The reason phrase comes from a small table.187 #[derive(Clone, Copy, PartialEq, Eq, Debug)]188 pub struct Status(pub u16);189 190 impl Status {191     pub const OK: Status = Status(200);192     pub const CREATED: Status = Status(201);193     pub const ACCEPTED: Status = Status(202);194     pub const BAD_REQUEST: Status = Status(400);195     pub const UNAUTHORIZED: Status = Status(401);196     pub const METHOD_NOT_ALLOWED: Status = Status(405);197     pub const NOT_FOUND: Status = Status(404);198     pub const REQUEST_TIMEOUT: Status = Status(408);199     pub const TOO_LARGE: Status = Status(413);200     pub const EXPECTATION_FAILED: Status = Status(417);201     pub const INTERNAL: Status = Status(500);202     pub const BAD_GATEWAY: Status = Status(502);203     pub const SERVICE_UNAVAILABLE: Status = Status(503);204 205     /// The reason phrase for this code. A code outside the table gets206     /// `"Unknown"`, because a status line always needs a phrase.207     pub const fn reason(self) -> &'static str {208         match self.0 {209             200 => "OK",210             201 => "Created",211             202 => "Accepted",212             204 => "No Content",213             400 => "Bad Request",214             401 => "Unauthorized",215             403 => "Forbidden",216             404 => "Not Found",217             405 => "Method Not Allowed",218             408 => "Request Timeout",219             409 => "Conflict",220             413 => "Content Too Large",221             417 => "Expectation Failed",222             429 => "Too Many Requests",223             500 => "Internal Server Error",224             501 => "Not Implemented",225             502 => "Bad Gateway",226             503 => "Service Unavailable",227             504 => "Gateway Timeout",228             _ => "Unknown",229         }230     }231 }232 233 /// The body of a response.234 pub enum Body {235     /// A body of a known size, framed with `Content-Length`.236     Bytes(Vec<u8>),237     /// A stream framed with `Transfer-Encoding: chunked`. Each item is one238     /// chunk and is flushed as it arrives. An `Err` ends the connection239     /// without the terminating zero chunk, so a truncated body cannot look240     /// complete.241     Chunks(Box<dyn Iterator<Item = io::Result<Vec<u8>>> + Send>),242 }243 244 /// A response to write to the connection.245 pub struct Response {246     pub status: Status,247     /// Headers to write as given. Do not name `Content-Length`,248     /// `Transfer-Encoding`, or `Connection`; `write_response` appends them.249     pub headers: Vec<(String, String)>,250     pub body: Body,251 }252 253 impl Response {254     /// A `text/plain` response with this body.255     pub fn text(status: Status, body: &str) -> Response {256         Response {257             status,258             headers: vec![(259                 "content-type".to_string(),260                 "text/plain; charset=utf-8".to_string(),261             )],262             body: Body::Bytes(body.as_bytes().to_vec()),263         }264     }265 266     /// An `application/json` response with this body.267     pub fn json(status: Status, body: &str) -> Response {268         Response {269             status,270             headers: vec![("content-type".to_string(), "application/json".to_string())],271             body: Body::Bytes(body.as_bytes().to_vec()),272         }273     }274 }275 276 /// True for the RFC 9110 `tchar` set, which every method and header name is277 /// made of.278 fn is_tchar(b: u8) -> bool {279     b.is_ascii_alphanumeric()280         || matches!(281             b,282             b'!' | b'#'283                 | b'$'284                 | b'%'285                 | b'&'286                 | b'\''287                 | b'*'288                 | b'+'289                 | b'-'290                 | b'.'291                 | b'^'292                 | b'_'293                 | b'`'294                 | b'|'295                 | b'~'296         )297 }298 299 /// True for the two error kinds that a socket read timeout reports.300 fn is_timeout(why: &io::Error) -> bool {301     matches!(302         why.kind(),303         io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut304     )305 }306 307 /// A failed read, classified so that the server can answer a timeout.308 fn read_failure(why: io::Error) -> ParseError {309     if is_timeout(&why) {310         ParseError::Timeout311     } else {312         ParseError::Io(why)313     }314 }315 316 /// Reads one line of the head, stopping when `budget` bytes of it would pass317 /// the limit. The bytes past the limit are left unread, so an oversized head318 /// is refused without buffering it.319 ///320 /// `Ok(None)` means a clean end of input at a line boundary. An end of input321 /// in the middle of a line is `BadRequest`.322 fn read_head_line<R: BufRead>(323     reader: &mut R,324     budget: usize,325     deadline: Instant,326 ) -> Result<Option<Vec<u8>>, ParseError> {327     let mut line = Vec::new();328     loop {329         if Instant::now() >= deadline {330             return Err(ParseError::Timeout);331         }332         let buf = match reader.fill_buf() {333             Ok(buf) => buf,334             Err(why) if why.kind() == io::ErrorKind::Interrupted => continue,335             Err(why) => return Err(read_failure(why)),336         };337         if buf.is_empty() {338             if line.is_empty() {339                 return Ok(None);340             }341             return Err(ParseError::BadRequest);342         }343         let newline = buf.iter().position(|&b| b == b'\n');344         let take = match newline {345             Some(i) => i + 1,346             None => buf.len(),347         };348         if line.len() + take > budget {349             return Err(ParseError::TooLarge);350         }351         line.extend_from_slice(&buf[..take]);352         reader.consume(take);353         if newline.is_some() {354             if line.last() == Some(&b'\n') {355                 line.pop();356             }357             if line.last() == Some(&b'\r') {358                 line.pop();359             }360             return Ok(Some(line));361         }362     }363 }364 365 /// Reads the request line: `METHOD SP TARGET SP HTTP/1.1`.366 ///367 /// The target is the origin form, `path?query`: it starts with `/` and holds368 /// only bytes from `!` to `~`, kept exactly as sent. Only HTTP/1.1 is369 /// accepted, so HTTP/1.0 is `BadRequest` like any other version: this server370 /// speaks one version.371 fn parse_request_line(line: &[u8]) -> Result<(Method, String), ParseError> {372     let mut parts = line.split(|&b| b == b' ');373     let method = parts374         .next()375         .filter(|p| !p.is_empty())376         .ok_or(ParseError::BadRequest)?;377     let target = parts378         .next()379         .filter(|p| !p.is_empty())380         .ok_or(ParseError::BadRequest)?;381     let version = parts.next().ok_or(ParseError::BadRequest)?;382     if parts.next().is_some() {383         return Err(ParseError::BadRequest);384     }385     if version != b"HTTP/1.1" {386         return Err(ParseError::BadRequest);387     }388     if !method.iter().all(|&b| is_tchar(b)) {389         return Err(ParseError::BadRequest);390     }391     if target.first() != Some(&b'/') || !target.iter().all(|&b| (0x21..=0x7e).contains(&b)) {392         return Err(ParseError::BadRequest);393     }394     let method_text = String::from_utf8(method.to_vec()).map_err(|_| ParseError::BadRequest)?;395     let method = match method_text.as_str() {396         "GET" => Method::Get,397         "POST" => Method::Post,398         "DELETE" => Method::Delete,399         _ => Method::Other(method_text),400     };401     let target = String::from_utf8(target.to_vec()).map_err(|_| ParseError::BadRequest)?;402     Ok((method, target))403 }404 405 /// Reads one header line: a `tchar` name, `:`, and a value without its406 /// surrounding OWS.407 fn parse_header_line(line: &[u8]) -> Result<(String, String), ParseError> {408     let colon = line409         .iter()410         .position(|&b| b == b':')411         .ok_or(ParseError::BadRequest)?;412     let (name, value) = (413         line.get(..colon).ok_or(ParseError::BadRequest)?,414         &line[colon + 1..],415     );416     if name.is_empty() || !name.iter().all(|&b| is_tchar(b)) {417         return Err(ParseError::BadRequest);418     }419     let value = value.trim_ascii();420     let name = String::from_utf8(name.to_vec()).map_err(|_| ParseError::BadRequest)?;421     let value = String::from_utf8(value.to_vec()).map_err(|_| ParseError::BadRequest)?;422     Ok((name, value))423 }424 425 /// Parses a `Content-Length` value: decimal digits only.426 ///427 /// `Ok(None)` is the empty value that names no size. A value with a non-digit428 /// or a bare empty value is `BadRequest`; a value too big for `u64` is429 /// `TooLarge` because it cannot fit any body limit.430 fn parse_content_length(value: &str) -> Result<Option<u64>, ParseError> {431     if value.is_empty() {432         return Ok(None);433     }434     let mut number: u64 = 0;435     for b in value.as_bytes() {436         let digit = u64::from(b.wrapping_sub(b'0'));437         if digit > 9 {438             return Err(ParseError::BadRequest);439         }440         number = number441             .checked_mul(10)442             .and_then(|n| n.checked_add(digit))443             .ok_or(ParseError::TooLarge)?;444     }445     Ok(Some(number))446 }447 448 /// Reads exactly `length` body bytes. A reader that ends first is a short449 /// request and `BadRequest`.450 fn read_body<R: BufRead>(reader: &mut R, length: usize) -> Result<Vec<u8>, ParseError> {451     let mut body = vec![0u8; length];452     let mut got = 0;453     while got < length {454         match reader.read(&mut body[got..]) {455             Ok(0) => return Err(ParseError::BadRequest),456             Ok(n) => got += n,457             Err(e) if e.kind() == io::ErrorKind::Interrupted => {}458             Err(e) => return Err(read_failure(e)),459         }460     }461     Ok(body)462 }463 464 /// Spools exactly `length` bytes to an unlinked temporary file.465 ///466 /// The file has no name after `open`, so a crash leaves nothing behind and a467 /// second process cannot read a caller's upload. The bytes reach the disk in468 /// chunks; the transport never holds the whole body.469 fn spool_body<R: BufRead>(reader: &mut R, length: u64) -> Result<Upload, ParseError> {470     static NEXT: AtomicU64 = AtomicU64::new(1);471     let name = format!(472         "inf3r-upload-{}-{}",473         std::process::id(),474         NEXT.fetch_add(1, Ordering::Relaxed)475     );476     let path = std::env::temp_dir().join(name);477     let mut file = std::fs::OpenOptions::new()478         .create_new(true)479         .read(true)480         .write(true)481         .mode(0o600)482         .open(&path)?;483     // Unlink first: the descriptor is the only handle, and no later reader can484     // find the body by name.485     let _ = std::fs::remove_file(&path);486     let mut left = length;487     let mut buf = [0u8; 64 << 10];488     while left > 0 {489         let want = usize::try_from(left.min(buf.len() as u64)).unwrap_or(buf.len());490         let n = match reader.read(&mut buf[..want]) {491             Ok(0) => return Err(ParseError::BadRequest),492             Ok(n) => n,493             Err(why) if why.kind() == io::ErrorKind::Interrupted => continue,494             Err(why) => return Err(read_failure(why)),495         };496         file.write_all(&buf[..n])?;497         left -= n as u64;498     }499     file.seek(SeekFrom::Start(0))?;500     Ok(Upload { file, len: length })501 }502 503 /// True when the headers ask the server to send `100 Continue` before the504 /// body. An `Expect` value outside that one token is refused: the server has505 /// no other expectation that it could meet.506 fn wants_continue(headers: &Headers) -> Result<bool, ParseError> {507     let mut wants = false;508     for value in headers.values("expect") {509         for token in value.split(',') {510             if !token.trim_ascii().eq_ignore_ascii_case("100-continue") {511                 return Err(ParseError::Expectation);512             }513             wants = true;514         }515     }516     Ok(wants)517 }518 519 /// Parses one request under `limits`, with no interim response.520 ///521 /// A `Content-Length` is required for a body; without one the body is empty.522 /// `Transfer-Encoding` is refused whenever it appears, so there is no chunked523 /// request body and no request-smuggling surface. Two `Content-Length` values524 /// that disagree are `BadRequest`; identical ones are accepted.525 pub fn parse_request<R: BufRead>(reader: &mut R, limits: &Limits) -> Result<Request, ParseError> {526     parse_request_with(reader, limits, || Ok(()))527 }528 529 /// Parses one request and writes `100 Continue` when the client asked for it530 /// and the body is otherwise acceptable.531 ///532 /// `interim` runs after the head is checked and before the first body byte is533 /// read. A client such as curl waits for that line before it sends a body over534 /// 1 KiB; without it the client and the server wait for each other until the535 /// client gives up.536 fn parse_request_with<R: BufRead, F: FnMut() -> io::Result<()>>(537     reader: &mut R,538     limits: &Limits,539     mut interim: F,540 ) -> Result<Request, ParseError> {541     let deadline = Instant::now() + limits.head_timeout;542     let mut head_bytes = 0usize;543 544     let request_line =545         read_head_line(reader, limits.max_head_bytes + 1, deadline)?.ok_or_else(|| {546             ParseError::Io(io::Error::new(547                 io::ErrorKind::UnexpectedEof,548                 "the connection closed before a request",549             ))550         })?;551     head_bytes += request_line.len();552     let (method, target) = parse_request_line(&request_line)?;553 554     let mut headers = Headers::new();555     loop {556         let remaining = limits.max_head_bytes + 1 - head_bytes;557         let line = read_head_line(reader, remaining, deadline)?.ok_or(ParseError::BadRequest)?;558         head_bytes += line.len();559         if head_bytes > limits.max_head_bytes {560             return Err(ParseError::TooLarge);561         }562         if line.is_empty() {563             break;564         }565         let (name, value) = parse_header_line(&line)?;566         headers.push(&name, &value);567     }568 569     if headers.values("transfer-encoding").next().is_some() {570         return Err(ParseError::Unsupported);571     }572 573     let mut body_len: Option<u64> = None;574     for value in headers.values("content-length") {575         let value = parse_content_length(value)?;576         match (body_len, value) {577             (None, Some(n)) => body_len = Some(n),578             (Some(a), Some(b)) if a == b => {}579             _ => return Err(ParseError::BadRequest),580         }581     }582     let body_len = body_len.unwrap_or(0);583     let wants_body = wants_continue(&headers)?;584     let buffered = u64::try_from(limits.max_body_bytes).unwrap_or(u64::MAX);585     let uploadable = u64::try_from(limits.max_upload_bytes).unwrap_or(u64::MAX);586     if body_len > buffered.max(uploadable) {587         return Err(ParseError::TooLarge);588     }589     if wants_body && body_len > 0 {590         interim().map_err(ParseError::Io)?;591     }592     if body_len > buffered {593         let upload = spool_body(reader, body_len)?;594         return Ok(Request {595             method,596             target,597             peer_uid: None,598             headers,599             body: Vec::new(),600             upload: Some(upload),601         });602     }603 604     let body = read_body(reader, body_len as usize)?;605     Ok(Request {606         method,607         target,608         peer_uid: None,609         headers,610         body,611         upload: None,612     })613 }614 615 /// Writes `chunk` as one `Transfer-Encoding: chunked` chunk.616 fn write_chunk<W: Write>(writer: &mut W, chunk: &[u8]) -> io::Result<()> {617     write!(writer, "{:x}\r\n", chunk.len())?;618     writer.write_all(chunk)?;619     writer.write_all(b"\r\n")?;620     // Each chunk reaches the client before the next is produced, so a stream621     // that stalls mid-body is visible as a stall, not as a complete body.622     writer.flush()623 }624 625 /// Streams the chunks, then the terminating zero chunk. An `Err` item returns626 /// before the terminator: a truncated stream must not look complete.627 fn write_chunks<W: Write>(628     writer: &mut W,629     chunks: impl Iterator<Item = io::Result<Vec<u8>>>,630 ) -> io::Result<()> {631     for chunk in chunks {632         let chunk = chunk?;633         // A zero-size chunk is the terminator in chunked framing, so an empty634         // item mid-stream is skipped rather than written.635         if !chunk.is_empty() {636             write_chunk(writer, &chunk)?;637         }638     }639     writer.write_all(b"0\r\n\r\n")?;640     writer.flush()641 }642 643 /// Writes one response and ends the framing.644 ///645 /// The status line and the headers are written as given; then646 /// `Content-Length` for `Body::Bytes`, or `Transfer-Encoding: chunked` for647 /// `Body::Chunks`, then `Connection: close`, because this server serves one648 /// request per connection.649 pub fn write_response<W: Write>(writer: &mut W, response: Response) -> io::Result<()> {650     let mut head = format!(651         "HTTP/1.1 {} {}\r\n",652         response.status.0,653         response.status.reason()654     );655     for (name, value) in &response.headers {656         head.push_str(&format!("{name}: {value}\r\n"));657     }658     match &response.body {659         Body::Bytes(b) => head.push_str(&format!("Content-Length: {}\r\n", b.len())),660         Body::Chunks(_) => head.push_str("Transfer-Encoding: chunked\r\n"),661     }662     head.push_str("Connection: close\r\n\r\n");663     writer.write_all(head.as_bytes())?;664 665     match response.body {666         Body::Bytes(b) => writer.write_all(&b),667         Body::Chunks(chunks) => write_chunks(writer, chunks),668     }669 }670 671 /// Writes the interim response that a client waits for before a body.672 fn write_continue<W: Write>(mut writer: W) -> io::Result<()> {673     writer.write_all(b"HTTP/1.1 100 Continue\r\n\r\n")?;674     writer.flush()675 }676 677 /// The reply that closes one connection that found the gate full, then a678 /// short non-blocking drain of what the client already sent.679 ///680 /// A close with unread request bytes makes the kernel send a reset, and the681 /// reset can discard the 503 before the client reads it. The drain is bounded682 /// and never waits, so a busy client costs the acceptor no thread.683 fn refuse_busy_tcp(mut stream: TcpStream, limits: Limits) {684     let response = Response::text(Status::SERVICE_UNAVAILABLE, "busy\n");685     let _ = write_response(&mut stream, response);686     let _ = stream.set_read_timeout(Some(limits.read_timeout));687     let _ = stream.set_nonblocking(true);688     drain_busy(&mut stream, limits);689 }690 691 /// The Unix twin of [`refuse_busy_tcp`].692 fn refuse_busy_unix(mut stream: std::os::unix::net::UnixStream, limits: Limits) {693     let response = Response::text(Status::SERVICE_UNAVAILABLE, "busy\n");694     let _ = write_response(&mut stream, response);695     let _ = stream.set_read_timeout(Some(limits.read_timeout));696     let _ = stream.set_nonblocking(true);697     drain_busy(&mut stream, limits);698 }699 700 /// Reads what is already available, up to the inline request size. A read701 /// that would wait is the end of the drain.702 fn drain_busy<R: Read>(reader: &mut R, limits: Limits) {703     let mut left = limits.max_head_bytes.saturating_add(limits.max_body_bytes);704     let mut buf = [0u8; 1024];705     while left > 0 {706         let want = left.min(buf.len());707         match reader.read(&mut buf[..want]) {708             Ok(0) | Err(_) => break,709             Ok(n) => left -= n,710         }711     }712 }713 714 /// The short reply for a request that the parser refused. `None` means the715 /// connection is already unusable, so there is nothing to send.716 fn parse_refusal(why: ParseError) -> Option<Response> {717     match why {718         ParseError::BadRequest => Some(Response::text(Status::BAD_REQUEST, "bad request\n")),719         ParseError::Unsupported => Some(Response::text(Status::BAD_REQUEST, "unsupported\n")),720         ParseError::TooLarge => Some(Response::text(Status::TOO_LARGE, "too large\n")),721         ParseError::Timeout => Some(Response::text(Status::REQUEST_TIMEOUT, "request timeout\n")),722         ParseError::Expectation => Some(Response::text(723             Status::EXPECTATION_FAILED,724             "expectation failed\n",725         )),726         ParseError::Io(_) => None,727     }728 }729 730 /// Serves `listener` forever: one thread per connection, one request per731 /// connection, then close.732 ///733 /// A refused request gets a short text body: 400 for `ParseError::BadRequest`734 /// and `ParseError::Unsupported`, 408 for `ParseError::Timeout`, 413 for735 /// `ParseError::TooLarge`, and 417 for `ParseError::Expectation`. A reader736 /// error ends the connection with no reply. A connection above the concurrent737 /// limit gets 503 and is closed; an accept error that repeats returns from738 /// `serve`.739 pub fn serve<H>(listener: TcpListener, limits: Limits, handler: H) -> io::Result<()>740 where741     H: Fn(Request) -> Response + Send + Sync + 'static,742 {743     serve_until(listener, limits, &Stop::new(), handler)744 }745 746 /// Serves until `stop` is asked to stop, then waits for the connections that747 /// are still running.748 ///749 /// The listener is polled rather than blocked so that the flag is read without750 /// a second socket whose only job is to wake `accept`. The pause is the cost,751 /// and it is stated in [`Stop::pause`].752 pub fn serve_until<H>(753     listener: TcpListener,754     limits: Limits,755     stop: &Stop,756     handler: H,757 ) -> io::Result<()>758 where759     H: Fn(Request) -> Response + Send + Sync + 'static,760 {761     let handler = Arc::new(handler);762     listener.set_nonblocking(true)?;763     while !stop.stopping() {764         match listener.accept() {765             Ok((stream, _)) => {766                 stream.set_nonblocking(false)?;767                 let Some(slot) = stop.enter_connection(limits.max_connections) else {768                     let _ = stream.set_write_timeout(Some(limits.write_timeout));769                     refuse_busy_tcp(stream, limits);770                     continue;771                 };772                 let handler = Arc::clone(&handler);773                 let active = stop.enter();774                 // One thread per connection keeps a slow handler from holding775                 // the accept loop. `active` is released when the thread ends,776                 // which is what the drain waits for. `slot` is released there777                 // too, so a streamed body keeps its place in the cap.778                 let _ = thread::spawn(move || {779                     let _slot = slot;780                     let _active = active;781                     serve_connection(stream, limits, handler.as_ref());782                 });783             }784             Err(why) if why.kind() == io::ErrorKind::WouldBlock => thread::sleep(Stop::pause()),785             Err(why) => return Err(why),786         }787     }788     let _ = stop.wait();789     Ok(())790 }791 792 /// Serves a Unix socket forever: one thread per connection, one request per793 /// connection.794 ///795 /// The peer uid is filled in from the socket credentials, and nothing else796 /// differs from [`serve`]. The uid is what the auth module checks: possession of797 /// the socket is the credential, and the kernel is the one that says who798 /// connected (spec section 9.1).799 pub fn serve_unix<H>(800     listener: std::os::unix::net::UnixListener,801     limits: Limits,802     handler: H,803 ) -> io::Result<()>804 where805     H: Fn(Request) -> Response + Send + Sync + 'static,806 {807     serve_unix_until(listener, limits, &Stop::new(), handler)808 }809 810 /// The Unix twin of [`serve_until`]: the same accept loop and the same drain.811 pub fn serve_unix_until<H>(812     listener: std::os::unix::net::UnixListener,813     limits: Limits,814     stop: &Stop,815     handler: H,816 ) -> io::Result<()>817 where818     H: Fn(Request) -> Response + Send + Sync + 'static,819 {820     let handler = Arc::new(handler);821     listener.set_nonblocking(true)?;822     while !stop.stopping() {823         match listener.accept() {824             Ok((stream, _)) => {825                 stream.set_nonblocking(false)?;826                 let Some(slot) = stop.enter_connection(limits.max_connections) else {827                     let _ = stream.set_write_timeout(Some(limits.write_timeout));828                     refuse_busy_unix(stream, limits);829                     continue;830                 };831                 let handler = Arc::clone(&handler);832                 let active = stop.enter();833                 let _ = thread::spawn(move || {834                     let _slot = slot;835                     let _active = active;836                     serve_unix_connection(stream, limits, handler.as_ref());837                 });838             }839             Err(why) if why.kind() == io::ErrorKind::WouldBlock => thread::sleep(Stop::pause()),840             Err(why) => return Err(why),841         }842     }843     let _ = stop.wait();844     Ok(())845 }846 847 fn serve_unix_connection<H: Fn(Request) -> Response>(848     stream: std::os::unix::net::UnixStream,849     limits: Limits,850     handler: &H,851 ) {852     if stream.set_read_timeout(Some(limits.read_timeout)).is_err() {853         return;854     }855     if stream856         .set_write_timeout(Some(limits.write_timeout))857         .is_err()858     {859         return;860     }861     let uid = rustix::net::sockopt::socket_peercred(&stream)862         .ok()863         .map(|cred| cred.uid.as_raw());864     let response = {865         let mut reader = BufReader::new(&stream);866         match parse_request_with(&mut reader, &limits, || write_continue(&stream)) {867             Ok(mut request) => {868                 request.peer_uid = uid;869                 handler(request)870             }871             Err(why) => match parse_refusal(why) {872                 Some(response) => response,873                 None => return,874             },875         }876     };877     let mut stream = stream;878     let _ = write_response(&mut stream, response);879 }880 881 fn serve_connection<H: Fn(Request) -> Response>(882     mut stream: TcpStream,883     limits: Limits,884     handler: &H,885 ) {886     if stream.set_read_timeout(Some(limits.read_timeout)).is_err() {887         return;888     }889     if stream890         .set_write_timeout(Some(limits.write_timeout))891         .is_err()892     {893         return;894     }895     let response = {896         let mut reader = BufReader::new(&stream);897         match parse_request_with(&mut reader, &limits, || write_continue(&stream)) {898             Ok(request) => handler(request),899             Err(why) => match parse_refusal(why) {900                 Some(response) => response,901                 None => return,902             },903         }904     };905     let _ = write_response(&mut stream, response);906 }