Skip to main content

rws_server/server/
mod.rs

1//! The listeners and connection loops.
2//!
3//! [`Server::setup`] binds the listener (and, in the `http1` build, creates the
4//! thread pool); then [`Server::run`] (`http1`), `run_tls` (TLS with HTTP/2 via
5//! ALPN, or plain HTTP/1.1 without a certificate), `run_quic` (HTTP/3) and
6//! `run_redirect` (HTTP → HTTPS) accept connections, parse requests and hand
7//! them to your [`Application`](crate::application::Application).
8//! [`ConnectionInfo`] carries the client and server addresses and the TLS SNI
9//! name. Examples: `src/server/example/`.
10
11#[cfg(all(test, not(target_arch = "wasm32")))]
12pub mod tests;
13/// Test helpers the facade's tests use too (feature `test-support`).
14#[cfg(all(any(test, feature = "test-support"), not(target_arch = "wasm32")))]
15#[doc(hidden)]
16pub mod test_support {
17    use std::cmp::min;
18    use std::io::{Read, Write};
19
20    pub struct MockTcpStream {
21        pub read_data: Vec<u8>,
22        pub write_data: Vec<u8>,
23    }
24
25    impl Read for MockTcpStream {
26        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
27            let size : usize = min(self.read_data.len(), buf.len());
28            buf[..size].copy_from_slice(&self.read_data[..size]);
29            Ok(size)
30        }
31    }
32
33    impl Write for MockTcpStream {
34
35        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
36            self.write_data = Vec::from(buf);
37            Ok(buf.len())
38        }
39
40        fn flush(&mut self) -> std::io::Result<()> {
41            Ok(())
42        }
43    }
44
45    impl Unpin for MockTcpStream {}
46}
47#[cfg(all(test, not(target_arch = "wasm32")))]
48mod example;
49#[cfg(feature = "http2")]
50#[doc(hidden)]
51pub mod http1_async;
52mod chunked_decoder;
53#[cfg(feature = "http2")]
54#[doc(hidden)]
55pub mod body_stream;
56#[cfg(feature = "http2")]
57pub(crate) mod body_pump;
58#[cfg(feature = "http2")]
59pub(crate) mod sendfile;
60#[cfg(feature = "http2")]
61pub mod per_core;
62#[doc(hidden)]
63pub mod framing;
64pub mod proxy_protocol;
65
66// The TCP/thread-pool accept loop below (`Server::setup`/`run`/`process`/…) needs
67// `std::net::TcpListener` and OS threads, neither available on `wasm32-wasip2`.
68// `ConnectionInfo`/`Address` further down have no socket dependency and stay
69// compiled on every target — see spec/WASM_SHIM.md for the guest-adapter that
70// replaces this accept loop under WASI.
71#[cfg(not(target_arch = "wasm32"))]
72use std::io::prelude::*;
73#[cfg(not(target_arch = "wasm32"))]
74use std::borrow::Borrow;
75#[cfg(not(target_arch = "wasm32"))]
76use std::net::{IpAddr, SocketAddr, TcpListener};
77#[cfg(not(target_arch = "wasm32"))]
78use std::str::FromStr;
79#[cfg(not(target_arch = "wasm32"))]
80use std::time::Duration;
81
82#[cfg(not(target_arch = "wasm32"))]
83use crate::request::{METHOD, Request};
84#[cfg(not(target_arch = "wasm32"))]
85use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
86#[cfg(not(target_arch = "wasm32"))]
87use crate::app::App;
88#[cfg(not(target_arch = "wasm32"))]
89use crate::application::Application;
90#[cfg(not(target_arch = "wasm32"))]
91use crate::entry_point::{bootstrap, get_ip_port_thread_count, get_request_allocation_size, set_default_values};
92#[cfg(not(target_arch = "wasm32"))]
93use crate::header::Header;
94#[cfg(not(target_arch = "wasm32"))]
95use crate::log::Log;
96#[cfg(not(target_arch = "wasm32"))]
97use crate::symbol::SYMBOL;
98#[cfg(not(target_arch = "wasm32"))]
99use crate::thread_pool::ThreadPool;
100
101#[cfg(not(target_arch = "wasm32"))]
102/// Longest time from the first byte of a request head to its end (nginx's
103/// `client_header_timeout`). The idle timeout alone restarts on every read,
104/// so a client sending one byte every few seconds could hold a connection
105/// for weeks with a 64 KiB head.
106pub const REQUEST_HEAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
107
108/// Largest read (and write) [`Server::pipe_stream`] makes. It was 8 KiB with
109/// three writes per chunk: over HTTP/1.1 a proxied 55 MB download ran at
110/// 1.8 MB/s against 90 MB/s over HTTP/2.
111#[doc(hidden)]
112pub const PIPE_CHUNK: usize = 64 * 1024;
113
114/// The response's `Content-Length`, when it has exactly one valid value
115/// (repeats of the same value count as one). `None` for none, an invalid
116/// value, or conflicting values: the body is then sent chunked.
117#[cfg(not(target_arch = "wasm32"))]
118fn single_content_length(response: &Response) -> Option<u64> {
119    let mut found: Option<u64> = None;
120    for h in response.headers.iter().filter(|h| h.name.eq_ignore_ascii_case("content-length")) {
121        let value = h.value.trim();
122        if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
123            return None;
124        }
125        let len: u64 = value.parse().ok()?;
126        match found {
127            Some(prev) if prev != len => return None,
128            _ => found = Some(len),
129        }
130    }
131    found
132}
133
134pub struct Server {}
135#[cfg(not(target_arch = "wasm32"))]
136impl Server {
137    pub fn process_request(mut stream: impl Read + Write + Unpin, peer_addr: SocketAddr) -> Vec<u8> {
138        let request_allocation_size = get_request_allocation_size();
139        let mut buffer = vec![0; request_allocation_size as usize];
140        let boxed_read = stream.read(&mut buffer);
141        if boxed_read.is_err() {
142            let message = boxed_read.err().unwrap().to_string();
143            eprintln!("unable to read TCP stream {}", &message);
144
145            let raw_response = Server::bad_request_response(message);
146            let boxed_stream = stream.write(raw_response.borrow());
147            if boxed_stream.is_ok() {
148                stream.flush().unwrap();
149            };
150            return raw_response;
151        }
152
153        boxed_read.unwrap();
154        let request : &[u8] = &buffer;
155
156        // let raw_request = String::from_utf8(Vec::from(request)).unwrap();
157        // println!("\n\n______{}______\n\n", raw_request);
158
159
160        let boxed_request = Request::parse_request(request);
161        if boxed_request.is_err() {
162            let message = boxed_request.err().unwrap();
163            eprintln!("unable to parse request: {}", &message);
164
165            let raw_response = Server::bad_request_response(message);
166            let boxed_stream = stream.write(raw_response.borrow());
167            if boxed_stream.is_ok() {
168                stream.flush().unwrap();
169            };
170            return raw_response;
171        }
172
173
174        let request: Request = boxed_request.unwrap();
175        let (response, request) = App::handle_request(request);
176
177
178        let log_request_response = Log::combined(&request, &response, &peer_addr);
179        println!("{}", log_request_response);
180        let raw_response = Response::generate_response(response, request);
181
182        let boxed_stream = stream.write(raw_response.borrow());
183        if boxed_stream.is_ok() {
184            stream.flush().unwrap();
185        };
186
187        raw_response
188    }
189
190    pub fn bad_request_response(message: String) -> Vec<u8> {
191        let error_request = Request {
192            method: METHOD.get.to_string(),
193            request_uri: "".to_string(),
194            http_version: "".to_string(),
195            headers: vec![],
196            body: Default::default(),
197        };
198
199        let (body, content_type) = crate::error::problem::from_text(STATUS_CODE_REASON_PHRASE.n400_bad_request, &message);
200        let content_range = crate::range::Range::get_content_range(body, content_type.to_string());
201
202        let header_list = Header::get_header_list(&error_request);
203        let error_response: Response = Response::get_response(
204            STATUS_CODE_REASON_PHRASE.n400_bad_request,
205            Some(header_list),
206            Some(vec![content_range])
207        );
208
209        let response = Response::generate_response(error_response, error_request);
210        return response;
211    }
212
213    /// Builds a `413 Payload Too Large` raw response for a request whose declared
214    /// `Content-Length` exceeds `RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES`. The connection
215    /// is always closed after this is sent (see [`Server::process`]) — the client's
216    /// unread body bytes are still queued on the socket, so keep-alive framing
217    /// can't be trusted.
218    pub fn payload_too_large_response(message: String) -> Vec<u8> {
219        let error_request = Request {
220            method: METHOD.get.to_string(),
221            request_uri: "".to_string(),
222            http_version: "".to_string(),
223            headers: vec![],
224            body: Default::default(),
225        };
226
227        let (body, content_type) = crate::error::problem::from_text(STATUS_CODE_REASON_PHRASE.n413_payload_too_large, &message);
228        let content_range = crate::range::Range::get_content_range(body, content_type.to_string());
229
230        let mut header_list = Header::get_header_list(&error_request);
231        header_list.push(Header { name: Header::_CONNECTION.into(), value: "close".into() });
232        let error_response: Response = Response::get_response(
233            STATUS_CODE_REASON_PHRASE.n413_payload_too_large,
234            Some(header_list),
235            Some(vec![content_range])
236        );
237
238        Response::generate_response(error_response, error_request)
239    }
240
241    /// Builds a `431 Request Header Fields Too Large` raw response for a
242    /// request head longer than [`framing::MAX_HEAD_SIZE`]. The connection is
243    /// closed after it: the rest of the oversized head is still unread.
244    pub fn header_fields_too_large_response() -> Vec<u8> {
245        Server::closing_error_response(
246            STATUS_CODE_REASON_PHRASE.n431_request_header_fields_too_large,
247            format!("431 Request Header Fields Too Large: the request head exceeds {} bytes", framing::MAX_HEAD_SIZE),
248        )
249    }
250
251    /// Builds a `408 Request Timeout` raw response for a client that started
252    /// a request head but didn't finish it within [`REQUEST_HEAD_TIMEOUT`].
253    /// The connection is closed after it.
254    pub fn request_timeout_response() -> Vec<u8> {
255        Server::closing_error_response(
256            STATUS_CODE_REASON_PHRASE.n408_request_timeout,
257            format!("408 Request Timeout: the request head took longer than {} s", REQUEST_HEAD_TIMEOUT.as_secs()),
258        )
259    }
260
261    /// A plain-text error response with `Connection: close`.
262    fn closing_error_response(status: &'static crate::response::StatusCodeReasonPhrase, message: String) -> Vec<u8> {
263        let error_request = Request {
264            method: METHOD.get.to_string(),
265            request_uri: "".to_string(),
266            http_version: "".to_string(),
267            headers: vec![],
268            body: Default::default(),
269        };
270
271        let (body, content_type) = crate::error::problem::from_text(status, &message);
272        let content_range = crate::range::Range::get_content_range(body, content_type.to_string());
273
274        let mut header_list = Header::get_header_list(&error_request);
275        header_list.push(Header { name: Header::_CONNECTION.into(), value: "close".into() });
276        let error_response: Response = Response::get_response(status, Some(header_list), Some(vec![content_range]));
277
278        Response::generate_response(error_response, error_request)
279    }
280
281    /// Builds the `100 Continue` interim response (RFC 9110 §15.2.1) — no
282    /// headers, no body, just the status line. Sent immediately after parsing
283    /// a request with `Expect: 100-continue`, before reading its body, so the
284    /// client (which is waiting for this before it uploads the body) doesn't
285    /// stall or time out. See [`Server::process`] for where this is sent from.
286    pub fn continue_response() -> Vec<u8> {
287        let dummy_request = Request {
288            method: METHOD.get.to_string(),
289            request_uri: "".to_string(),
290            http_version: "".to_string(),
291            headers: vec![],
292            body: Default::default(),
293        };
294        let response = Response::get_response(STATUS_CODE_REASON_PHRASE.n100_continue, None, None);
295        Response::generate_response(response, dummy_request)
296    }
297
298    /// Builds a `417 Expectation Failed` raw response for an `Expect` header
299    /// value other than `100-continue` (RFC 9110 §10.1.1) — the only
300    /// expectation this server understands. Sent instead of reading the
301    /// request body, since the expectation can't be met either way.
302    pub fn expectation_failed_response(message: String) -> Vec<u8> {
303        let error_request = Request {
304            method: METHOD.get.to_string(),
305            request_uri: "".to_string(),
306            http_version: "".to_string(),
307            headers: vec![],
308            body: Default::default(),
309        };
310
311        let (body, content_type) = crate::error::problem::from_text(STATUS_CODE_REASON_PHRASE.n417_expectation_failed, &message);
312        let content_range = crate::range::Range::get_content_range(body, content_type.to_string());
313
314        let mut header_list = Header::get_header_list(&error_request);
315        header_list.push(Header { name: Header::_CONNECTION.into(), value: "close".into() });
316        let error_response: Response = Response::get_response(
317            STATUS_CODE_REASON_PHRASE.n417_expectation_failed,
318            Some(header_list),
319            Some(vec![content_range])
320        );
321
322        Response::generate_response(error_response, error_request)
323    }
324
325    pub fn process(stream: impl Read + Write + Unpin,
326                   connection: ConnectionInfo,
327                   app: impl Application) -> Result<(), String> {
328        // Without an owned socket a WebSocket upgrade can't be handed over.
329        Self::process_upgradable(stream, connection, app, |_| None)
330    }
331
332    /// [`Self::process`], with `split` giving an upgraded connection
333    /// (`WebSocket::upgrade`) its own reader and writer — `None` when this
334    /// stream can't be handed over (the upgrade is refused with a 500).
335    fn process_upgradable<S: Read + Write + Unpin>(
336        mut stream: S,
337        connection: ConnectionInfo,
338        app: impl Application,
339        split: impl Fn(&mut S) -> Option<(Box<dyn Read + Send>, Box<dyn Write + Send>)>,
340    ) -> Result<(), String> {
341
342        let request_allocation_size = connection.request_size;
343        let client = connection.client.clone();
344        let client_addr = SocketAddr::new(IpAddr::from_str(client.ip.as_str()).unwrap(), client.port as u16);
345
346        let max_body_size = crate::entry_point::get_max_body_size();
347
348        // Bytes read from the connection but not consumed yet: the rest of a
349        // request head, a body, or the next pipelined request.
350        let mut pending: Vec<u8> = Vec::new();
351        let mut read_buffer = vec![0u8; request_allocation_size as usize];
352
353        'session: loop {
354            // Read until the request head is complete — it may span several
355            // reads, but must finish within REQUEST_HEAD_TIMEOUT of its first
356            // byte (checked after each read; every read is itself bounded by
357            // the socket's read timeout).
358            let mut head_started: Option<std::time::Instant> = None;
359            let head_len = loop {
360                framing::skip_leading_empty_lines(&mut pending);
361                match framing::scan_head(&pending) {
362                    framing::HeadScan::Complete(n) => break Some(n),
363                    framing::HeadScan::TooLarge => {
364                        let _ = stream.write_all(&Server::header_fields_too_large_response());
365                        let _ = stream.flush();
366                        return Err("request head too large".to_string());
367                    }
368                    framing::HeadScan::Incomplete => {}
369                }
370                if !pending.is_empty() && head_started.is_none() {
371                    head_started = Some(std::time::Instant::now());
372                }
373                match stream.read(&mut read_buffer) {
374                    // timeout or client closed — normal end of keep-alive session
375                    Ok(0) | Err(_) => break None,
376                    Ok(n) => pending.extend_from_slice(&read_buffer[..n]),
377                }
378                let started = *head_started.get_or_insert_with(std::time::Instant::now);
379                if started.elapsed() > REQUEST_HEAD_TIMEOUT && framing::scan_head(&pending) == framing::HeadScan::Incomplete {
380                    let _ = stream.write_all(&Server::request_timeout_response());
381                    let _ = stream.flush();
382                    return Err("request head timed out".to_string());
383                }
384            };
385            let Some(head_len) = head_len else { break };
386
387            let parsed = Request::parse(&pending[..head_len])
388                .and_then(|request| framing::validate_head(&pending[..head_len], &request).map(|_| request))
389                .and_then(|request| framing::body_framing(&request).map(|f| (request, f)));
390            pending.drain(..head_len);
391            let (mut request, body_framing) = match parsed {
392                Ok(parsed) => parsed,
393                Err(message) => {
394                    let _ = stream.write_all(&Server::bad_request_response(message.clone()));
395                    let _ = stream.flush();
396                    return Err(message);
397                }
398            };
399
400            // RFC 9110 §10.1.1 `Expect` — the only expectation this server
401            // understands is `100-continue`; anything else fails fast with a
402            // final status instead of reading a body we can't act on.
403            let expects_continue = match request.header(Header::_EXPECT) {
404                Some(h) if h.value.trim().eq_ignore_ascii_case("100-continue") => true,
405                Some(h) => {
406                    let raw_response = Server::expectation_failed_response(format!(
407                        "417 Expectation Failed: unsupported Expect value '{}'", h.value.trim()
408                    ));
409                    let _ = stream.write_all(&raw_response);
410                    let _ = stream.flush();
411                    break;
412                }
413                None => false,
414            };
415
416            match body_framing {
417                framing::BodyFraming::None => {}
418                framing::BodyFraming::Length(declared_len) => {
419                    if max_body_size > 0 && declared_len > max_body_size {
420                        let raw_response = Server::payload_too_large_response(format!(
421                            "413 Payload Too Large: declared Content-Length {} exceeds the {} byte limit",
422                            declared_len, max_body_size
423                        ));
424                        let _ = stream.write_all(&raw_response);
425                        let _ = stream.flush();
426                        break;
427                    }
428
429                    // Tell the client to go ahead and send the body now, before we
430                    // block waiting for it below.
431                    if expects_continue && (pending.len() as u64) < declared_len {
432                        if stream.write_all(&Server::continue_response()).and_then(|_| stream.flush()).is_err() {
433                            break;
434                        }
435                    }
436
437                    while (pending.len() as u64) < declared_len {
438                        match stream.read(&mut read_buffer) {
439                            Ok(0) | Err(_) => break 'session, // closed or stalled mid-body
440                            Ok(k) => pending.extend_from_slice(&read_buffer[..k]),
441                        }
442                    }
443                    request.body = pending.drain(..declared_len as usize).collect::<Vec<u8>>().into();
444                }
445                framing::BodyFraming::Chunked => {
446                    if expects_continue && pending.is_empty() {
447                        if stream.write_all(&Server::continue_response()).and_then(|_| stream.flush()).is_err() {
448                            break;
449                        }
450                    }
451
452                    let mut decoder = framing::ChunkedBody::new(max_body_size);
453                    loop {
454                        match decoder.feed(&pending) {
455                            Ok((consumed, done)) => {
456                                pending.drain(..consumed);
457                                if done { break; }
458                            }
459                            Err(framing::ChunkError::TooLarge) => {
460                                let raw_response = Server::payload_too_large_response(format!(
461                                    "413 Payload Too Large: chunked body exceeds the {} byte limit", max_body_size
462                                ));
463                                let _ = stream.write_all(&raw_response);
464                                let _ = stream.flush();
465                                break 'session;
466                            }
467                            Err(framing::ChunkError::Malformed(message)) => {
468                                let _ = stream.write_all(&Server::bad_request_response(message.clone()));
469                                let _ = stream.flush();
470                                return Err(message);
471                            }
472                        }
473                        match stream.read(&mut read_buffer) {
474                            Ok(0) | Err(_) => break 'session,
475                            Ok(k) => pending.extend_from_slice(&read_buffer[..k]),
476                        }
477                    }
478                    request.body = decoder.body.into();
479                }
480            }
481
482            let keep_alive = framing::keep_alive(&request);
483
484            let started = std::time::Instant::now();
485            // The handler runs on this thread, which owns the socket: its
486            // `103`s are written once it returns, before the response.
487            let result = if crate::early_hints::http1_wanted(&request) {
488                let hints: std::sync::Arc<std::sync::Mutex<Vec<Vec<String>>>> = Default::default();
489                let queue = std::sync::Arc::clone(&hints);
490                let sink = crate::early_hints::Sink::new(move |links| queue.lock().unwrap_or_else(|e| e.into_inner()).push(links));
491                let result = crate::early_hints::with_sink(Some(sink), || app.execute(&request, &connection));
492                for links in std::mem::take(&mut *hints.lock().unwrap_or_else(|e| e.into_inner())) {
493                    if stream.write_all(&crate::early_hints::http1_head(&links)).is_err() {
494                        return Err("client closed the connection".to_string());
495                    }
496                }
497                result
498            } else {
499                app.execute(&request, &connection)
500            };
501            let mut response = match result {
502                Ok(r) => r,
503                Err(message) => {
504                    crate::metrics::http::observe(&request.method, 400, false, &request.http_version, started);
505                    let raw_response = Server::bad_request_response(message.clone());
506                    let boxed_stream = stream.write(raw_response.borrow());
507                    if boxed_stream.is_ok() { stream.flush().unwrap(); }
508                    return Err(message);
509                }
510            };
511
512            crate::metrics::record_request();
513            crate::metrics::http::observe(&request.method, response.status_code, false, &request.http_version, started);
514            // A WebSocket upgrade: send the 101, then the connection is the
515            // handler's, on a thread of its own.
516            if let Some(upgrade) = crate::websocket::take_upgrade(&mut response) {
517                let Some((reader, writer)) = split(&mut stream) else {
518                    let _ = stream.write_all(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
519                    let _ = stream.flush();
520                    return Err("WebSocket upgrade on a connection that can't be handed over".to_string());
521                };
522                Log::log_served(&request, &mut response, &client_addr);
523                stream.write_all(&crate::websocket::upgrade_head(&response)).and_then(|_| stream.flush()).map_err(|e| e.to_string())?;
524                let reader = std::io::Cursor::new(std::mem::take(&mut pending)).chain(reader);
525                std::thread::spawn(move || upgrade.run(Box::new(reader), writer));
526                return Ok(());
527            }
528            crate::compression::apply_compression(&request, &mut response);
529            response.drop_content_for_status();
530
531            response.headers.push(Header {
532                name: Header::_CONNECTION.into(),
533                value: if keep_alive { "keep-alive".into() } else { "close".into() },
534            });
535
536            Log::log_served(&request, &mut response, &client_addr);
537
538            if let Some(reader) = response.stream_pipe.take() {
539                if let Err(e) = Server::pipe_stream(&mut stream, response, request, reader) {
540                    return Err(e);
541                }
542            } else if let Some(ref filepath) = response.stream_file.clone() {
543                if let Err(e) = Server::write_chunked_file(&mut stream, response, request, filepath) {
544                    return Err(e);
545                }
546            } else {
547                let raw_response = Response::generate_response(response, request);
548                // write_all: a single write() may accept only part of a large response.
549                if let Err(e) = stream.write_all(raw_response.borrow()) {
550                    return Err(e.to_string());
551                }
552                stream.flush().unwrap();
553            }
554
555            if !keep_alive { break; }
556        }
557
558        Ok(())
559    }
560
561    /// Streams a file to `stream` using HTTP/1.1 chunked transfer encoding.
562    /// The response headers are written first, then the file is read and written in 64 KB chunks.
563    #[doc(hidden)]
564    pub fn write_chunked_file(
565        stream: &mut impl Write,
566        response: Response,
567        request: Request,
568        filepath: &str,
569    ) -> Result<(), String> {
570        use std::fs::File;
571        use std::io::Read as _;
572
573        let (head, chunked) = Server::stream_file_head(response);
574        stream.write_all(&head).map_err(|e| e.to_string())?;
575
576        if request.method != METHOD.head {
577            let mut file = File::open(filepath).map_err(|e| e.to_string())?;
578            let mut buf = vec![0u8; 65536];
579            loop {
580                let n = file.read(&mut buf).map_err(|e| e.to_string())?;
581                if n == 0 { break; }
582                if chunked {
583                    // chunk header: hex size + CRLF
584                    stream.write_all(format!("{:x}\r\n", n).as_bytes()).map_err(|e| e.to_string())?;
585                    stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
586                    stream.write_all(b"\r\n").map_err(|e| e.to_string())?;
587                } else {
588                    stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
589                }
590            }
591            if chunked {
592                // terminal chunk
593                stream.write_all(b"0\r\n\r\n").map_err(|e| e.to_string())?;
594            }
595        }
596
597        stream.flush().map_err(|e| e.to_string())
598    }
599
600    /// The status line and headers of a `stream_file` response, and whether
601    /// its body is sent chunked. With a known Content-Length (static files
602    /// set it) the body goes out as-is; Transfer-Encoding: chunked is only
603    /// for an unknown length. Sending both is forbidden (RFC 9112 §6.1) —
604    /// mismatched handling of the two by intermediaries is how request
605    /// smuggling happens.
606    #[doc(hidden)]
607    pub fn stream_file_head(mut response: Response) -> (Vec<u8>, bool) {
608        let chunked = !response.headers.iter().any(|h| h.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH));
609        if chunked {
610            response.headers.push(Header {
611                name: Header::_TRANSFER_ENCODING.into(),
612                value: "chunked".into(),
613            });
614        }
615
616        // build status line + headers (no body)
617        let status = [
618            response.http_version.clone(),
619            response.status_code.to_string(),
620            Header::single_line(&response.reason_phrase).into_owned(),
621        ].join(SYMBOL.whitespace);
622
623        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
624        for header in &response.headers {
625            headers_str.push_str(&Header::single_line(&header.name));
626            headers_str.push_str(Header::NAME_VALUE_SEPARATOR);
627            headers_str.push_str(&Header::single_line(&header.value));
628            headers_str.push_str(SYMBOL.new_line_carriage_return);
629        }
630        let head = format!("{}{}{}", status, headers_str, SYMBOL.new_line_carriage_return);
631        (head.into_bytes(), chunked)
632    }
633
634    /// Streams a `Read` source to `stream` over HTTP/1.1.
635    ///
636    /// Called when `response.stream_pipe` is set (proxy passthrough for SSE, AI token
637    /// streams, and large downloads). The framing follows the response's headers:
638    /// - `Transfer-Encoding: chunked` (a chunked upstream): decoded and framed again, so
639    ///   the body ends at the upstream's last chunk, not when its connection closes;
640    /// - one valid `Content-Length` (a large upstream download): kept, and exactly that
641    ///   many bytes are copied, so the client can tell a complete body from a cut one;
642    /// - neither (SSE, a pipe of unknown length): wrapped in chunked framing here.
643    ///
644    /// A read error, or a body shorter than its `Content-Length`, returns `Err` without
645    /// ending the body (no terminating chunk), and the caller closes the connection:
646    /// the client sees a broken transfer, never a truncated body that looks complete.
647    /// Reads are up to [`PIPE_CHUNK`] bytes and each becomes one write.
648    #[doc(hidden)]
649    pub fn pipe_stream(
650        stream: &mut impl Write,
651        mut response: Response,
652        request: Request,
653        mut reader: Box<dyn std::io::Read + Send>,
654    ) -> Result<(), String> {
655        let backend_is_chunked = response.headers.iter().any(|h| {
656            h.name.eq_ignore_ascii_case("transfer-encoding")
657                && h.value.to_lowercase().contains("chunked")
658        });
659        let declared_length = if backend_is_chunked { None } else { single_content_length(&response) };
660
661        response.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-length"));
662        if let Some(len) = declared_length {
663            response.headers.push(Header { name: Header::_CONTENT_LENGTH.into(), value: len.to_string().into() });
664        } else if !backend_is_chunked {
665            response.headers.push(Header {
666                name: Header::_TRANSFER_ENCODING.into(),
667                value: "chunked".into(),
668            });
669        }
670
671        let status = [
672            response.http_version.clone(),
673            response.status_code.to_string(),
674            Header::single_line(&response.reason_phrase).into_owned(),
675        ].join(SYMBOL.whitespace);
676
677        let mut head = format!("{}\r\n", status);
678        for header in &response.headers {
679            head.push_str(&Header::single_line(&header.name));
680            head.push_str(Header::NAME_VALUE_SEPARATOR);
681            head.push_str(&Header::single_line(&header.value));
682            head.push_str(SYMBOL.new_line_carriage_return);
683        }
684        head.push_str(SYMBOL.new_line_carriage_return);
685        stream.write_all(head.as_bytes()).map_err(|e| e.to_string())?;
686
687        if request.method != METHOD.head {
688            // Room for a chunk-size line in front and the CRLF behind, so a
689            // re-encoded chunk is one write too.
690            const FRAME_ROOM: usize = 16;
691            let mut buf = vec![0u8; FRAME_ROOM + PIPE_CHUNK + 2];
692            let read_failed = |e: std::io::Error| format!("upstream body read failed: {}", e);
693            if backend_is_chunked {
694                // Copying the raw frames read past the last chunk into the
695                // upstream's idle keep-alive connection, until its read
696                // timeout: decode (which stops at the last chunk), frame again
697                // below. Upstream trailers are not forwarded over HTTP/1.1.
698                reader = Box::new(chunked_decoder::ChunkedDecoder::new(reader));
699            }
700            if let Some(len) = declared_length {
701                // Known length: copy exactly that many bytes, unframed.
702                let mut remaining = len;
703                while remaining > 0 {
704                    let want = remaining.min(PIPE_CHUNK as u64) as usize;
705                    let n = reader.read(&mut buf[..want]).map_err(read_failed)?;
706                    if n == 0 {
707                        return Err(format!("upstream body ended after {} of {} bytes", len - remaining, len));
708                    }
709                    stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
710                    remaining -= n as u64;
711                }
712            } else {
713                // Re-encode: wrap the raw byte stream in chunked framing so
714                // the client receives each fragment as it arrives (SSE).
715                loop {
716                    let n = reader.read(&mut buf[FRAME_ROOM..FRAME_ROOM + PIPE_CHUNK]).map_err(read_failed)?;
717                    if n == 0 {
718                        break;
719                    }
720                    let size_line = format!("{:x}\r\n", n);
721                    let start = FRAME_ROOM - size_line.len();
722                    buf[start..FRAME_ROOM].copy_from_slice(size_line.as_bytes());
723                    let end = FRAME_ROOM + n;
724                    buf[end..end + 2].copy_from_slice(b"\r\n");
725                    stream.write_all(&buf[start..end + 2]).map_err(|e| e.to_string())?;
726                    stream.flush().map_err(|e| e.to_string())?;
727                }
728                stream.write_all(b"0\r\n\r\n").map_err(|e| e.to_string())?;
729            }
730        }
731
732        stream.flush().map_err(|e| e.to_string())
733    }
734
735    /// Reads configuration (IP, port, thread count, TLS paths) from the layered config system
736    /// and returns a bound `TcpListener` and a sized `ThreadPool`. Call once at startup.
737    pub fn setup() -> Result<(TcpListener, ThreadPool), String> {
738        let verbose = crate::entry_point::verbose();
739        if verbose {
740            let info = Log::info("Rust Web Server");
741            println!("{}", info);
742            // Not the whole usage text on every start (it was ~150 lines ahead
743            // of the lines that matter); `rws --help` prints it.
744            println!("Every setting: rws --help, or https://rws8.tech/docs/configuration/env-vars/\n");
745            println!("RWS Configuration Start: \n");
746        }
747
748        set_default_values();
749        bootstrap();
750
751        #[cfg(feature = "secrets")]
752        crate::secrets::resolve_env_vars().map_err(|e| e.to_string())?;
753
754        if verbose {
755            println!("\nRWS Configuration End\n\n");
756        }
757
758
759        let (ip, port, thread_count) = get_ip_port_thread_count();
760
761
762        let mut ip_readable = ip.to_string();
763
764        if ip.contains(":") {
765            ip_readable = [SYMBOL.opening_square_bracket, &ip, SYMBOL.closing_square_bracket].join("");
766        }
767
768        let bind_addr = [ip_readable, SYMBOL.colon.to_string(), port.to_string()].join(SYMBOL.empty_string);
769
770        #[cfg(feature = "http2")]
771        let protocol = {
772            let cert = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE).unwrap_or_default();
773            if cert.is_empty() { "http" } else { "https" }
774        };
775        #[cfg(not(feature = "http2"))]
776        let protocol = "http";
777
778        crate::entry_point::note(&format!("Setting up {}://{}...", protocol, bind_addr));
779
780        // A socket systemd passed (socket activation), else our own.
781        #[cfg(all(unix, any(feature = "http1", feature = "http2")))]
782        let inherited = bind_addr.parse::<std::net::SocketAddr>().ok().and_then(|addr| crate::systemd::tcp(addr, Some(protocol)));
783        #[cfg(not(all(unix, any(feature = "http1", feature = "http2"))))]
784        let inherited: Option<TcpListener> = None;
785        let boxed_listener = match inherited {
786            Some(listener) => Ok(listener),
787            None => TcpListener::bind(&bind_addr),
788        };
789        if let Err(e) = &boxed_listener {
790            return Err(bind_error_message(&bind_addr, e));
791        }
792
793        let listener = boxed_listener.unwrap();
794        let pool = ThreadPool::new(thread_count as usize);
795
796        if verbose {
797            let server_url_thread_count = Log::server_url_thread_count(protocol, &bind_addr, thread_count);
798            println!("{}", server_url_thread_count);
799        } else {
800            print!("{}", startup_summary(protocol, &ip, port));
801        }
802
803        Ok((listener, pool))
804    }
805
806    /// Accepts TCP connections in a loop and dispatches each to the thread pool.
807    ///
808    /// When built with the `http1` feature, Ctrl+C and SIGTERM stop the accept
809    /// loop gracefully: `SERVER_READY` is cleared and the pool drains all
810    /// in-flight connections before returning.
811    ///
812    /// For TLS/HTTP2/HTTP3 use [`Server::run_tls`].
813    pub fn run(listener: TcpListener,
814               pool: ThreadPool,
815               app: impl Application + Send + 'static + Clone) {
816        mark_serving();
817        #[cfg(feature = "http1")]
818        {
819            use std::sync::Arc;
820            use std::sync::atomic::{AtomicBool, Ordering};
821
822            let shutdown = Arc::new(AtomicBool::new(false));
823            let s = shutdown.clone();
824            if let Err(e) = ctrlc::set_handler(move || {
825                s.store(true, Ordering::SeqCst);
826            }) {
827                eprintln!("unable to install signal handler: {}", e);
828            }
829            crate::config_reload::install_sighup_handler();
830            if let Err(e) = listener.set_nonblocking(true) {
831                eprintln!("unable to set non-blocking listener: {}", e);
832            }
833
834            loop {
835                if shutdown.load(Ordering::SeqCst) {
836                    break;
837                }
838                if crate::config_reload::RELOAD_REQUESTED
839                    .compare_exchange(true, false, Ordering::SeqCst, Ordering::Relaxed)
840                    .is_ok()
841                {
842                    crate::config_reload::reload();
843                }
844                match listener.accept() {
845                    Ok((stream, peer_addr)) => {
846                        Server::dispatch_connection(stream, peer_addr, &pool, app.clone());
847                    }
848                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
849                        std::thread::sleep(Duration::from_millis(10));
850                    }
851                    Err(e) => {
852                        eprintln!("accept error: {}", e);
853                        break;
854                    }
855                }
856            }
857
858            crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
859            #[cfg(unix)]
860            crate::systemd::stopping();
861            println!("Shutting down — waiting for in-flight connections to finish");
862            pool.join();
863            println!("Server stopped");
864        }
865
866        #[cfg(not(feature = "http1"))]
867        {
868            for boxed_stream in listener.incoming() {
869                match boxed_stream {
870                    Err(e) => {
871                        eprintln!("unable to get TCP stream: {}", e);
872                        return;
873                    }
874                    Ok(stream) => {
875                        let peer_addr = match stream.peer_addr() {
876                            Ok(a) => a,
877                            Err(e) => {
878                                eprintln!("unable to read peer addr: {}", e);
879                                return;
880                            }
881                        };
882                        Server::dispatch_connection(stream, peer_addr, &pool, app.clone());
883                    }
884                }
885            }
886        }
887    }
888
889    fn dispatch_connection(
890        stream: std::net::TcpStream,
891        peer_addr: std::net::SocketAddr,
892        pool: &ThreadPool,
893        app: impl Application + Send + 'static + Clone,
894    ) {
895        print!("Connection established, ");
896        if let Ok(local) = stream.local_addr() {
897            print!("local addr: {}", local);
898        }
899        println!(", peer addr: {}", peer_addr);
900
901        let (server_ip, server_port, _thread_count) = get_ip_port_thread_count();
902        let connection = ConnectionInfo {
903            client: Address {
904                ip: peer_addr.ip().to_string(),
905                port: peer_addr.port() as i32,
906            },
907            server: Address {
908                ip: server_ip,
909                port: server_port,
910            },
911            request_size: get_request_allocation_size(),
912            sni_hostname: None,
913            tls: false,
914        };
915
916        if let Err(e) = stream.set_read_timeout(Some(Duration::from_secs(30))) {
917            eprintln!("failed to set read timeout: {}", e);
918        }
919
920        pool.execute(move || {
921            let mut stream = stream;
922            let mut connection = connection;
923            if proxy_protocol::enabled() {
924                // Read on the worker: a slow load balancer mustn't hold the accept loop.
925                match proxy_protocol::read_blocking(&mut stream) {
926                    Ok(Some(source)) => {
927                        connection.client = Address { ip: source.ip().to_string(), port: source.port() as i32 };
928                    }
929                    Ok(None) => {}
930                    Err(e) => {
931                        eprintln!("PROXY protocol header from {}: {}", peer_addr, e);
932                        return;
933                    }
934                }
935            }
936            crate::metrics::connection_open();
937            let result = Server::process_upgradable(stream, connection, app, |stream| {
938                let reader = stream.try_clone().ok()?;
939                let writer = stream.try_clone().ok()?;
940                // The 30 s request read timeout doesn't apply to a WebSocket.
941                let _ = reader.set_read_timeout(None);
942                Some((Box::new(reader) as Box<dyn Read + Send>, Box::new(writer) as Box<dyn Write + Send>))
943            });
944            crate::metrics::connection_close();
945            if let Err(msg) = result {
946                crate::metrics::record_error();
947                eprintln!("{}", msg);
948            }
949        });
950    }
951
952}
953
954/// Network context for the current connection, passed into every [`Controller`](crate::controller::Controller).
955#[derive(Clone)]
956pub struct ConnectionInfo {
957    /// Client (peer) address.
958    pub client: Address,
959    /// Server (local) address.
960    pub server: Address,
961    /// Bytes allocated for reading the request.
962    pub request_size: i64,
963    /// SNI hostname sent by the client during the TLS handshake, if any.
964    /// `None` for plain-HTTP connections or when the client omits SNI.
965    pub sni_hostname: Option<String>,
966    /// The client connected over TLS (HTTPS, HTTP/2 over TLS, HTTP/3).
967    /// Proxies send it on as `X-Forwarded-Proto` (18.9.0).
968    pub tls: bool,
969}
970
971impl Default for ConnectionInfo {
972    /// Unknown addresses (`0.0.0.0:0`), no SNI, not TLS: for building one
973    /// with `..Default::default()` in tests and adapters.
974    fn default() -> Self {
975        let unknown = Address { ip: "0.0.0.0".to_string(), port: 0 };
976        ConnectionInfo { client: unknown.clone(), server: unknown, request_size: 0, sni_hostname: None, tls: false }
977    }
978}
979
980/// IP address and port pair.
981#[derive(Clone)]
982pub struct Address {
983    pub ip: String,
984    pub port: i32
985}
986
987impl ConnectionInfo {
988    /// A connection from `client` to `server`; plain (not TLS), no SNI, the
989    /// default request allocation size. Set `tls`/`sni_hostname` after.
990    pub fn new(client: Address, server: Address) -> Self {
991        ConnectionInfo { client, server, request_size: 0, sni_hostname: None, tls: false }
992    }
993
994    /// Parse the client address into a [`std::net::SocketAddr`], if the stored
995    /// IP and port are valid. Returns `None` if parsing fails.
996    pub fn peer_addr(&self) -> Option<std::net::SocketAddr> {
997        self.client.to_socket_addr()
998    }
999}
1000
1001impl Address {
1002    /// Parse this address into a [`std::net::SocketAddr`]. Returns `None` if
1003    /// the IP string or port value cannot be converted.
1004    pub fn to_socket_addr(&self) -> Option<std::net::SocketAddr> {
1005        let ip: std::net::IpAddr = self.ip.parse().ok()?;
1006        let port = u16::try_from(self.port).ok()?;
1007        Some(std::net::SocketAddr::new(ip, port))
1008    }
1009}
1010
1011/// One accepted TLS connection: handshake (bounded by
1012/// `TLS_HANDSHAKE_TIMEOUT`), then HTTP/2 or HTTP/1.1 by ALPN.
1013#[cfg(feature = "http2")]
1014#[doc(hidden)]
1015pub async fn serve_tls_connection(
1016    mut tcp_stream: tokio::net::TcpStream,
1017    peer_addr: std::net::SocketAddr,
1018    acceptor: tokio_rustls::TlsAcceptor,
1019    app: impl Application + Send + 'static + Clone,
1020) {
1021    let _ = tcp_stream.set_nodelay(true);
1022    let Some(peer_addr) = client_address(&mut tcp_stream, peer_addr).await else { return };
1023    let timed_out = || std::io::Error::from(std::io::ErrorKind::TimedOut);
1024    let handshake = async {
1025        if let Some(acme) = crate::tls::acme_hooks().filter(|acme| (acme.on_demand_enabled)()) {
1026            // On-demand TLS: read the ClientHello, get a certificate for
1027            // its name if it should have one (bounded by
1028            // `on_demand::HANDSHAKE_WAIT`), then finish the handshake.
1029            let lazy = tokio_rustls::LazyConfigAcceptor::new(rustls::server::Acceptor::default(), tcp_stream);
1030            let start = tokio::time::timeout(http1_async::TLS_HANDSHAKE_TIMEOUT, lazy).await.map_err(|_| timed_out())??;
1031            let hello = start.client_hello();
1032            let name = hello.server_name().filter(|_| !(acme.is_challenge)(&hello)).map(str::to_string);
1033            if let Some(name) = name {
1034                (acme.on_demand_ensure)(&name).await;
1035            }
1036            let finish = start.into_stream(acceptor.config().clone());
1037            return tokio::time::timeout(http1_async::TLS_HANDSHAKE_TIMEOUT, finish).await.map_err(|_| timed_out())?;
1038        }
1039        tokio::time::timeout(http1_async::TLS_HANDSHAKE_TIMEOUT, acceptor.accept(tcp_stream)).await.map_err(|_| timed_out())?
1040    };
1041    match handshake.await {
1042        Err(e) if e.kind() == std::io::ErrorKind::TimedOut => {} // client never finished the handshake
1043        Err(e) => {
1044            crate::metrics::tls::record_handshake_failure();
1045            eprintln!("TLS handshake failed: {}", e)
1046        }
1047        Ok(tls_stream) => {
1048            let server_conn = tls_stream.get_ref().1;
1049            crate::metrics::tls::record_rustls(server_conn);
1050            let sni = server_conn.server_name().map(|s| s.to_string());
1051            let protocol = server_conn.alpn_protocol().map(|p| p.to_vec());
1052
1053            match protocol.as_deref() {
1054                // A TLS-ALPN-01 validation: the handshake was the answer.
1055                Some(crate::tls::ACME_TLS_ALPN) => {}
1056                Some(b"h2") => {
1057                    if let Err(e) = crate::h2_server::handle_connection(tls_stream, peer_addr, sni, app).await {
1058                        eprintln!("H2 connection error: {}", e);
1059                    }
1060                }
1061                _ => {
1062                    crate::metrics::connection_open();
1063                    let result = http1_async::serve(tls_stream, peer_addr, sni, true, app).await;
1064                    crate::metrics::connection_close();
1065                    if let Err(e) = result {
1066                        crate::metrics::record_error();
1067                        eprintln!("H1 TLS error: {}", e);
1068                    }
1069                }
1070            }
1071        }
1072    }
1073}
1074
1075/// One accepted plain-HTTP connection.
1076#[cfg(feature = "http2")]
1077#[doc(hidden)]
1078pub async fn serve_plain_connection(
1079    tcp_stream: tokio::net::TcpStream,
1080    peer_addr: std::net::SocketAddr,
1081    app: impl Application + Send + 'static + Clone,
1082) {
1083    // Head and body go out as separate writes: don't let Nagle hold the
1084    // body back waiting for an ACK.
1085    let mut tcp_stream = tcp_stream;
1086    let _ = tcp_stream.set_nodelay(true);
1087    let Some(peer_addr) = client_address(&mut tcp_stream, peer_addr).await else { return };
1088    if starts_with_h2_preface(&tcp_stream).await {
1089        if let Err(e) = crate::h2_server::serve(tcp_stream, peer_addr, None, false, app).await {
1090            eprintln!("H2C connection error: {}", e);
1091        }
1092        return;
1093    }
1094    crate::metrics::connection_open();
1095    let result = http1_async::serve(tcp_stream, peer_addr, None, false, app).await;
1096    crate::metrics::connection_close();
1097    if let Err(e) = result {
1098        crate::metrics::record_error();
1099        eprintln!("{}", e);
1100    }
1101}
1102
1103/// The client's address: the peer's, or with `proxy_protocol = true` the one
1104/// in the PROXY protocol header the connection starts with. `None`: no valid
1105/// header (in time) — close the connection.
1106#[cfg(feature = "http2")]
1107async fn client_address(tcp_stream: &mut tokio::net::TcpStream, peer_addr: std::net::SocketAddr) -> Option<std::net::SocketAddr> {
1108    if !proxy_protocol::enabled() {
1109        return Some(peer_addr);
1110    }
1111    match tokio::time::timeout(http1_async::TLS_HANDSHAKE_TIMEOUT, proxy_protocol::read_async(tcp_stream)).await {
1112        Ok(Ok(source)) => Some(source.unwrap_or(peer_addr)),
1113        Ok(Err(e)) => {
1114            eprintln!("PROXY protocol header from {}: {}", peer_addr, e);
1115            None
1116        }
1117        Err(_) => None,
1118    }
1119}
1120
1121/// Whether a plain connection opens with the HTTP/2 connection preface —
1122/// cleartext HTTP/2 with prior knowledge (h2c), as `grpcurl -plaintext` and
1123/// gRPC clients without TLS speak it. Looks without consuming; an HTTP/1.1
1124/// request differs within its first two bytes.
1125#[cfg(feature = "http2")]
1126async fn starts_with_h2_preface(tcp_stream: &tokio::net::TcpStream) -> bool {
1127    const PREFACE: &[u8; 24] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
1128    let mut seen = [0u8; 24];
1129    let deadline = tokio::time::Instant::now() + http1_async::READ_TIMEOUT;
1130    loop {
1131        let n = match tokio::time::timeout_at(deadline, tcp_stream.peek(&mut seen)).await {
1132            Ok(Ok(n)) => n,
1133            _ => return false,
1134        };
1135        if n == 0 || seen[..n] != PREFACE[..n] {
1136            return false;
1137        }
1138        if n == PREFACE.len() {
1139            return true;
1140        }
1141        // A preface arriving in pieces: look again shortly.
1142        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
1143    }
1144}
1145
1146/// An accept error (e.g. out of file descriptors): report it and back off
1147/// briefly instead of ending the loop.
1148#[cfg(feature = "http2")]
1149async fn accept_backoff(e: std::io::Error) {
1150    eprintln!("TCP accept error: {}", e);
1151    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1152}
1153
1154/// Set once by [`request_shutdown`]; every receiver sees it, however late.
1155#[cfg(feature = "http2")]
1156fn shutdown_requests() -> &'static tokio::sync::watch::Sender<bool> {
1157    static REQUESTS: std::sync::OnceLock<tokio::sync::watch::Sender<bool>> = std::sync::OnceLock::new();
1158    REQUESTS.get_or_init(|| tokio::sync::watch::channel(false).0)
1159}
1160
1161/// Shut the server down gracefully, as SIGTERM does — for hosts that stop a
1162/// process some other way (a Windows service's Stop control). The accept
1163/// loops of `run_tls`, `run_plain`, `run_quic` and `run_redirect` end.
1164#[cfg(feature = "http2")]
1165pub fn request_shutdown() {
1166    shutdown_requests().send_replace(true);
1167}
1168
1169/// Resolves when SIGTERM is received (Unix) or [`request_shutdown`] is
1170/// called. Enables a single `select!` branch to handle both, beside Ctrl+C.
1171///
1172/// After a SIGTERM (since 18.27.0) `/readyz` answers `503` at once, but this
1173/// resolves only `shutdown_delay_secs` later: the accept loops keep serving
1174/// while the load balancer notices and takes the pod out, then drain. The
1175/// deadline is shared, so a loop's `select!` dropping and re-creating this
1176/// future (on every accepted connection) keeps the same one.
1177#[cfg(feature = "http2")]
1178async fn sigterm() {
1179    static DEADLINE: std::sync::OnceLock<tokio::time::Instant> = std::sync::OnceLock::new();
1180    if let Some(deadline) = DEADLINE.get() {
1181        return tokio::time::sleep_until(*deadline).await;
1182    }
1183    if terminate_or_requested().await {
1184        let delay = std::time::Duration::from_secs(crate::server_config::ServerConfig::current().shutdown_delay_secs);
1185        let mut first = false;
1186        let deadline = *DEADLINE.get_or_init(|| {
1187            first = true;
1188            tokio::time::Instant::now() + delay
1189        });
1190        crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1191        #[cfg(unix)]
1192        crate::systemd::stopping();
1193        if first && !delay.is_zero() {
1194            println!("SIGTERM: not ready; draining in {} s (shutdown_delay_secs)", delay.as_secs());
1195        }
1196        tokio::time::sleep_until(deadline).await;
1197    } else {
1198        #[cfg(unix)]
1199        crate::systemd::stopping();
1200    }
1201}
1202
1203/// `/readyz` answers `200` (with its checks passing) from here on: the
1204/// accept loops call it as they start (18.35.0). Before, only the `rws`
1205/// binary set it, so a library app's `/readyz` answered `503` for good.
1206fn mark_serving() {
1207    crate::metrics::SERVER_READY.store(true, std::sync::atomic::Ordering::SeqCst);
1208}
1209
1210/// Wait until no request is being handled (`metrics::REQUESTS_IN_FLIGHT`),
1211/// at most `shutdown_timeout_secs` (18.35.0). The accept loops call it
1212/// after they stop accepting, so handlers that started finish before the
1213/// process exits. Returns how many were still running at the deadline.
1214#[cfg(feature = "http2")]
1215pub async fn drain_requests() -> i64 {
1216    let timeout = std::time::Duration::from_secs(crate::server_config::ServerConfig::current().shutdown_timeout_secs);
1217    drain_requests_within(timeout).await
1218}
1219
1220#[cfg(feature = "http2")]
1221pub(crate) async fn drain_requests_within(timeout: std::time::Duration) -> i64 {
1222    use std::sync::atomic::Ordering;
1223    let deadline = tokio::time::Instant::now() + timeout;
1224    let mut announced = false;
1225    loop {
1226        let running = crate::metrics::REQUESTS_IN_FLIGHT.load(Ordering::SeqCst);
1227        if running <= 0 {
1228            return 0;
1229        }
1230        if tokio::time::Instant::now() >= deadline {
1231            eprintln!("Shutdown: {running} request(s) still running after {} s (shutdown_timeout_secs)", timeout.as_secs());
1232            return running;
1233        }
1234        if !announced {
1235            println!("Shutdown: waiting for {running} request(s) to finish");
1236            announced = true;
1237        }
1238        tokio::time::sleep(std::time::Duration::from_millis(25)).await;
1239    }
1240}
1241
1242/// `true` for a SIGTERM, `false` for [`request_shutdown`] (no delay: no load
1243/// balancer is waiting on that path).
1244#[cfg(feature = "http2")]
1245async fn terminate_or_requested() -> bool {
1246    let requested = async {
1247        let mut requests = shutdown_requests().subscribe();
1248        let _ = requests.wait_for(|stop| *stop).await;
1249    };
1250    #[cfg(unix)]
1251    {
1252        if let Ok(mut s) = tokio::signal::unix::signal(
1253            tokio::signal::unix::SignalKind::terminate()
1254        ) {
1255            tokio::select! {
1256                _ = s.recv() => true,
1257                _ = requested => false,
1258            }
1259        } else {
1260            requested.await;
1261            false
1262        }
1263    }
1264    #[cfg(not(unix))]
1265    {
1266        requested.await;
1267        false
1268    }
1269}
1270
1271/// Returns a stream that fires on each SIGHUP on Unix; never fires elsewhere.
1272#[cfg(feature = "http2")]
1273async fn sighup() {
1274    #[cfg(unix)]
1275    {
1276        if let Ok(mut s) = tokio::signal::unix::signal(
1277            tokio::signal::unix::SignalKind::hangup()
1278        ) {
1279            crate::config_reload::note_sighup_handled();
1280            s.recv().await;
1281        } else {
1282            std::future::pending::<()>().await
1283        }
1284    }
1285    #[cfg(not(unix))]
1286    std::future::pending::<()>().await
1287}
1288
1289/// Bind `port` for both IPv4 and IPv6 when `ip` is the wildcard `0.0.0.0`
1290/// (otherwise just `ip`). Let's Encrypt validates HTTP-01 over IPv6 when a
1291/// domain has an AAAA record, so a v4-only challenge/redirect listener fails
1292/// validation on dual-stack hosts. On Linux/macOS `[::]` already accepts
1293/// IPv4 too and the second bind reports "address in use", which is fine; on
1294/// Windows (`IPV6_V6ONLY` by default) both binds succeed.
1295#[cfg(feature = "http2")]
1296#[doc(hidden)]
1297pub async fn bind_all_families(ip: &str, port: u16) -> Result<Vec<tokio::net::TcpListener>, String> {
1298    use tokio::net::TcpListener;
1299    #[cfg(unix)]
1300    {
1301        let wanted = if ip.contains(':') { format!("[{ip}]:{port}") } else { format!("{ip}:{port}") };
1302        if let Some(listener) = wanted.parse().ok().and_then(|addr| crate::systemd::tcp(addr, Some("redirect"))) {
1303            listener.set_nonblocking(true).map_err(|e| e.to_string())?;
1304            return TcpListener::from_std(listener).map(|l| vec![l]).map_err(|e| e.to_string());
1305        }
1306    }
1307    if ip != "0.0.0.0" {
1308        let addr = if ip.contains(':') { format!("[{ip}]:{port}") } else { format!("{ip}:{port}") };
1309        return TcpListener::bind(&addr).await.map(|l| vec![l]).map_err(|e| format!("{addr}: {e}"));
1310    }
1311    let mut listeners = Vec::new();
1312    let mut errors = Vec::new();
1313    for addr in [format!("[::]:{port}"), format!("0.0.0.0:{port}")] {
1314        match TcpListener::bind(&addr).await {
1315            Ok(l) => listeners.push(l),
1316            Err(e) => errors.push(format!("{addr}: {e}")),
1317        }
1318    }
1319    if listeners.is_empty() {
1320        return Err(errors.join("; "));
1321    }
1322    Ok(listeners)
1323}
1324
1325#[cfg(feature = "http2")]
1326impl Server {
1327    pub async fn run_tls(
1328        listener: TcpListener,
1329        pool: ThreadPool,
1330        app: impl Application + Send + 'static + Clone,
1331    ) {
1332        use crate::tls::create_tls_acceptor_from_vhosts;
1333
1334        let cert_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE)
1335            .unwrap_or_default();
1336        let key_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_KEY_FILE)
1337            .unwrap_or_default();
1338
1339        if cert_path.is_empty() || key_path.is_empty() {
1340            println!("No TLS certificate configured — serving plain HTTP/1.1.");
1341            drop(pool);
1342            Server::run_plain(listener, app).await;
1343            return;
1344        }
1345
1346        let vhosts = crate::entry_point::get_virtual_hosts();
1347        let mut tls_acceptor = match create_tls_acceptor_from_vhosts(&vhosts, &cert_path, &key_path) {
1348            Ok(a) => a,
1349            Err(e) => {
1350                eprintln!("TLS setup failed: {}", e);
1351                return;
1352            }
1353        };
1354        mark_serving();
1355        // From now on this listener answers TLS-ALPN-01 challenges itself.
1356        if let Some(acme) = crate::tls::acme_hooks() {
1357            (acme.note_tls_listener)();
1358        }
1359
1360        #[cfg(unix)]
1361        if per_core::enabled() {
1362            println!("Listening for TLS connections (HTTP/1.1 + HTTP/2), per-core runtimes...");
1363            let (acceptor_tx, acceptor_rx) = tokio::sync::watch::channel(tls_acceptor);
1364            let accept_loop = move |listener: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>| {
1365                let app = app.clone();
1366                let acceptor_rx = acceptor_rx.clone();
1367                async move {
1368                    loop {
1369                        tokio::select! {
1370                            result = listener.accept() => match result {
1371                                Ok((tcp_stream, peer_addr)) => {
1372                                    let acceptor = acceptor_rx.borrow().clone();
1373                                    tokio::spawn(serve_tls_connection(tcp_stream, peer_addr, acceptor, app.clone()));
1374                                }
1375                                Err(e) => accept_backoff(e).await,
1376                            },
1377                            _ = per_core::stopped(&mut stop) => {
1378                                drain_requests().await;
1379                                break;
1380                            }
1381                        }
1382                    }
1383                }
1384            };
1385            Server::run_per_core(listener, accept_loop, move || {
1386                let vhosts = crate::entry_point::get_virtual_hosts();
1387                if let Ok(new_acceptor) = create_tls_acceptor_from_vhosts(&vhosts, &cert_path, &key_path) {
1388                    let _ = acceptor_tx.send(new_acceptor);
1389                    println!("[TLS] Certificates reloaded ({} virtual hosts).", vhosts.len());
1390                }
1391            })
1392            .await;
1393            return;
1394        }
1395
1396        listener
1397            .set_nonblocking(true)
1398            .expect("failed to set TCP listener to non-blocking");
1399        let tokio_listener = tokio::net::TcpListener::from_std(listener)
1400            .expect("failed to convert TCP listener to tokio");
1401
1402        println!("Listening for TLS connections (HTTP/1.1 + HTTP/2)...");
1403
1404        loop {
1405            tokio::select! {
1406                result = tokio_listener.accept() => {
1407                    match result {
1408                        Ok((tcp_stream, peer_addr)) => {
1409                            tokio::spawn(serve_tls_connection(tcp_stream, peer_addr, tls_acceptor.clone(), app.clone()));
1410                        }
1411                        Err(e) => eprintln!("TCP accept error: {}", e),
1412                    }
1413                }
1414                _ = tokio::signal::ctrl_c() => {
1415                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1416                    println!("\nShutting down gracefully (SIGINT).");
1417                    break;
1418                }
1419                _ = sigterm() => {
1420                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1421                    println!("\nShutting down gracefully (SIGTERM).");
1422                    drain_requests().await;
1423                    break;
1424                }
1425                _ = sighup() => {
1426                    crate::config_reload::reload();
1427                    let vhosts = crate::entry_point::get_virtual_hosts();
1428                    if let Ok(new_acceptor) = create_tls_acceptor_from_vhosts(&vhosts, &cert_path, &key_path) {
1429                        tls_acceptor = new_acceptor;
1430                        println!("[TLS] Certificates reloaded ({} virtual hosts).", vhosts.len());
1431                    }
1432                }
1433            }
1434        }
1435    }
1436
1437    /// Plain-HTTP accept loop of the async builds (used by `run_tls` when no
1438    /// certificate is configured): one tokio task per connection via
1439    /// `http1_async::serve`, so idle or slow clients can't exhaust a thread
1440    /// pool. An accept error (e.g. out of file descriptors) backs off briefly
1441    /// and keeps serving instead of ending the loop.
1442    pub async fn run_plain(listener: TcpListener, app: impl Application + Send + 'static + Clone) {
1443        mark_serving();
1444        #[cfg(unix)]
1445        if per_core::enabled() {
1446            let accept_loop = move |listener: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>| {
1447                let app = app.clone();
1448                async move {
1449                    loop {
1450                        tokio::select! {
1451                            result = listener.accept() => match result {
1452                                Ok((tcp_stream, peer_addr)) => {
1453                                    tokio::spawn(serve_plain_connection(tcp_stream, peer_addr, app.clone()));
1454                                }
1455                                Err(e) => accept_backoff(e).await,
1456                            },
1457                            _ = per_core::stopped(&mut stop) => {
1458                                drain_requests().await;
1459                                break;
1460                            }
1461                        }
1462                    }
1463                }
1464            };
1465            Server::run_per_core(listener, accept_loop, || {}).await;
1466            return;
1467        }
1468
1469        listener
1470            .set_nonblocking(true)
1471            .expect("failed to set TCP listener to non-blocking");
1472        let tokio_listener = tokio::net::TcpListener::from_std(listener)
1473            .expect("failed to convert TCP listener to tokio");
1474
1475        loop {
1476            tokio::select! {
1477                result = tokio_listener.accept() => {
1478                    match result {
1479                        Ok((tcp_stream, peer_addr)) => {
1480                            tokio::spawn(serve_plain_connection(tcp_stream, peer_addr, app.clone()));
1481                        }
1482                        Err(e) => accept_backoff(e).await,
1483                    }
1484                }
1485                _ = tokio::signal::ctrl_c() => {
1486                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1487                    println!("\nShutting down gracefully (SIGINT).");
1488                    break;
1489                }
1490                _ = sigterm() => {
1491                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1492                    println!("\nShutting down gracefully (SIGTERM).");
1493                    drain_requests().await;
1494                    break;
1495                }
1496                _ = sighup() => {
1497                    crate::config_reload::reload();
1498                }
1499            }
1500        }
1501    }
1502
1503    /// Per-core mode of `run_tls`/`run_plain` ([`per_core`]): rebinds
1504    /// `listener`'s address as one `SO_REUSEPORT` socket per runtime, runs
1505    /// `accept_loop` on each, and handles the signals here — SIGINT/SIGTERM
1506    /// stop every loop, SIGHUP reloads the config and calls `on_reload`.
1507    #[cfg(unix)]
1508    async fn run_per_core<F, Fut>(listener: TcpListener, accept_loop: F, on_reload: impl Fn())
1509    where
1510        F: Fn(tokio::net::TcpListener, tokio::sync::watch::Receiver<bool>) -> Fut + Send + Clone + 'static,
1511        Fut: std::future::Future<Output = ()>,
1512    {
1513        let addr = match listener.local_addr() {
1514            Ok(a) => a,
1515            Err(e) => return eprintln!("per-core runtimes: {}", e),
1516        };
1517        // The setup listener has no SO_REUSEPORT, so it can't share the port.
1518        drop(listener);
1519        let count = per_core::runtime_count();
1520        let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
1521        let handles = per_core::spawn(addr, count, stop_rx, accept_loop);
1522        println!("Started {} per-core runtimes on {}.", handles.len(), addr);
1523
1524        loop {
1525            tokio::select! {
1526                _ = tokio::signal::ctrl_c() => {
1527                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1528                    println!("\nShutting down gracefully (SIGINT).");
1529                    break;
1530                }
1531                _ = sigterm() => {
1532                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1533                    println!("\nShutting down gracefully (SIGTERM).");
1534                    break;
1535                }
1536                _ = sighup() => {
1537                    crate::config_reload::reload();
1538                    on_reload();
1539                }
1540            }
1541        }
1542        let _ = stop_tx.send(true);
1543        let _ = tokio::task::spawn_blocking(move || {
1544            for h in handles {
1545                let _ = h.join();
1546            }
1547        })
1548        .await;
1549    }
1550
1551    /// Binds a plain-HTTP listener on the port in `RWS_CONFIG_HTTP_REDIRECT_PORT` and sends
1552    /// `301 Moved Permanently` to the HTTPS equivalent of every incoming URL.
1553    /// Returns immediately if TLS is not configured or the redirect port is not set.
1554    pub async fn run_redirect() {
1555        use std::env;
1556
1557        let cert_path = env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE)
1558            .unwrap_or_default();
1559        if cert_path.is_empty() {
1560            return;
1561        }
1562
1563        let redirect_port_str = env::var(crate::entry_point::Config::RWS_CONFIG_HTTP_REDIRECT_PORT)
1564            .unwrap_or_default();
1565        if redirect_port_str.is_empty() {
1566            return;
1567        }
1568
1569        let redirect_port: u16 = match redirect_port_str.parse() {
1570            Ok(p) => p,
1571            Err(_) => {
1572                eprintln!("Invalid RWS_CONFIG_HTTP_REDIRECT_PORT: {}", redirect_port_str);
1573                return;
1574            }
1575        };
1576
1577        let (server_ip, server_port, _) = get_ip_port_thread_count();
1578        let listeners = match bind_all_families(&server_ip, redirect_port).await {
1579            Ok(l) => l,
1580            Err(e) => {
1581                eprintln!("HTTP redirect listener error on port {}: {}", redirect_port, e);
1582                return;
1583            }
1584        };
1585
1586        println!("HTTP→HTTPS redirect listening on http://{}:{}", server_ip, redirect_port);
1587        if let Some(acme) = crate::tls::acme_hooks() {
1588            (acme.note_redirect_listener)(redirect_port);
1589        }
1590
1591        for listener in listeners {
1592            tokio::spawn(async move {
1593                loop {
1594                    match listener.accept().await {
1595                        Ok((stream, _peer)) => {
1596                            tokio::spawn(Server::handle_redirect_connection(stream, server_port));
1597                        }
1598                        Err(e) => eprintln!("HTTP redirect accept error: {}", e),
1599                    }
1600                }
1601            });
1602        }
1603
1604        loop {
1605            tokio::select! {
1606                _ = tokio::signal::ctrl_c() => {
1607                    println!("\nShutting down HTTP redirect listener (SIGINT).");
1608                    break;
1609                }
1610                _ = sigterm() => {
1611                    println!("\nShutting down HTTP redirect listener (SIGTERM).");
1612                    break;
1613                }
1614                _ = sighup() => {
1615                    crate::config_reload::reload();
1616                }
1617            }
1618        }
1619    }
1620
1621    /// One redirect-listener connection: answer a pending ACME HTTP-01
1622    /// challenge, or `301` to the HTTPS equivalent of the requested URL.
1623    #[doc(hidden)]
1624    pub async fn handle_redirect_connection(mut stream: tokio::net::TcpStream, https_port: i32) {
1625        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1626        let mut buf = vec![0u8; 4096];
1627        let n = match stream.read(&mut buf).await {
1628            Ok(n) => n,
1629            Err(_) => return,
1630        };
1631        let text = String::from_utf8_lossy(&buf[..n]);
1632
1633        let uri = text.lines()
1634            .next()
1635            .and_then(|line| line.split_whitespace().nth(1))
1636            .unwrap_or("/")
1637            .to_string();
1638
1639        // ACME HTTP-01 challenges must be answered over
1640        // plain HTTP, not redirected.
1641        let challenge = match crate::tls::acme_hooks() {
1642            Some(acme) => (acme.http_challenge)(&uri).await,
1643            None => None,
1644        };
1645        if let Some(challenge) = challenge {
1646            let _ = stream.write_all(challenge.as_bytes()).await;
1647            return;
1648        }
1649
1650        let host_header = text.lines()
1651            .find(|l| l.to_lowercase().starts_with("host:"))
1652            .map(|l| l[5..].trim().to_string());
1653
1654        let location = match host_header {
1655            Some(h) => {
1656                // strip existing port from Host header
1657                let h_no_port = if h.starts_with('[') {
1658                    // IPv6: [::1] or [::1]:port
1659                    h.find(']')
1660                        .map(|i| h[..=i].to_string())
1661                        .unwrap_or(h.clone())
1662                } else {
1663                    h.rfind(':')
1664                        .map(|i| h[..i].to_string())
1665                        .unwrap_or(h.clone())
1666                };
1667                if https_port == 443 {
1668                    format!("https://{}{}", h_no_port, uri)
1669                } else {
1670                    format!("https://{}:{}{}", h_no_port, https_port, uri)
1671                }
1672            }
1673            None => format!("https://localhost:{}{}", https_port, uri),
1674        };
1675
1676        let response = format!(
1677            "HTTP/1.1 301 Moved Permanently\r\nLocation: {}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
1678            location
1679        );
1680        let _ = stream.write_all(response.as_bytes()).await;
1681    }
1682
1683}
1684
1685#[cfg(feature = "http3")]
1686impl Server {
1687    pub async fn run_quic(
1688        app: impl Application + Send + 'static + Clone,
1689    ) {
1690        use crate::tls::create_quinn_server_config_from_vhosts;
1691        use crate::h3_handler;
1692
1693        let cert_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE)
1694            .unwrap_or_default();
1695        let key_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_KEY_FILE)
1696            .unwrap_or_default();
1697
1698        if cert_path.is_empty() || key_path.is_empty() {
1699            return;
1700        }
1701
1702        let vhosts = crate::entry_point::get_virtual_hosts();
1703        let server_config = match create_quinn_server_config_from_vhosts(&vhosts, &cert_path, &key_path) {
1704            Ok(c) => c,
1705            Err(e) => {
1706                eprintln!("QUIC TLS setup failed: {}", e);
1707                return;
1708            }
1709        };
1710
1711        let (server_ip, server_port, _) = get_ip_port_thread_count();
1712        let bind_addr = format!("{}:{}", server_ip, server_port);
1713        let addr: std::net::SocketAddr = match bind_addr.parse() {
1714            Ok(a) => a,
1715            Err(e) => {
1716                eprintln!("Invalid QUIC bind address '{}': {}", bind_addr, e);
1717                return;
1718            }
1719        };
1720
1721        // A UDP socket systemd passed, else bind one.
1722        #[cfg(unix)]
1723        let inherited = crate::systemd::udp(addr, Some("quic"));
1724        #[cfg(not(unix))]
1725        let inherited: Option<std::net::UdpSocket> = None;
1726        let endpoint = match inherited {
1727            Some(socket) => quinn::Endpoint::new(quinn::EndpointConfig::default(), Some(server_config), socket, std::sync::Arc::new(quinn::TokioRuntime)),
1728            None => quinn::Endpoint::server(server_config, addr),
1729        };
1730        let endpoint = match endpoint {
1731            Ok(e) => e,
1732            Err(e) => {
1733                eprintln!("QUIC endpoint error: {}", e);
1734                return;
1735            }
1736        };
1737
1738        println!("Listening for QUIC/HTTP3 on UDP {}:{}", server_ip, server_port);
1739
1740        loop {
1741            tokio::select! {
1742                maybe = endpoint.accept() => {
1743                    match maybe {
1744                        Some(incoming) => {
1745                            let app = app.clone();
1746                            tokio::spawn(async move {
1747                                match incoming.await {
1748                                    Ok(conn) => {
1749                                        let peer_addr = conn.remote_address();
1750                                        if let Err(e) = h3_handler::handle_connection(conn, peer_addr, app).await {
1751                                            eprintln!("H3 connection error: {}", e);
1752                                        }
1753                                    }
1754                                    Err(e) => eprintln!("QUIC connection error: {}", e),
1755                                }
1756                            });
1757                        }
1758                        None => break,
1759                    }
1760                }
1761                _ = tokio::signal::ctrl_c() => {
1762                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1763                    println!("\nShutting down QUIC (SIGINT).");
1764                    endpoint.close(0u32.into(), b"shutdown");
1765                    break;
1766                }
1767                _ = sigterm() => {
1768                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1769                    println!("\nShutting down QUIC (SIGTERM).");
1770                    drain_requests().await;
1771                    endpoint.close(0u32.into(), b"shutdown");
1772                    break;
1773                }
1774                _ = sighup() => {
1775                    crate::config_reload::reload();
1776                }
1777            }
1778        }
1779    }
1780}
1781
1782
1783
1784
1785/// The message for a listener that can't be bound: one line naming the
1786/// address and what to do, instead of a panic (18.37.0).
1787pub fn bind_error_message(bind_addr: &str, e: &std::io::Error) -> String {
1788    match e.kind() {
1789        std::io::ErrorKind::AddrInUse => format!(
1790            "rws: {bind_addr} is already in use: another program (or another rws) listens there.\n\
1791             Stop it, or pick another port: rws --port=8080 (or port = 8080 in rws.config.toml)."
1792        ),
1793        std::io::ErrorKind::PermissionDenied => format!(
1794            "rws: no permission to listen on {bind_addr}: ports below 1024 need root or CAP_NET_BIND_SERVICE.\n\
1795             Pick a port from 1024 up: rws --port=8080."
1796        ),
1797        std::io::ErrorKind::AddrNotAvailable => format!(
1798            "rws: {bind_addr} is not an address of this machine. Use --ip=0.0.0.0 (all interfaces) or --ip=127.0.0.1."
1799        ),
1800        _ => format!("rws: unable to listen on {bind_addr}: {e}"),
1801    }
1802}
1803
1804/// The few lines a start prints without `--verbose`: version, where the
1805/// configuration came from, what is served and where.
1806pub fn startup_summary(protocol: &str, ip: &str, port: i32) -> String {
1807    let config = match crate::entry_point::config_source() {
1808        Some(path) => format!("config {path}"),
1809        None => "no rws.config.toml: defaults, environment and flags".to_string(),
1810    };
1811    let proxy = std::env::var("RWS_CONFIG_FILE").is_ok() || crate::entry_point::config_source().is_some_and(|p| {
1812        std::fs::read_to_string(p).is_ok_and(|c| c.contains("[[route]]") || c.contains("[[upstream]]"))
1813    });
1814    let dir = crate::app::controller::static_resource::working_directory().to_string();
1815    let serving = if proxy { "reverse proxy (routes from the config)".to_string() } else { format!("files from {dir}") };
1816    let all = ip == "0.0.0.0" || ip == "::";
1817    let host = if all { "localhost".to_string() } else if ip.contains(':') { format!("[{ip}]") } else { ip.to_string() };
1818    let mut out = format!("rws {} · {config}\nServing {serving}\n", env!("CARGO_PKG_VERSION"));
1819    out.push_str(&format!("Server is up and running at: {protocol}://{host}:{port}\n"));
1820    if all {
1821        out.push_str(&format!("  Listening on all interfaces ({ip}:{port}): other machines on the network can reach it.\n"));
1822        if !proxy && crate::server_config::ServerConfig::current().directory_listing {
1823            out.push_str("  Directory listing is on, so they can browse this folder. Local only: --ip=127.0.0.1; no listing: directory_listing = false.\n");
1824        }
1825    }
1826    out.push_str("Ctrl+C stops it · --verbose prints every setting\n");
1827    out
1828}