Skip to main content

rust_web_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#[cfg(all(test, not(target_arch = "wasm32")))]
14mod example;
15#[cfg(feature = "http2")]
16pub(crate) mod http1_async;
17#[cfg(feature = "http2")]
18pub(crate) mod body_stream;
19#[cfg(feature = "http2")]
20pub(crate) mod body_pump;
21#[cfg(feature = "http2")]
22pub(crate) mod sendfile;
23#[cfg(feature = "http2")]
24pub mod per_core;
25pub(crate) mod framing;
26pub mod proxy_protocol;
27
28// The TCP/thread-pool accept loop below (`Server::setup`/`run`/`process`/…) needs
29// `std::net::TcpListener` and OS threads, neither available on `wasm32-wasip2`.
30// `ConnectionInfo`/`Address` further down have no socket dependency and stay
31// compiled on every target — see spec/WASM_SHIM.md for the guest-adapter that
32// replaces this accept loop under WASI.
33#[cfg(not(target_arch = "wasm32"))]
34use std::io::prelude::*;
35#[cfg(not(target_arch = "wasm32"))]
36use std::borrow::Borrow;
37#[cfg(not(target_arch = "wasm32"))]
38use std::net::{IpAddr, SocketAddr, TcpListener};
39#[cfg(not(target_arch = "wasm32"))]
40use std::str::FromStr;
41#[cfg(not(target_arch = "wasm32"))]
42use std::time::Duration;
43
44#[cfg(not(target_arch = "wasm32"))]
45use crate::request::{METHOD, Request};
46#[cfg(not(target_arch = "wasm32"))]
47use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
48#[cfg(not(target_arch = "wasm32"))]
49use crate::app::App;
50#[cfg(not(target_arch = "wasm32"))]
51use crate::application::Application;
52#[cfg(not(target_arch = "wasm32"))]
53use crate::entry_point::{bootstrap, get_ip_port_thread_count, get_request_allocation_size, set_default_values};
54#[cfg(not(target_arch = "wasm32"))]
55use crate::header::Header;
56#[cfg(not(target_arch = "wasm32"))]
57use crate::log::Log;
58#[cfg(not(target_arch = "wasm32"))]
59use crate::mime_type::MimeType;
60#[cfg(not(target_arch = "wasm32"))]
61use crate::range::{ContentRange, Range};
62#[cfg(not(target_arch = "wasm32"))]
63use crate::symbol::SYMBOL;
64#[cfg(not(target_arch = "wasm32"))]
65use crate::thread_pool::ThreadPool;
66
67#[cfg(not(target_arch = "wasm32"))]
68/// Longest time from the first byte of a request head to its end (nginx's
69/// `client_header_timeout`). The idle timeout alone restarts on every read,
70/// so a client sending one byte every few seconds could hold a connection
71/// for weeks with a 64 KiB head.
72pub const REQUEST_HEAD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
73
74pub struct Server {}
75#[cfg(not(target_arch = "wasm32"))]
76impl Server {
77    pub fn process_request(mut stream: impl Read + Write + Unpin, peer_addr: SocketAddr) -> Vec<u8> {
78        let request_allocation_size = get_request_allocation_size();
79        let mut buffer = vec![0; request_allocation_size as usize];
80        let boxed_read = stream.read(&mut buffer);
81        if boxed_read.is_err() {
82            let message = boxed_read.err().unwrap().to_string();
83            eprintln!("unable to read TCP stream {}", &message);
84
85            let raw_response = Server::bad_request_response(message);
86            let boxed_stream = stream.write(raw_response.borrow());
87            if boxed_stream.is_ok() {
88                stream.flush().unwrap();
89            };
90            return raw_response;
91        }
92
93        boxed_read.unwrap();
94        let request : &[u8] = &buffer;
95
96        // let raw_request = String::from_utf8(Vec::from(request)).unwrap();
97        // println!("\n\n______{}______\n\n", raw_request);
98
99
100        let boxed_request = Request::parse_request(request);
101        if boxed_request.is_err() {
102            let message = boxed_request.err().unwrap();
103            eprintln!("unable to parse request: {}", &message);
104
105            let raw_response = Server::bad_request_response(message);
106            let boxed_stream = stream.write(raw_response.borrow());
107            if boxed_stream.is_ok() {
108                stream.flush().unwrap();
109            };
110            return raw_response;
111        }
112
113
114        let request: Request = boxed_request.unwrap();
115        let (response, request) = App::handle_request(request);
116
117
118        let log_request_response = Log::combined(&request, &response, &peer_addr);
119        println!("{}", log_request_response);
120        let raw_response = Response::generate_response(response, request);
121
122        let boxed_stream = stream.write(raw_response.borrow());
123        if boxed_stream.is_ok() {
124            stream.flush().unwrap();
125        };
126
127        raw_response
128    }
129
130    pub fn bad_request_response(message: String) -> Vec<u8> {
131        let error_request = Request {
132            method: METHOD.get.to_string(),
133            request_uri: "".to_string(),
134            http_version: "".to_string(),
135            headers: vec![],
136            body: Default::default(),
137        };
138
139        let size = message.chars().count() as u64;
140        let content_range = ContentRange {
141            unit: Range::BYTES.to_string(),
142            range: Range { start: 0, end: size },
143            size: size.to_string(),
144            body: Vec::from(message.as_bytes()),
145            content_type: MimeType::TEXT_PLAIN.to_string(),
146        };
147
148        let header_list = Header::get_header_list(&error_request);
149        let error_response: Response = Response::get_response(
150            STATUS_CODE_REASON_PHRASE.n400_bad_request,
151            Some(header_list),
152            Some(vec![content_range])
153        );
154
155        let response = Response::generate_response(error_response, error_request);
156        return response;
157    }
158
159    /// Builds a `413 Payload Too Large` raw response for a request whose declared
160    /// `Content-Length` exceeds `RWS_CONFIG_MAX_BODY_SIZE_IN_BYTES`. The connection
161    /// is always closed after this is sent (see [`Server::process`]) — the client's
162    /// unread body bytes are still queued on the socket, so keep-alive framing
163    /// can't be trusted.
164    pub fn payload_too_large_response(message: String) -> Vec<u8> {
165        let error_request = Request {
166            method: METHOD.get.to_string(),
167            request_uri: "".to_string(),
168            http_version: "".to_string(),
169            headers: vec![],
170            body: Default::default(),
171        };
172
173        let size = message.chars().count() as u64;
174        let content_range = ContentRange {
175            unit: Range::BYTES.to_string(),
176            range: Range { start: 0, end: size },
177            size: size.to_string(),
178            body: Vec::from(message.as_bytes()),
179            content_type: MimeType::TEXT_PLAIN.to_string(),
180        };
181
182        let mut header_list = Header::get_header_list(&error_request);
183        header_list.push(Header { name: Header::_CONNECTION.into(), value: "close".into() });
184        let error_response: Response = Response::get_response(
185            STATUS_CODE_REASON_PHRASE.n413_payload_too_large,
186            Some(header_list),
187            Some(vec![content_range])
188        );
189
190        Response::generate_response(error_response, error_request)
191    }
192
193    /// Builds a `431 Request Header Fields Too Large` raw response for a
194    /// request head longer than [`framing::MAX_HEAD_SIZE`]. The connection is
195    /// closed after it: the rest of the oversized head is still unread.
196    pub fn header_fields_too_large_response() -> Vec<u8> {
197        Server::closing_error_response(
198            STATUS_CODE_REASON_PHRASE.n431_request_header_fields_too_large,
199            format!("431 Request Header Fields Too Large: the request head exceeds {} bytes", framing::MAX_HEAD_SIZE),
200        )
201    }
202
203    /// Builds a `408 Request Timeout` raw response for a client that started
204    /// a request head but didn't finish it within [`REQUEST_HEAD_TIMEOUT`].
205    /// The connection is closed after it.
206    pub fn request_timeout_response() -> Vec<u8> {
207        Server::closing_error_response(
208            STATUS_CODE_REASON_PHRASE.n408_request_timeout,
209            format!("408 Request Timeout: the request head took longer than {} s", REQUEST_HEAD_TIMEOUT.as_secs()),
210        )
211    }
212
213    /// A plain-text error response with `Connection: close`.
214    fn closing_error_response(status: &'static crate::response::StatusCodeReasonPhrase, message: String) -> Vec<u8> {
215        let error_request = Request {
216            method: METHOD.get.to_string(),
217            request_uri: "".to_string(),
218            http_version: "".to_string(),
219            headers: vec![],
220            body: Default::default(),
221        };
222
223        let size = message.chars().count() as u64;
224        let content_range = ContentRange {
225            unit: Range::BYTES.to_string(),
226            range: Range { start: 0, end: size },
227            size: size.to_string(),
228            body: Vec::from(message.as_bytes()),
229            content_type: MimeType::TEXT_PLAIN.to_string(),
230        };
231
232        let mut header_list = Header::get_header_list(&error_request);
233        header_list.push(Header { name: Header::_CONNECTION.into(), value: "close".into() });
234        let error_response: Response = Response::get_response(status, Some(header_list), Some(vec![content_range]));
235
236        Response::generate_response(error_response, error_request)
237    }
238
239    /// Builds the `100 Continue` interim response (RFC 9110 §15.2.1) — no
240    /// headers, no body, just the status line. Sent immediately after parsing
241    /// a request with `Expect: 100-continue`, before reading its body, so the
242    /// client (which is waiting for this before it uploads the body) doesn't
243    /// stall or time out. See [`Server::process`] for where this is sent from.
244    pub fn continue_response() -> Vec<u8> {
245        let dummy_request = Request {
246            method: METHOD.get.to_string(),
247            request_uri: "".to_string(),
248            http_version: "".to_string(),
249            headers: vec![],
250            body: Default::default(),
251        };
252        let response = Response::get_response(STATUS_CODE_REASON_PHRASE.n100_continue, None, None);
253        Response::generate_response(response, dummy_request)
254    }
255
256    /// Builds a `417 Expectation Failed` raw response for an `Expect` header
257    /// value other than `100-continue` (RFC 9110 §10.1.1) — the only
258    /// expectation this server understands. Sent instead of reading the
259    /// request body, since the expectation can't be met either way.
260    pub fn expectation_failed_response(message: String) -> Vec<u8> {
261        let error_request = Request {
262            method: METHOD.get.to_string(),
263            request_uri: "".to_string(),
264            http_version: "".to_string(),
265            headers: vec![],
266            body: Default::default(),
267        };
268
269        let size = message.chars().count() as u64;
270        let content_range = ContentRange {
271            unit: Range::BYTES.to_string(),
272            range: Range { start: 0, end: size },
273            size: size.to_string(),
274            body: Vec::from(message.as_bytes()),
275            content_type: MimeType::TEXT_PLAIN.to_string(),
276        };
277
278        let mut header_list = Header::get_header_list(&error_request);
279        header_list.push(Header { name: Header::_CONNECTION.into(), value: "close".into() });
280        let error_response: Response = Response::get_response(
281            STATUS_CODE_REASON_PHRASE.n417_expectation_failed,
282            Some(header_list),
283            Some(vec![content_range])
284        );
285
286        Response::generate_response(error_response, error_request)
287    }
288
289    pub fn process(mut stream: impl Read + Write + Unpin,
290                   connection: ConnectionInfo,
291                   app: impl Application) -> Result<(), String> {
292
293        let request_allocation_size = connection.request_size;
294        let client = connection.client.clone();
295        let client_addr = SocketAddr::new(IpAddr::from_str(client.ip.as_str()).unwrap(), client.port as u16);
296
297        let max_body_size = crate::entry_point::get_max_body_size();
298
299        // Bytes read from the connection but not consumed yet: the rest of a
300        // request head, a body, or the next pipelined request.
301        let mut pending: Vec<u8> = Vec::new();
302        let mut read_buffer = vec![0u8; request_allocation_size as usize];
303
304        'session: loop {
305            // Read until the request head is complete — it may span several
306            // reads, but must finish within REQUEST_HEAD_TIMEOUT of its first
307            // byte (checked after each read; every read is itself bounded by
308            // the socket's read timeout).
309            let mut head_started: Option<std::time::Instant> = None;
310            let head_len = loop {
311                framing::skip_leading_empty_lines(&mut pending);
312                match framing::scan_head(&pending) {
313                    framing::HeadScan::Complete(n) => break Some(n),
314                    framing::HeadScan::TooLarge => {
315                        let _ = stream.write_all(&Server::header_fields_too_large_response());
316                        let _ = stream.flush();
317                        return Err("request head too large".to_string());
318                    }
319                    framing::HeadScan::Incomplete => {}
320                }
321                if !pending.is_empty() && head_started.is_none() {
322                    head_started = Some(std::time::Instant::now());
323                }
324                match stream.read(&mut read_buffer) {
325                    // timeout or client closed — normal end of keep-alive session
326                    Ok(0) | Err(_) => break None,
327                    Ok(n) => pending.extend_from_slice(&read_buffer[..n]),
328                }
329                let started = *head_started.get_or_insert_with(std::time::Instant::now);
330                if started.elapsed() > REQUEST_HEAD_TIMEOUT && framing::scan_head(&pending) == framing::HeadScan::Incomplete {
331                    let _ = stream.write_all(&Server::request_timeout_response());
332                    let _ = stream.flush();
333                    return Err("request head timed out".to_string());
334                }
335            };
336            let Some(head_len) = head_len else { break };
337
338            let parsed = Request::parse(&pending[..head_len])
339                .and_then(|request| framing::validate_head(&pending[..head_len], &request).map(|_| request))
340                .and_then(|request| framing::body_framing(&request).map(|f| (request, f)));
341            pending.drain(..head_len);
342            let (mut request, body_framing) = match parsed {
343                Ok(parsed) => parsed,
344                Err(message) => {
345                    let _ = stream.write_all(&Server::bad_request_response(message.clone()));
346                    let _ = stream.flush();
347                    return Err(message);
348                }
349            };
350
351            // RFC 9110 §10.1.1 `Expect` — the only expectation this server
352            // understands is `100-continue`; anything else fails fast with a
353            // final status instead of reading a body we can't act on.
354            let expects_continue = match request.header(Header::_EXPECT) {
355                Some(h) if h.value.trim().eq_ignore_ascii_case("100-continue") => true,
356                Some(h) => {
357                    let raw_response = Server::expectation_failed_response(format!(
358                        "417 Expectation Failed: unsupported Expect value '{}'", h.value.trim()
359                    ));
360                    let _ = stream.write_all(&raw_response);
361                    let _ = stream.flush();
362                    break;
363                }
364                None => false,
365            };
366
367            match body_framing {
368                framing::BodyFraming::None => {}
369                framing::BodyFraming::Length(declared_len) => {
370                    if max_body_size > 0 && declared_len > max_body_size {
371                        let raw_response = Server::payload_too_large_response(format!(
372                            "413 Payload Too Large: declared Content-Length {} exceeds the {} byte limit",
373                            declared_len, max_body_size
374                        ));
375                        let _ = stream.write_all(&raw_response);
376                        let _ = stream.flush();
377                        break;
378                    }
379
380                    // Tell the client to go ahead and send the body now, before we
381                    // block waiting for it below.
382                    if expects_continue && (pending.len() as u64) < declared_len {
383                        if stream.write_all(&Server::continue_response()).and_then(|_| stream.flush()).is_err() {
384                            break;
385                        }
386                    }
387
388                    while (pending.len() as u64) < declared_len {
389                        match stream.read(&mut read_buffer) {
390                            Ok(0) | Err(_) => break 'session, // closed or stalled mid-body
391                            Ok(k) => pending.extend_from_slice(&read_buffer[..k]),
392                        }
393                    }
394                    request.body = pending.drain(..declared_len as usize).collect::<Vec<u8>>().into();
395                }
396                framing::BodyFraming::Chunked => {
397                    if expects_continue && pending.is_empty() {
398                        if stream.write_all(&Server::continue_response()).and_then(|_| stream.flush()).is_err() {
399                            break;
400                        }
401                    }
402
403                    let mut decoder = framing::ChunkedBody::new(max_body_size);
404                    loop {
405                        match decoder.feed(&pending) {
406                            Ok((consumed, done)) => {
407                                pending.drain(..consumed);
408                                if done { break; }
409                            }
410                            Err(framing::ChunkError::TooLarge) => {
411                                let raw_response = Server::payload_too_large_response(format!(
412                                    "413 Payload Too Large: chunked body exceeds the {} byte limit", max_body_size
413                                ));
414                                let _ = stream.write_all(&raw_response);
415                                let _ = stream.flush();
416                                break 'session;
417                            }
418                            Err(framing::ChunkError::Malformed(message)) => {
419                                let _ = stream.write_all(&Server::bad_request_response(message.clone()));
420                                let _ = stream.flush();
421                                return Err(message);
422                            }
423                        }
424                        match stream.read(&mut read_buffer) {
425                            Ok(0) | Err(_) => break 'session,
426                            Ok(k) => pending.extend_from_slice(&read_buffer[..k]),
427                        }
428                    }
429                    request.body = decoder.body.into();
430                }
431            }
432
433            let keep_alive = framing::keep_alive(&request);
434
435            let mut response = match app.execute(&request, &connection) {
436                Ok(r) => r,
437                Err(message) => {
438                    let raw_response = Server::bad_request_response(message.clone());
439                    let boxed_stream = stream.write(raw_response.borrow());
440                    if boxed_stream.is_ok() { stream.flush().unwrap(); }
441                    return Err(message);
442                }
443            };
444
445            crate::metrics::record_request();
446            crate::compression::apply_compression(&request, &mut response);
447            response.drop_content_for_status();
448
449            response.headers.push(Header {
450                name: Header::_CONNECTION.into(),
451                value: if keep_alive { "keep-alive".into() } else { "close".into() },
452            });
453
454            Log::log_access(&request, &response, &client_addr);
455
456            if let Some(reader) = response.stream_pipe.take() {
457                if let Err(e) = Server::pipe_stream(&mut stream, response, request, reader) {
458                    return Err(e);
459                }
460            } else if let Some(ref filepath) = response.stream_file.clone() {
461                if let Err(e) = Server::write_chunked_file(&mut stream, response, request, filepath) {
462                    return Err(e);
463                }
464            } else {
465                let raw_response = Response::generate_response(response, request);
466                // write_all: a single write() may accept only part of a large response.
467                if let Err(e) = stream.write_all(raw_response.borrow()) {
468                    return Err(e.to_string());
469                }
470                stream.flush().unwrap();
471            }
472
473            if !keep_alive { break; }
474        }
475
476        Ok(())
477    }
478
479    /// Streams a file to `stream` using HTTP/1.1 chunked transfer encoding.
480    /// The response headers are written first, then the file is read and written in 64 KB chunks.
481    pub(crate) fn write_chunked_file(
482        stream: &mut impl Write,
483        response: Response,
484        request: Request,
485        filepath: &str,
486    ) -> Result<(), String> {
487        use std::fs::File;
488        use std::io::Read as _;
489
490        let (head, chunked) = Server::stream_file_head(response);
491        stream.write_all(&head).map_err(|e| e.to_string())?;
492
493        if request.method != METHOD.head {
494            let mut file = File::open(filepath).map_err(|e| e.to_string())?;
495            let mut buf = vec![0u8; 65536];
496            loop {
497                let n = file.read(&mut buf).map_err(|e| e.to_string())?;
498                if n == 0 { break; }
499                if chunked {
500                    // chunk header: hex size + CRLF
501                    stream.write_all(format!("{:x}\r\n", n).as_bytes()).map_err(|e| e.to_string())?;
502                    stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
503                    stream.write_all(b"\r\n").map_err(|e| e.to_string())?;
504                } else {
505                    stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
506                }
507            }
508            if chunked {
509                // terminal chunk
510                stream.write_all(b"0\r\n\r\n").map_err(|e| e.to_string())?;
511            }
512        }
513
514        stream.flush().map_err(|e| e.to_string())
515    }
516
517    /// The status line and headers of a `stream_file` response, and whether
518    /// its body is sent chunked. With a known Content-Length (static files
519    /// set it) the body goes out as-is; Transfer-Encoding: chunked is only
520    /// for an unknown length. Sending both is forbidden (RFC 9112 §6.1) —
521    /// mismatched handling of the two by intermediaries is how request
522    /// smuggling happens.
523    pub(crate) fn stream_file_head(mut response: Response) -> (Vec<u8>, bool) {
524        let chunked = !response.headers.iter().any(|h| h.name.eq_ignore_ascii_case(Header::_CONTENT_LENGTH));
525        if chunked {
526            response.headers.push(Header {
527                name: Header::_TRANSFER_ENCODING.into(),
528                value: "chunked".into(),
529            });
530        }
531
532        // build status line + headers (no body)
533        let status = [
534            response.http_version.clone(),
535            response.status_code.to_string(),
536            Header::single_line(&response.reason_phrase).into_owned(),
537        ].join(SYMBOL.whitespace);
538
539        let mut headers_str = SYMBOL.new_line_carriage_return.to_string();
540        for header in &response.headers {
541            headers_str.push_str(&Header::single_line(&header.name));
542            headers_str.push_str(Header::NAME_VALUE_SEPARATOR);
543            headers_str.push_str(&Header::single_line(&header.value));
544            headers_str.push_str(SYMBOL.new_line_carriage_return);
545        }
546        let head = format!("{}{}{}", status, headers_str, SYMBOL.new_line_carriage_return);
547        (head.into_bytes(), chunked)
548    }
549
550    /// Streams a `Read` source to `stream` using HTTP/1.1 chunked transfer encoding.
551    ///
552    /// Called when `response.stream_pipe` is set (proxy passthrough for SSE, AI token
553    /// streams, and large downloads). The response headers are written first (with
554    /// `Transfer-Encoding: chunked` injected and any `Content-Length` stripped), then
555    /// bytes are read from `reader` and forwarded in 8 KB chunks. Each chunk is flushed
556    /// immediately so the client sees data as it arrives.
557    pub(crate) fn pipe_stream(
558        stream: &mut impl Write,
559        mut response: Response,
560        request: Request,
561        mut reader: Box<dyn std::io::Read + Send>,
562    ) -> Result<(), String> {
563        // If the backend already uses chunked encoding we pass the raw chunk
564        // frames through; otherwise we wrap the raw bytes in our own chunked
565        // framing so the client can receive data incrementally.
566        let backend_is_chunked = response.headers.iter().any(|h| {
567            h.name.eq_ignore_ascii_case("transfer-encoding")
568                && h.value.to_lowercase().contains("chunked")
569        });
570
571        response.headers.retain(|h| !h.name.eq_ignore_ascii_case("content-length"));
572        if !backend_is_chunked {
573            response.headers.push(Header {
574                name: Header::_TRANSFER_ENCODING.into(),
575                value: "chunked".into(),
576            });
577        }
578
579        let status = [
580            response.http_version.clone(),
581            response.status_code.to_string(),
582            Header::single_line(&response.reason_phrase).into_owned(),
583        ].join(SYMBOL.whitespace);
584
585        let mut head = format!("{}\r\n", status);
586        for header in &response.headers {
587            head.push_str(&Header::single_line(&header.name));
588            head.push_str(Header::NAME_VALUE_SEPARATOR);
589            head.push_str(&Header::single_line(&header.value));
590            head.push_str(SYMBOL.new_line_carriage_return);
591        }
592        head.push_str(SYMBOL.new_line_carriage_return);
593        stream.write_all(head.as_bytes()).map_err(|e| e.to_string())?;
594
595        if request.method != METHOD.head {
596            let mut buf = [0u8; 8192];
597            if backend_is_chunked {
598                // Passthrough: forward raw chunk frames as-is; the client
599                // decodes them itself (avoids double-chunking).
600                loop {
601                    match reader.read(&mut buf) {
602                        Ok(0) | Err(_) => break,
603                        Ok(n) => {
604                            stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
605                            stream.flush().map_err(|e| e.to_string())?;
606                        }
607                    }
608                }
609            } else {
610                // Re-encode: wrap the raw byte stream in chunked framing so
611                // the client can receive each fragment as it arrives (SSE,
612                // large downloads).
613                loop {
614                    match reader.read(&mut buf) {
615                        Ok(0) | Err(_) => break,
616                        Ok(n) => {
617                            stream
618                                .write_all(format!("{:x}\r\n", n).as_bytes())
619                                .map_err(|e| e.to_string())?;
620                            stream.write_all(&buf[..n]).map_err(|e| e.to_string())?;
621                            stream.write_all(b"\r\n").map_err(|e| e.to_string())?;
622                            stream.flush().map_err(|e| e.to_string())?;
623                        }
624                    }
625                }
626                stream.write_all(b"0\r\n\r\n").map_err(|e| e.to_string())?;
627            }
628        }
629
630        stream.flush().map_err(|e| e.to_string())
631    }
632
633    /// Reads configuration (IP, port, thread count, TLS paths) from the layered config system
634    /// and returns a bound `TcpListener` and a sized `ThreadPool`. Call once at startup.
635    pub fn setup() -> Result<(TcpListener, ThreadPool), String> {
636        let info = Log::info("Rust Web Server");
637        println!("{}", info);
638
639        let usage_info = Log::usage_information();
640        println!("{}", usage_info);
641
642
643        println!("RWS Configuration Start: \n");
644
645        set_default_values();
646        bootstrap();
647
648        #[cfg(feature = "secrets")]
649        crate::secrets::resolve_env_vars().map_err(|e| e.to_string())?;
650
651        println!("\nRWS Configuration End\n\n");
652
653
654        let (ip, port, thread_count) = get_ip_port_thread_count();
655
656
657        let mut ip_readable = ip.to_string();
658
659        if ip.contains(":") {
660            ip_readable = [SYMBOL.opening_square_bracket, &ip, SYMBOL.closing_square_bracket].join("");
661        }
662
663        let bind_addr = [ip_readable, SYMBOL.colon.to_string(), port.to_string()].join(SYMBOL.empty_string);
664
665        #[cfg(feature = "http2")]
666        let protocol = {
667            let cert = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE).unwrap_or_default();
668            if cert.is_empty() { "http" } else { "https" }
669        };
670        #[cfg(not(feature = "http2"))]
671        let protocol = "http";
672
673        println!("Setting up {}://{}...", protocol, &bind_addr);
674
675        let boxed_listener = TcpListener::bind(&bind_addr);
676        if boxed_listener.is_err() {
677            let message = format!("unable to set up TCP listener: {}", boxed_listener.err().unwrap());
678            return Err(message);
679        }
680
681        let listener = boxed_listener.unwrap();
682        let pool = ThreadPool::new(thread_count as usize);
683
684
685        let server_url_thread_count = Log::server_url_thread_count(protocol, &bind_addr, thread_count);
686        println!("{}", server_url_thread_count);
687
688        Ok((listener, pool))
689    }
690
691    /// Accepts TCP connections in a loop and dispatches each to the thread pool.
692    ///
693    /// When built with the `http1` feature, Ctrl+C and SIGTERM stop the accept
694    /// loop gracefully: `SERVER_READY` is cleared and the pool drains all
695    /// in-flight connections before returning.
696    ///
697    /// For TLS/HTTP2/HTTP3 use [`Server::run_tls`].
698    pub fn run(listener: TcpListener,
699               pool: ThreadPool,
700               app: impl Application + Send + 'static + Clone) {
701        #[cfg(feature = "http1")]
702        {
703            use std::sync::Arc;
704            use std::sync::atomic::{AtomicBool, Ordering};
705
706            let shutdown = Arc::new(AtomicBool::new(false));
707            let s = shutdown.clone();
708            if let Err(e) = ctrlc::set_handler(move || {
709                s.store(true, Ordering::SeqCst);
710            }) {
711                eprintln!("unable to install signal handler: {}", e);
712            }
713            crate::config_reload::install_sighup_handler();
714            if let Err(e) = listener.set_nonblocking(true) {
715                eprintln!("unable to set non-blocking listener: {}", e);
716            }
717
718            loop {
719                if shutdown.load(Ordering::SeqCst) {
720                    break;
721                }
722                if crate::config_reload::RELOAD_REQUESTED
723                    .compare_exchange(true, false, Ordering::SeqCst, Ordering::Relaxed)
724                    .is_ok()
725                {
726                    crate::config_reload::reload();
727                }
728                match listener.accept() {
729                    Ok((stream, peer_addr)) => {
730                        Server::dispatch_connection(stream, peer_addr, &pool, app.clone());
731                    }
732                    Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
733                        std::thread::sleep(Duration::from_millis(10));
734                    }
735                    Err(e) => {
736                        eprintln!("accept error: {}", e);
737                        break;
738                    }
739                }
740            }
741
742            crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
743            println!("Shutting down — waiting for in-flight connections to finish");
744            pool.join();
745            println!("Server stopped");
746        }
747
748        #[cfg(not(feature = "http1"))]
749        {
750            for boxed_stream in listener.incoming() {
751                match boxed_stream {
752                    Err(e) => {
753                        eprintln!("unable to get TCP stream: {}", e);
754                        return;
755                    }
756                    Ok(stream) => {
757                        let peer_addr = match stream.peer_addr() {
758                            Ok(a) => a,
759                            Err(e) => {
760                                eprintln!("unable to read peer addr: {}", e);
761                                return;
762                            }
763                        };
764                        Server::dispatch_connection(stream, peer_addr, &pool, app.clone());
765                    }
766                }
767            }
768        }
769    }
770
771    fn dispatch_connection(
772        stream: std::net::TcpStream,
773        peer_addr: std::net::SocketAddr,
774        pool: &ThreadPool,
775        app: impl Application + Send + 'static + Clone,
776    ) {
777        print!("Connection established, ");
778        if let Ok(local) = stream.local_addr() {
779            print!("local addr: {}", local);
780        }
781        println!(", peer addr: {}", peer_addr);
782
783        let (server_ip, server_port, _thread_count) = get_ip_port_thread_count();
784        let connection = ConnectionInfo {
785            client: Address {
786                ip: peer_addr.ip().to_string(),
787                port: peer_addr.port() as i32,
788            },
789            server: Address {
790                ip: server_ip,
791                port: server_port,
792            },
793            request_size: get_request_allocation_size(),
794            sni_hostname: None,
795        };
796
797        if let Err(e) = stream.set_read_timeout(Some(Duration::from_secs(30))) {
798            eprintln!("failed to set read timeout: {}", e);
799        }
800
801        pool.execute(move || {
802            let mut stream = stream;
803            let mut connection = connection;
804            if proxy_protocol::enabled() {
805                // Read on the worker: a slow load balancer mustn't hold the accept loop.
806                match proxy_protocol::read_blocking(&mut stream) {
807                    Ok(Some(source)) => {
808                        connection.client = Address { ip: source.ip().to_string(), port: source.port() as i32 };
809                    }
810                    Ok(None) => {}
811                    Err(e) => {
812                        eprintln!("PROXY protocol header from {}: {}", peer_addr, e);
813                        return;
814                    }
815                }
816            }
817            crate::metrics::connection_open();
818            let result = Server::process(stream, connection, app);
819            crate::metrics::connection_close();
820            if let Err(msg) = result {
821                crate::metrics::record_error();
822                eprintln!("{}", msg);
823            }
824        });
825    }
826
827}
828
829/// Network context for the current connection, passed into every [`Controller`](crate::controller::Controller).
830#[derive(Clone)]
831pub struct ConnectionInfo {
832    /// Client (peer) address.
833    pub client: Address,
834    /// Server (local) address.
835    pub server: Address,
836    /// Bytes allocated for reading the request.
837    pub request_size: i64,
838    /// SNI hostname sent by the client during the TLS handshake, if any.
839    /// `None` for plain-HTTP connections or when the client omits SNI.
840    pub sni_hostname: Option<String>,
841}
842
843/// IP address and port pair.
844#[derive(Clone)]
845pub struct Address {
846    pub ip: String,
847    pub port: i32
848}
849
850impl ConnectionInfo {
851    /// Parse the client address into a [`std::net::SocketAddr`], if the stored
852    /// IP and port are valid. Returns `None` if parsing fails.
853    pub fn peer_addr(&self) -> Option<std::net::SocketAddr> {
854        self.client.to_socket_addr()
855    }
856}
857
858impl Address {
859    /// Parse this address into a [`std::net::SocketAddr`]. Returns `None` if
860    /// the IP string or port value cannot be converted.
861    pub fn to_socket_addr(&self) -> Option<std::net::SocketAddr> {
862        let ip: std::net::IpAddr = self.ip.parse().ok()?;
863        let port = u16::try_from(self.port).ok()?;
864        Some(std::net::SocketAddr::new(ip, port))
865    }
866}
867
868/// One accepted TLS connection: handshake (bounded by
869/// `TLS_HANDSHAKE_TIMEOUT`), then HTTP/2 or HTTP/1.1 by ALPN.
870#[cfg(feature = "http2")]
871async fn serve_tls_connection(
872    mut tcp_stream: tokio::net::TcpStream,
873    peer_addr: std::net::SocketAddr,
874    acceptor: tokio_rustls::TlsAcceptor,
875    app: impl Application + Send + 'static + Clone,
876) {
877    let _ = tcp_stream.set_nodelay(true);
878    let Some(peer_addr) = client_address(&mut tcp_stream, peer_addr).await else { return };
879    let handshake = tokio::time::timeout(http1_async::TLS_HANDSHAKE_TIMEOUT, acceptor.accept(tcp_stream));
880    match handshake.await {
881        Err(_) => {} // client never finished the handshake
882        Ok(Err(e)) => eprintln!("TLS handshake failed: {}", e),
883        Ok(Ok(tls_stream)) => {
884            let server_conn = tls_stream.get_ref().1;
885            let sni = server_conn.server_name().map(|s| s.to_string());
886            let protocol = server_conn.alpn_protocol().map(|p| p.to_vec());
887
888            match protocol.as_deref() {
889                Some(b"h2") => {
890                    if let Err(e) = crate::h2_server::handle_connection(tls_stream, peer_addr, sni, app).await {
891                        eprintln!("H2 connection error: {}", e);
892                    }
893                }
894                _ => {
895                    crate::metrics::connection_open();
896                    let result = http1_async::serve(tls_stream, peer_addr, sni, true, app).await;
897                    crate::metrics::connection_close();
898                    if let Err(e) = result {
899                        crate::metrics::record_error();
900                        eprintln!("H1 TLS error: {}", e);
901                    }
902                }
903            }
904        }
905    }
906}
907
908/// One accepted plain-HTTP connection.
909#[cfg(feature = "http2")]
910async fn serve_plain_connection(
911    tcp_stream: tokio::net::TcpStream,
912    peer_addr: std::net::SocketAddr,
913    app: impl Application + Send + 'static + Clone,
914) {
915    // Head and body go out as separate writes: don't let Nagle hold the
916    // body back waiting for an ACK.
917    let mut tcp_stream = tcp_stream;
918    let _ = tcp_stream.set_nodelay(true);
919    let Some(peer_addr) = client_address(&mut tcp_stream, peer_addr).await else { return };
920    if starts_with_h2_preface(&tcp_stream).await {
921        if let Err(e) = crate::h2_server::handle_connection(tcp_stream, peer_addr, None, app).await {
922            eprintln!("H2C connection error: {}", e);
923        }
924        return;
925    }
926    crate::metrics::connection_open();
927    let result = http1_async::serve(tcp_stream, peer_addr, None, false, app).await;
928    crate::metrics::connection_close();
929    if let Err(e) = result {
930        crate::metrics::record_error();
931        eprintln!("{}", e);
932    }
933}
934
935/// The client's address: the peer's, or with `proxy_protocol = true` the one
936/// in the PROXY protocol header the connection starts with. `None`: no valid
937/// header (in time) — close the connection.
938#[cfg(feature = "http2")]
939async fn client_address(tcp_stream: &mut tokio::net::TcpStream, peer_addr: std::net::SocketAddr) -> Option<std::net::SocketAddr> {
940    if !proxy_protocol::enabled() {
941        return Some(peer_addr);
942    }
943    match tokio::time::timeout(http1_async::TLS_HANDSHAKE_TIMEOUT, proxy_protocol::read_async(tcp_stream)).await {
944        Ok(Ok(source)) => Some(source.unwrap_or(peer_addr)),
945        Ok(Err(e)) => {
946            eprintln!("PROXY protocol header from {}: {}", peer_addr, e);
947            None
948        }
949        Err(_) => None,
950    }
951}
952
953/// Whether a plain connection opens with the HTTP/2 connection preface —
954/// cleartext HTTP/2 with prior knowledge (h2c), as `grpcurl -plaintext` and
955/// gRPC clients without TLS speak it. Looks without consuming; an HTTP/1.1
956/// request differs within its first two bytes.
957#[cfg(feature = "http2")]
958async fn starts_with_h2_preface(tcp_stream: &tokio::net::TcpStream) -> bool {
959    const PREFACE: &[u8; 24] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
960    let mut seen = [0u8; 24];
961    let deadline = tokio::time::Instant::now() + http1_async::READ_TIMEOUT;
962    loop {
963        let n = match tokio::time::timeout_at(deadline, tcp_stream.peek(&mut seen)).await {
964            Ok(Ok(n)) => n,
965            _ => return false,
966        };
967        if n == 0 || seen[..n] != PREFACE[..n] {
968            return false;
969        }
970        if n == PREFACE.len() {
971            return true;
972        }
973        // A preface arriving in pieces: look again shortly.
974        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
975    }
976}
977
978/// An accept error (e.g. out of file descriptors): report it and back off
979/// briefly instead of ending the loop.
980#[cfg(feature = "http2")]
981async fn accept_backoff(e: std::io::Error) {
982    eprintln!("TCP accept error: {}", e);
983    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
984}
985
986/// Set once by [`request_shutdown`]; every receiver sees it, however late.
987#[cfg(feature = "http2")]
988fn shutdown_requests() -> &'static tokio::sync::watch::Sender<bool> {
989    static REQUESTS: std::sync::OnceLock<tokio::sync::watch::Sender<bool>> = std::sync::OnceLock::new();
990    REQUESTS.get_or_init(|| tokio::sync::watch::channel(false).0)
991}
992
993/// Shut the server down gracefully, as SIGTERM does — for hosts that stop a
994/// process some other way (a Windows service's Stop control). The accept
995/// loops of `run_tls`, `run_plain`, `run_quic` and `run_redirect` end.
996#[cfg(feature = "http2")]
997pub fn request_shutdown() {
998    shutdown_requests().send_replace(true);
999}
1000
1001/// Resolves when SIGTERM is received (Unix) or [`request_shutdown`] is
1002/// called. Enables a single `select!` branch to handle both, beside Ctrl+C.
1003#[cfg(feature = "http2")]
1004async fn sigterm() {
1005    let requested = async {
1006        let mut requests = shutdown_requests().subscribe();
1007        let _ = requests.wait_for(|stop| *stop).await;
1008    };
1009    #[cfg(unix)]
1010    {
1011        if let Ok(mut s) = tokio::signal::unix::signal(
1012            tokio::signal::unix::SignalKind::terminate()
1013        ) {
1014            tokio::select! {
1015                _ = s.recv() => {}
1016                _ = requested => {}
1017            }
1018        } else {
1019            requested.await
1020        }
1021    }
1022    #[cfg(not(unix))]
1023    requested.await
1024}
1025
1026/// Returns a stream that fires on each SIGHUP on Unix; never fires elsewhere.
1027#[cfg(feature = "http2")]
1028async fn sighup() {
1029    #[cfg(unix)]
1030    {
1031        if let Ok(mut s) = tokio::signal::unix::signal(
1032            tokio::signal::unix::SignalKind::hangup()
1033        ) {
1034            s.recv().await;
1035        } else {
1036            std::future::pending::<()>().await
1037        }
1038    }
1039    #[cfg(not(unix))]
1040    std::future::pending::<()>().await
1041}
1042
1043/// Bind `port` for both IPv4 and IPv6 when `ip` is the wildcard `0.0.0.0`
1044/// (otherwise just `ip`). Let's Encrypt validates HTTP-01 over IPv6 when a
1045/// domain has an AAAA record, so a v4-only challenge/redirect listener fails
1046/// validation on dual-stack hosts. On Linux/macOS `[::]` already accepts
1047/// IPv4 too and the second bind reports "address in use", which is fine; on
1048/// Windows (`IPV6_V6ONLY` by default) both binds succeed.
1049#[cfg(feature = "http2")]
1050pub(crate) async fn bind_all_families(ip: &str, port: u16) -> Result<Vec<tokio::net::TcpListener>, String> {
1051    use tokio::net::TcpListener;
1052    if ip != "0.0.0.0" {
1053        let addr = if ip.contains(':') { format!("[{ip}]:{port}") } else { format!("{ip}:{port}") };
1054        return TcpListener::bind(&addr).await.map(|l| vec![l]).map_err(|e| format!("{addr}: {e}"));
1055    }
1056    let mut listeners = Vec::new();
1057    let mut errors = Vec::new();
1058    for addr in [format!("[::]:{port}"), format!("0.0.0.0:{port}")] {
1059        match TcpListener::bind(&addr).await {
1060            Ok(l) => listeners.push(l),
1061            Err(e) => errors.push(format!("{addr}: {e}")),
1062        }
1063    }
1064    if listeners.is_empty() {
1065        return Err(errors.join("; "));
1066    }
1067    Ok(listeners)
1068}
1069
1070#[cfg(feature = "http2")]
1071impl Server {
1072    pub async fn run_tls(
1073        listener: TcpListener,
1074        pool: ThreadPool,
1075        app: impl Application + Send + 'static + Clone,
1076    ) {
1077        use crate::tls::create_tls_acceptor_from_vhosts;
1078
1079        let cert_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE)
1080            .unwrap_or_default();
1081        let key_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_KEY_FILE)
1082            .unwrap_or_default();
1083
1084        if cert_path.is_empty() || key_path.is_empty() {
1085            println!("No TLS certificate configured — serving plain HTTP/1.1.");
1086            drop(pool);
1087            Server::run_plain(listener, app).await;
1088            return;
1089        }
1090
1091        let vhosts = crate::entry_point::get_virtual_hosts();
1092        let mut tls_acceptor = match create_tls_acceptor_from_vhosts(&vhosts, &cert_path, &key_path) {
1093            Ok(a) => a,
1094            Err(e) => {
1095                eprintln!("TLS setup failed: {}", e);
1096                return;
1097            }
1098        };
1099
1100        #[cfg(unix)]
1101        if per_core::enabled() {
1102            println!("Listening for TLS connections (HTTP/1.1 + HTTP/2), per-core runtimes...");
1103            let (acceptor_tx, acceptor_rx) = tokio::sync::watch::channel(tls_acceptor);
1104            let accept_loop = move |listener: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>| {
1105                let app = app.clone();
1106                let acceptor_rx = acceptor_rx.clone();
1107                async move {
1108                    loop {
1109                        tokio::select! {
1110                            result = listener.accept() => match result {
1111                                Ok((tcp_stream, peer_addr)) => {
1112                                    let acceptor = acceptor_rx.borrow().clone();
1113                                    tokio::spawn(serve_tls_connection(tcp_stream, peer_addr, acceptor, app.clone()));
1114                                }
1115                                Err(e) => accept_backoff(e).await,
1116                            },
1117                            _ = per_core::stopped(&mut stop) => break,
1118                        }
1119                    }
1120                }
1121            };
1122            Server::run_per_core(listener, accept_loop, move || {
1123                let vhosts = crate::entry_point::get_virtual_hosts();
1124                if let Ok(new_acceptor) = create_tls_acceptor_from_vhosts(&vhosts, &cert_path, &key_path) {
1125                    let _ = acceptor_tx.send(new_acceptor);
1126                    println!("[TLS] Certificates reloaded ({} virtual hosts).", vhosts.len());
1127                }
1128            })
1129            .await;
1130            return;
1131        }
1132
1133        listener
1134            .set_nonblocking(true)
1135            .expect("failed to set TCP listener to non-blocking");
1136        let tokio_listener = tokio::net::TcpListener::from_std(listener)
1137            .expect("failed to convert TCP listener to tokio");
1138
1139        println!("Listening for TLS connections (HTTP/1.1 + HTTP/2)...");
1140
1141        loop {
1142            tokio::select! {
1143                result = tokio_listener.accept() => {
1144                    match result {
1145                        Ok((tcp_stream, peer_addr)) => {
1146                            tokio::spawn(serve_tls_connection(tcp_stream, peer_addr, tls_acceptor.clone(), app.clone()));
1147                        }
1148                        Err(e) => eprintln!("TCP accept error: {}", e),
1149                    }
1150                }
1151                _ = tokio::signal::ctrl_c() => {
1152                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1153                    println!("\nShutting down gracefully (SIGINT).");
1154                    break;
1155                }
1156                _ = sigterm() => {
1157                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1158                    println!("\nShutting down gracefully (SIGTERM).");
1159                    break;
1160                }
1161                _ = sighup() => {
1162                    crate::config_reload::reload();
1163                    let vhosts = crate::entry_point::get_virtual_hosts();
1164                    if let Ok(new_acceptor) = create_tls_acceptor_from_vhosts(&vhosts, &cert_path, &key_path) {
1165                        tls_acceptor = new_acceptor;
1166                        println!("[TLS] Certificates reloaded ({} virtual hosts).", vhosts.len());
1167                    }
1168                }
1169            }
1170        }
1171    }
1172
1173    /// Plain-HTTP accept loop of the async builds (used by `run_tls` when no
1174    /// certificate is configured): one tokio task per connection via
1175    /// `http1_async::serve`, so idle or slow clients can't exhaust a thread
1176    /// pool. An accept error (e.g. out of file descriptors) backs off briefly
1177    /// and keeps serving instead of ending the loop.
1178    pub async fn run_plain(listener: TcpListener, app: impl Application + Send + 'static + Clone) {
1179        #[cfg(unix)]
1180        if per_core::enabled() {
1181            let accept_loop = move |listener: tokio::net::TcpListener, mut stop: tokio::sync::watch::Receiver<bool>| {
1182                let app = app.clone();
1183                async move {
1184                    loop {
1185                        tokio::select! {
1186                            result = listener.accept() => match result {
1187                                Ok((tcp_stream, peer_addr)) => {
1188                                    tokio::spawn(serve_plain_connection(tcp_stream, peer_addr, app.clone()));
1189                                }
1190                                Err(e) => accept_backoff(e).await,
1191                            },
1192                            _ = per_core::stopped(&mut stop) => break,
1193                        }
1194                    }
1195                }
1196            };
1197            Server::run_per_core(listener, accept_loop, || {}).await;
1198            return;
1199        }
1200
1201        listener
1202            .set_nonblocking(true)
1203            .expect("failed to set TCP listener to non-blocking");
1204        let tokio_listener = tokio::net::TcpListener::from_std(listener)
1205            .expect("failed to convert TCP listener to tokio");
1206
1207        loop {
1208            tokio::select! {
1209                result = tokio_listener.accept() => {
1210                    match result {
1211                        Ok((tcp_stream, peer_addr)) => {
1212                            tokio::spawn(serve_plain_connection(tcp_stream, peer_addr, app.clone()));
1213                        }
1214                        Err(e) => accept_backoff(e).await,
1215                    }
1216                }
1217                _ = tokio::signal::ctrl_c() => {
1218                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1219                    println!("\nShutting down gracefully (SIGINT).");
1220                    break;
1221                }
1222                _ = sigterm() => {
1223                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1224                    println!("\nShutting down gracefully (SIGTERM).");
1225                    break;
1226                }
1227                _ = sighup() => {
1228                    crate::config_reload::reload();
1229                }
1230            }
1231        }
1232    }
1233
1234    /// Per-core mode of `run_tls`/`run_plain` ([`per_core`]): rebinds
1235    /// `listener`'s address as one `SO_REUSEPORT` socket per runtime, runs
1236    /// `accept_loop` on each, and handles the signals here — SIGINT/SIGTERM
1237    /// stop every loop, SIGHUP reloads the config and calls `on_reload`.
1238    #[cfg(unix)]
1239    async fn run_per_core<F, Fut>(listener: TcpListener, accept_loop: F, on_reload: impl Fn())
1240    where
1241        F: Fn(tokio::net::TcpListener, tokio::sync::watch::Receiver<bool>) -> Fut + Send + Clone + 'static,
1242        Fut: std::future::Future<Output = ()>,
1243    {
1244        let addr = match listener.local_addr() {
1245            Ok(a) => a,
1246            Err(e) => return eprintln!("per-core runtimes: {}", e),
1247        };
1248        // The setup listener has no SO_REUSEPORT, so it can't share the port.
1249        drop(listener);
1250        let count = per_core::runtime_count();
1251        let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
1252        let handles = per_core::spawn(addr, count, stop_rx, accept_loop);
1253        println!("Started {} per-core runtimes on {}.", handles.len(), addr);
1254
1255        loop {
1256            tokio::select! {
1257                _ = tokio::signal::ctrl_c() => {
1258                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1259                    println!("\nShutting down gracefully (SIGINT).");
1260                    break;
1261                }
1262                _ = sigterm() => {
1263                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1264                    println!("\nShutting down gracefully (SIGTERM).");
1265                    break;
1266                }
1267                _ = sighup() => {
1268                    crate::config_reload::reload();
1269                    on_reload();
1270                }
1271            }
1272        }
1273        let _ = stop_tx.send(true);
1274        let _ = tokio::task::spawn_blocking(move || {
1275            for h in handles {
1276                let _ = h.join();
1277            }
1278        })
1279        .await;
1280    }
1281
1282    /// Binds a plain-HTTP listener on the port in `RWS_CONFIG_HTTP_REDIRECT_PORT` and sends
1283    /// `301 Moved Permanently` to the HTTPS equivalent of every incoming URL.
1284    /// Returns immediately if TLS is not configured or the redirect port is not set.
1285    pub async fn run_redirect() {
1286        use std::env;
1287
1288        let cert_path = env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE)
1289            .unwrap_or_default();
1290        if cert_path.is_empty() {
1291            return;
1292        }
1293
1294        let redirect_port_str = env::var(crate::entry_point::Config::RWS_CONFIG_HTTP_REDIRECT_PORT)
1295            .unwrap_or_default();
1296        if redirect_port_str.is_empty() {
1297            return;
1298        }
1299
1300        let redirect_port: u16 = match redirect_port_str.parse() {
1301            Ok(p) => p,
1302            Err(_) => {
1303                eprintln!("Invalid RWS_CONFIG_HTTP_REDIRECT_PORT: {}", redirect_port_str);
1304                return;
1305            }
1306        };
1307
1308        let (server_ip, server_port, _) = get_ip_port_thread_count();
1309        let listeners = match bind_all_families(&server_ip, redirect_port).await {
1310            Ok(l) => l,
1311            Err(e) => {
1312                eprintln!("HTTP redirect listener error on port {}: {}", redirect_port, e);
1313                return;
1314            }
1315        };
1316
1317        println!("HTTP→HTTPS redirect listening on http://{}:{}", server_ip, redirect_port);
1318        #[cfg(feature = "acme")]
1319        crate::acme::note_redirect_listener(redirect_port);
1320
1321        for listener in listeners {
1322            tokio::spawn(async move {
1323                loop {
1324                    match listener.accept().await {
1325                        Ok((stream, _peer)) => {
1326                            tokio::spawn(Server::handle_redirect_connection(stream, server_port));
1327                        }
1328                        Err(e) => eprintln!("HTTP redirect accept error: {}", e),
1329                    }
1330                }
1331            });
1332        }
1333
1334        loop {
1335            tokio::select! {
1336                _ = tokio::signal::ctrl_c() => {
1337                    println!("\nShutting down HTTP redirect listener (SIGINT).");
1338                    break;
1339                }
1340                _ = sigterm() => {
1341                    println!("\nShutting down HTTP redirect listener (SIGTERM).");
1342                    break;
1343                }
1344                _ = sighup() => {
1345                    crate::config_reload::reload();
1346                }
1347            }
1348        }
1349    }
1350
1351    /// One redirect-listener connection: answer a pending ACME HTTP-01
1352    /// challenge, or `301` to the HTTPS equivalent of the requested URL.
1353    pub(crate) async fn handle_redirect_connection(mut stream: tokio::net::TcpStream, https_port: i32) {
1354        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1355        let mut buf = vec![0u8; 4096];
1356        let n = match stream.read(&mut buf).await {
1357            Ok(n) => n,
1358            Err(_) => return,
1359        };
1360        let text = String::from_utf8_lossy(&buf[..n]);
1361
1362        let uri = text.lines()
1363            .next()
1364            .and_then(|line| line.split_whitespace().nth(1))
1365            .unwrap_or("/")
1366            .to_string();
1367
1368        // ACME HTTP-01 challenges must be answered over
1369        // plain HTTP, not redirected.
1370        #[cfg(feature = "acme")]
1371        if let Some(challenge) = crate::acme::challenge_http_response(&uri) {
1372            let _ = stream.write_all(challenge.as_bytes()).await;
1373            return;
1374        }
1375
1376        let host_header = text.lines()
1377            .find(|l| l.to_lowercase().starts_with("host:"))
1378            .map(|l| l[5..].trim().to_string());
1379
1380        let location = match host_header {
1381            Some(h) => {
1382                // strip existing port from Host header
1383                let h_no_port = if h.starts_with('[') {
1384                    // IPv6: [::1] or [::1]:port
1385                    h.find(']')
1386                        .map(|i| h[..=i].to_string())
1387                        .unwrap_or(h.clone())
1388                } else {
1389                    h.rfind(':')
1390                        .map(|i| h[..i].to_string())
1391                        .unwrap_or(h.clone())
1392                };
1393                if https_port == 443 {
1394                    format!("https://{}{}", h_no_port, uri)
1395                } else {
1396                    format!("https://{}:{}{}", h_no_port, https_port, uri)
1397                }
1398            }
1399            None => format!("https://localhost:{}{}", https_port, uri),
1400        };
1401
1402        let response = format!(
1403            "HTTP/1.1 301 Moved Permanently\r\nLocation: {}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
1404            location
1405        );
1406        let _ = stream.write_all(response.as_bytes()).await;
1407    }
1408
1409}
1410
1411#[cfg(feature = "http3")]
1412impl Server {
1413    pub async fn run_quic(
1414        app: impl Application + Send + 'static + Clone,
1415    ) {
1416        use crate::tls::create_quinn_server_config_from_vhosts;
1417        use crate::h3_handler;
1418
1419        let cert_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_CERT_FILE)
1420            .unwrap_or_default();
1421        let key_path = std::env::var(crate::entry_point::Config::RWS_CONFIG_TLS_KEY_FILE)
1422            .unwrap_or_default();
1423
1424        if cert_path.is_empty() || key_path.is_empty() {
1425            return;
1426        }
1427
1428        let vhosts = crate::entry_point::get_virtual_hosts();
1429        let server_config = match create_quinn_server_config_from_vhosts(&vhosts, &cert_path, &key_path) {
1430            Ok(c) => c,
1431            Err(e) => {
1432                eprintln!("QUIC TLS setup failed: {}", e);
1433                return;
1434            }
1435        };
1436
1437        let (server_ip, server_port, _) = get_ip_port_thread_count();
1438        let bind_addr = format!("{}:{}", server_ip, server_port);
1439        let addr: std::net::SocketAddr = match bind_addr.parse() {
1440            Ok(a) => a,
1441            Err(e) => {
1442                eprintln!("Invalid QUIC bind address '{}': {}", bind_addr, e);
1443                return;
1444            }
1445        };
1446
1447        let endpoint = match quinn::Endpoint::server(server_config, addr) {
1448            Ok(e) => e,
1449            Err(e) => {
1450                eprintln!("QUIC endpoint error: {}", e);
1451                return;
1452            }
1453        };
1454
1455        println!("Listening for QUIC/HTTP3 on UDP {}:{}", server_ip, server_port);
1456
1457        loop {
1458            tokio::select! {
1459                maybe = endpoint.accept() => {
1460                    match maybe {
1461                        Some(incoming) => {
1462                            let app = app.clone();
1463                            tokio::spawn(async move {
1464                                match incoming.await {
1465                                    Ok(conn) => {
1466                                        let peer_addr = conn.remote_address();
1467                                        if let Err(e) = h3_handler::handle_connection(conn, peer_addr, app).await {
1468                                            eprintln!("H3 connection error: {}", e);
1469                                        }
1470                                    }
1471                                    Err(e) => eprintln!("QUIC connection error: {}", e),
1472                                }
1473                            });
1474                        }
1475                        None => break,
1476                    }
1477                }
1478                _ = tokio::signal::ctrl_c() => {
1479                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1480                    println!("\nShutting down QUIC (SIGINT).");
1481                    endpoint.close(0u32.into(), b"shutdown");
1482                    break;
1483                }
1484                _ = sigterm() => {
1485                    crate::metrics::SERVER_READY.store(false, std::sync::atomic::Ordering::SeqCst);
1486                    println!("\nShutting down QUIC (SIGTERM).");
1487                    endpoint.close(0u32.into(), b"shutdown");
1488                    break;
1489                }
1490                _ = sighup() => {
1491                    crate::config_reload::reload();
1492                }
1493            }
1494        }
1495    }
1496}
1497
1498