Skip to main content

rustio_admin/
server.rs

1//! The HTTP server. Binds a TCP listener, runs each connection on its
2//! own Tokio task, and shuts down gracefully on Ctrl-C.
3
4use std::collections::HashMap;
5use std::net::SocketAddr;
6use std::sync::Arc;
7
8use bytes::Bytes;
9use http_body_util::{BodyExt, Full};
10use hyper::body::Incoming;
11use hyper::service::service_fn;
12use hyper::StatusCode;
13use hyper_util::rt::TokioIo;
14use tokio::net::TcpListener;
15
16use crate::error::Result;
17use crate::http::{Request, Response};
18use crate::router::Router;
19
20pub struct Server {
21    router: Arc<Router>,
22    addr: SocketAddr,
23}
24
25impl Server {
26    pub fn new(router: Router, addr: SocketAddr) -> Self {
27        Self {
28            router: Arc::new(router),
29            addr,
30        }
31    }
32
33    /// Run until Ctrl-C / SIGTERM. Active connections get a brief grace
34    /// period to drain before the runtime drops them.
35    pub async fn run(self) -> Result<()> {
36        let listener = TcpListener::bind(self.addr).await?;
37        log::info!("rustio listening on http://{}", self.addr);
38
39        let shutdown = shutdown_signal();
40        tokio::pin!(shutdown);
41
42        loop {
43            tokio::select! {
44                accept = listener.accept() => {
45                    let (stream, peer) = accept?;
46                    let io = TokioIo::new(stream);
47                    let router = self.router.clone();
48                    tokio::spawn(async move {
49                        let svc = service_fn(move |req: hyper::Request<Incoming>| {
50                            let router = router.clone();
51                            async move { handle(router, req, peer).await }
52                        });
53                        let conn = hyper::server::conn::http1::Builder::new()
54                            .keep_alive(true)
55                            .serve_connection(io, svc);
56                        if let Err(e) = conn.await {
57                            // Normal client disconnects produce noisy errors;
58                            // only log at debug level.
59                            log::debug!("connection error: {e}");
60                        }
61                    });
62                }
63                _ = &mut shutdown => {
64                    log::info!("shutdown signal received, stopping accept loop");
65                    break;
66                }
67            }
68        }
69
70        tokio::time::sleep(std::time::Duration::from_secs(1)).await;
71        Ok(())
72    }
73}
74
75async fn handle(
76    router: Arc<Router>,
77    hyper_req: hyper::Request<Incoming>,
78    _peer: SocketAddr,
79) -> std::result::Result<hyper::Response<Full<Bytes>>, hyper::Error> {
80    let method = hyper_req.method().clone();
81    let uri = hyper_req.uri().clone();
82    let path = uri.path().to_string();
83    let query = uri.query().unwrap_or("").to_string();
84
85    let mut headers = HashMap::new();
86    for (name, value) in hyper_req.headers() {
87        if let Ok(v) = value.to_str() {
88            headers.insert(name.as_str().to_ascii_lowercase(), v.to_string());
89        }
90    }
91
92    let body = match hyper_req.into_body().collect().await {
93        Ok(b) => b.to_bytes(),
94        Err(_) => {
95            return Ok(simple_response(
96                StatusCode::BAD_REQUEST,
97                "could not read body",
98            ));
99        }
100    };
101
102    let our_req = Request::new(method, path, query, headers, body);
103    let our_resp = router.dispatch(our_req).await;
104    Ok(to_hyper(our_resp))
105}
106
107fn to_hyper(resp: Response) -> hyper::Response<Full<Bytes>> {
108    let mut builder = hyper::Response::builder().status(resp.status);
109    for (name, value) in resp.headers {
110        builder = builder.header(name, value);
111    }
112    builder.body(Full::new(resp.body)).unwrap_or_else(|_| {
113        hyper::Response::builder()
114            .status(StatusCode::INTERNAL_SERVER_ERROR)
115            .body(Full::new(Bytes::from("internal error")))
116            .unwrap()
117    })
118}
119
120fn simple_response(status: StatusCode, body: &str) -> hyper::Response<Full<Bytes>> {
121    hyper::Response::builder()
122        .status(status)
123        .header("content-type", "text/plain; charset=utf-8")
124        .body(Full::new(Bytes::from(body.to_string())))
125        .unwrap()
126}
127
128async fn shutdown_signal() {
129    let ctrl_c = async {
130        tokio::signal::ctrl_c().await.ok();
131    };
132
133    #[cfg(unix)]
134    let terminate = async {
135        if let Ok(mut sig) =
136            tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
137        {
138            sig.recv().await;
139        }
140    };
141
142    #[cfg(not(unix))]
143    let terminate = std::future::pending::<()>();
144
145    tokio::select! {
146        _ = ctrl_c => {}
147        _ = terminate => {}
148    }
149}
150
151/// Serve a static file from disk. Strips path separators and rejects
152/// `..` traversal.
153pub async fn serve_static(root: std::path::PathBuf, name: &str) -> Result<Response> {
154    let safe: String = name
155        .chars()
156        .filter(|c| *c != '/' && *c != '\\' && *c != '\0')
157        .collect();
158    if safe.contains("..") {
159        return Err(crate::error::Error::BadRequest("invalid path".into()));
160    }
161    let path = root.join(&safe);
162    if !path.is_file() {
163        return Err(crate::error::Error::NotFound(safe));
164    }
165    let bytes = tokio::fs::read(&path).await?;
166    Ok(Response::new(StatusCode::OK, Bytes::from(bytes))
167        .with_header("content-type", guess_content_type(&safe)))
168}
169
170fn guess_content_type(name: &str) -> &'static str {
171    match name.rsplit_once('.').map(|(_, ext)| ext) {
172        Some("css") => "text/css; charset=utf-8",
173        Some("js") => "application/javascript; charset=utf-8",
174        Some("png") => "image/png",
175        Some("jpg" | "jpeg") => "image/jpeg",
176        Some("svg") => "image/svg+xml",
177        Some("ico") => "image/x-icon",
178        Some("html") => "text/html; charset=utf-8",
179        Some("woff2") => "font/woff2",
180        Some("json") => "application/json; charset=utf-8",
181        _ => "application/octet-stream",
182    }
183}