Skip to main content

netio/
server.rs

1// server -- a blocking HTTP/1.1 server: one accept thread, a pool of worker threads, each
2// worker serves one connection at a time (keep-alive, pipelined requests in order)
3//
4//   Server::start(&addr, ServerConfig, handler) -> NetResult<Server>
5//   Server::start_with(.., Some(wrap))   wrap turns an accepted TcpStream into the Stream HTTP
6//                                        runs over (TLS) and the identity it proved
7//   server.local_addr() / server.stop()
8//
9// (G7d) A handler's answer with status 101 and Body::Upgrade (ws::Acceptor::accept) takes the
10// connection out of HTTP: the head goes out, the upgrade runs on a thread of its own (the worker
11// is free again), and stop() sets the Upgraded's stop flag and waits for those threads too.
12//
13// The handler runs on a worker thread; it must not panic (panics abort the process).
14// Requests with both Content-Length and Transfer-Encoding are refused (request smuggling).
15// A slow client holds a worker only so long: the head must arrive within read_ms, a body at
16// MIN_BODY_RATE on average after a first read_ms (over TLS too: records without data end a read
17// after read_ms).
18
19use alloc::boxed::Box;
20use alloc::string::String;
21use alloc::sync::Arc;
22use alloc::vec::Vec;
23use core::sync::atomic::{AtomicBool, Ordering};
24
25use plat::net::{NetResult, SocketAddr, TcpListener, TcpStream};
26use plat::sync::{channel, Mutex, Receiver};
27
28use crate::http::{self, Body, ReadError, Reader, Request, Response, Upgrade, Upgraded};
29use crate::Stream;
30
31/// the slowest request body a server waits for, in bytes a second on average (after a first
32/// read_ms): slower ones end the connection
33pub const MIN_BODY_RATE: u32 = 1024;
34
35#[derive(Clone, Copy, Debug)]
36pub struct ServerConfig {
37    /// worker threads (connections served at once)
38    pub threads: usize,
39    /// the largest request body
40    pub max_body: usize,
41    /// how long an idle keep-alive connection stays open
42    pub idle_ms: u32,
43    /// the longest wait for the next bytes of a request in progress; the head must be complete
44    /// within it, a body must bring 1 KiB a second on average after it (MIN_BODY_RATE)
45    pub read_ms: u32,
46    pub write_ms: u32,
47    /// requests per connection
48    pub max_requests: usize,
49}
50
51impl Default for ServerConfig {
52    fn default() -> Self {
53        ServerConfig { threads: 8, max_body: 64 << 20, idle_ms: 30_000, read_ms: 30_000, write_ms: 60_000, max_requests: 1000 }
54    }
55}
56
57pub type Handler = Arc<dyn Fn(&Request) -> Response + Send + Sync>;
58/// turns an accepted connection into the stream HTTP runs over and the identity it proved
59/// (None: drop the connection, e.g. a failed TLS handshake)
60pub type Wrap = Arc<dyn Fn(TcpStream) -> Option<(Box<dyn Stream>, Option<String>)> + Send + Sync>;
61
62pub struct Server {
63    addr: SocketAddr,
64    stop: Arc<AtomicBool>,
65    threads: Vec<plat::Thread>,
66    upgraded: Upgrades,
67}
68
69type Queue = Arc<Mutex<Receiver<(TcpStream, SocketAddr)>>>;
70/// (G7d) the threads of upgraded connections, each with the flag it sets when it is done
71type Upgrades = Arc<Mutex<Vec<(Arc<AtomicBool>, plat::Thread)>>>;
72
73impl Server {
74    pub fn start(addr: &SocketAddr, cfg: ServerConfig, handler: Handler) -> NetResult<Server> {
75        Server::start_with(addr, cfg, handler, None)
76    }
77
78    pub fn start_with(addr: &SocketAddr, cfg: ServerConfig, handler: Handler, wrap: Option<Wrap>) -> NetResult<Server> {
79        let listener = TcpListener::bind(addr)?;
80        let local = listener.local_addr()?;
81        let stop = Arc::new(AtomicBool::new(false));
82        let upgraded: Upgrades = Arc::new(Mutex::new(Vec::new()));
83        let (tx, rx) = channel::<(TcpStream, SocketAddr)>(cfg.threads.max(1) * 4);
84        let rx: Queue = Arc::new(Mutex::new(rx));
85        let mut threads = Vec::new();
86        for _ in 0..cfg.threads.max(1) {
87            let (rx, handler, wrap, stop, up) = (rx.clone(), handler.clone(), wrap.clone(), stop.clone(), upgraded.clone());
88            if let Some(t) = plat::thread_spawn(256 * 1024, Box::new(move || worker(rx, cfg, handler, wrap, stop, up))) {
89                threads.push(t);
90            }
91        }
92        let st = stop.clone();
93        let accept = plat::thread_spawn(64 * 1024, Box::new(move || {
94            while !st.load(Ordering::Relaxed) {
95                match listener.accept_timeout(200) {
96                    Ok(Some(c)) => {
97                        if tx.send(c).is_err() {
98                            break;
99                        }
100                    }
101                    Ok(None) => {}
102                    Err(_) => plat::sleep_ms(20),
103                }
104            }
105            // dropping tx ends the workers once the queue is empty
106        }));
107        if let Some(t) = accept {
108            threads.push(t);
109        }
110        Ok(Server { addr: local, stop, threads, upgraded })
111    }
112
113    pub fn local_addr(&self) -> SocketAddr {
114        self.addr
115    }
116
117    /// (G7d) upgraded connections (WebSockets) still running
118    pub fn upgraded(&self) -> usize {
119        self.upgraded.lock().iter().filter(|(done, _)| !done.load(Ordering::Acquire)).count()
120    }
121
122    /// stop accepting, finish the requests in progress, wait for the threads; upgraded
123    /// connections see their stop flag set and are waited for as well
124    pub fn stop(self) {
125        self.stop.store(true, Ordering::Relaxed);
126        for t in self.threads {
127            t.join();
128        }
129        let up = core::mem::take(&mut *self.upgraded.lock());
130        for (_, t) in up {
131            t.join();
132        }
133    }
134}
135
136/// (G7d) run an upgrade on a thread of its own; finished ones are joined on the way
137fn spawn_upgrade(upgrades: &Upgrades, up: Upgrade, conn: Upgraded) {
138    let done = Arc::new(AtomicBool::new(false));
139    let d = done.clone();
140    let t = plat::thread_spawn(256 * 1024, Box::new(move || {
141        up.run(conn);
142        d.store(true, Ordering::Release);
143    }));
144    let mut list = upgrades.lock();
145    let mut i = 0;
146    while i < list.len() {
147        if list[i].0.load(Ordering::Acquire) {
148            let (_, t) = list.swap_remove(i);
149            t.join();
150        } else {
151            i += 1;
152        }
153    }
154    if let Some(t) = t {
155        list.push((done, t));
156    }
157}
158
159fn worker(rx: Queue, cfg: ServerConfig, handler: Handler, wrap: Option<Wrap>, stop: Arc<AtomicBool>, upgrades: Upgrades) {
160    loop {
161        let next = rx.lock().recv();
162        let Some((tcp, peer)) = next else { return };
163        let _ = tcp.set_nodelay(true);
164        let (stream, id): (Box<dyn Stream>, Option<String>) = match &wrap {
165            Some(w) => {
166                tcp.set_read_timeout(Some(cfg.read_ms));
167                tcp.set_write_timeout(Some(cfg.write_ms));
168                match w(tcp) {
169                    Some(x) => x,
170                    None => continue,
171                }
172            }
173            None => (Box::new(tcp), None),
174        };
175        if let Some((up, buffered)) = serve(&*stream, peer, id, &cfg, &handler, &stop) {
176            stream.set_timeouts(None, None);
177            spawn_upgrade(&upgrades, up, Upgraded { stream, buffered, peer: Some(peer), stop: stop.clone() });
178        }
179    }
180}
181
182/// how long and how much a connection ended by an error answer still reads (see linger)
183const LINGER_MS: u64 = 2000;
184const LINGER_BYTES: usize = 1 << 20;
185
186/// answer an error and end the connection (-> None: serve's end without an upgrade)
187fn error<T>(s: &dyn Stream, status: u16, stop: &AtomicBool) -> Option<T> {
188    let mut r = Response::text(status, http::reason(status));
189    if http::write_response(s, &mut r, false, false) {
190        linger(s, stop);
191    }
192    None
193}
194
195/// end a connection whose request was not read to its end: send the end, then read and drop
196/// what the client still sends until it closes (at most LINGER_MS / LINGER_BYTES).  Closing a
197/// socket with unread bytes sends a reset, and a reset destroys the answer the client has not
198/// read yet (Windows drops its received bytes).
199fn linger(s: &dyn Stream, stop: &AtomicBool) {
200    s.shutdown();
201    s.set_timeouts(Some(250), Some(250));
202    let end = plat::time_us() + LINGER_MS * 1000;
203    let mut buf = alloc::vec![0u8; 16 * 1024];
204    let mut left = LINGER_BYTES;
205    while left > 0 && !stop.load(Ordering::Relaxed) && plat::time_us() < end {
206        if s.wait_readable(250) {
207            match s.read(&mut buf) {
208                Ok(n) if n > 0 => left = left.saturating_sub(n),
209                _ => return,
210            }
211        }
212    }
213}
214
215/// serve the requests of one connection -> an upgrade that takes it over (101 + Body::Upgrade),
216/// with the bytes read after its request
217fn serve(s: &dyn Stream, peer: SocketAddr, id: Option<String>, cfg: &ServerConfig, handler: &Handler, stop: &AtomicBool) -> Option<(Upgrade, Vec<u8>)> {
218    let mut rd = Reader::new(s);
219    for n in 0..cfg.max_requests {
220        if n > 0 && !rd.has_buffered() {
221            // idle keep-alive: wait in slices so a stop is noticed
222            let mut waited = 0;
223            loop {
224                if stop.load(Ordering::Relaxed) {
225                    s.shutdown();
226                    return None;
227                }
228                if s.wait_readable(250) {
229                    break;
230                }
231                waited += 250;
232                if waited >= cfg.idle_ms {
233                    s.shutdown();
234                    return None;
235                }
236            }
237        }
238        s.set_timeouts(Some(cfg.read_ms), Some(cfg.write_ms));
239        rd.set_deadline(Some(plat::time_us() + cfg.read_ms as u64 * 1000));
240        let head = rd.head();
241        rd.set_deadline(None);
242        let (start, headers) = match head {
243            Ok(x) => x,
244            // the client's end (its close_notify over TLS) is answered with ours (RFC 8446 6.1)
245            Err(ReadError::Closed) | Err(ReadError::Net(_)) => {
246                s.shutdown();
247                return None;
248            }
249            Err(ReadError::HeadTooLarge) => return error(s, 431, stop),
250            Err(_) => return error(s, 400, stop),
251        };
252        let mut parts = start.split(' ');
253        let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
254            return error(s, 400, stop);
255        };
256        let http11 = match version {
257            "HTTP/1.1" => true,
258            "HTTP/1.0" => false,
259            _ => return error(s, 505, stop),
260        };
261        if method.is_empty() || !method.bytes().all(|b| b.is_ascii_uppercase()) || !(target.starts_with('/') || target == "*") {
262            return error(s, 400, stop);
263        }
264        if target.len() > 8 * 1024 {
265            return error(s, 414, stop);
266        }
267        if headers.get("transfer-encoding").is_some() && headers.get("content-length").is_some() {
268            return error(s, 400, stop);
269        }
270        let keep = if http11 { !headers.has_token("connection", "close") } else { headers.has_token("connection", "keep-alive") };
271        if headers.has_token("expect", "100-continue") {
272            match headers.content_length() {
273                Err(()) => return error(s, 400, stop),
274                Ok(Some(n)) if n > cfg.max_body as u64 => return error(s, 413, stop),
275                _ => {}
276            }
277            if s.write_all(b"HTTP/1.1 100 Continue\r\n\r\n").is_err() {
278                return None;
279            }
280        }
281        // the body must keep moving: MIN_BODY_RATE bytes a second on average after a first
282        // read_ms (the head has its deadline; a body sent a byte at a time held a worker)
283        rd.set_min_rate(Some((MIN_BODY_RATE, cfg.read_ms)));
284        let body = rd.body(&headers, cfg.max_body, false);
285        rd.set_min_rate(None);
286        let body = match body {
287            Ok(b) => b,
288            Err(ReadError::BodyTooLarge) => return error(s, 413, stop),
289            Err(ReadError::Net(_)) | Err(ReadError::Closed) => {
290                s.shutdown();
291                return None;
292            }
293            Err(_) => return error(s, 400, stop),
294        };
295        let req = Request { method: String::from(method), target: String::from(target), headers, body, peer: Some(peer), client_id: id.clone() };
296        let mut resp = handler(&req);
297        // (G7d) a protocol takes the connection over: the head, then the upgrade's thread
298        if resp.status == 101 {
299            let Body::Upgrade(up) = core::mem::replace(&mut resp.body, Body::Empty) else {
300                return error(s, 500, stop);
301            };
302            if !http::write_switch(s, &resp) {
303                return None;
304            }
305            return Some((up, rd.take_buffered()));
306        }
307        let keep = keep && !stop.load(Ordering::Relaxed) && !resp.headers.has_token("connection", "close");
308        if !http::write_response(s, &mut resp, method == "HEAD", keep) || !keep {
309            s.shutdown();
310            return None;
311        }
312    }
313    s.shutdown();
314    None
315}