mini_static/server.rs
1use std::convert::Infallible;
2use std::fs;
3use std::net::SocketAddr;
4use std::path::{Path, PathBuf};
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8use std::time::{Duration, SystemTime};
9
10use bytes::Bytes;
11use http_body_util::Full;
12use hyper::body::Incoming;
13use hyper::http::response::Builder;
14use hyper::service::service_fn;
15use hyper::{HeaderMap, Method, Request, Response, StatusCode};
16use hyper_util::rt::TokioExecutor;
17use hyper_util::rt::TokioIo;
18use hyper_util::server::conn::auto::Builder as AutoBuilder;
19use tokio::fs::File;
20use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt, AsyncWrite, ReadBuf};
21use tokio::net::{TcpListener, TcpStream};
22use tokio::sync::{OwnedSemaphorePermit, Semaphore};
23use tokio::time::timeout;
24
25use crate::css::{CssOptions, CssTool};
26use crate::error::StaticError;
27use crate::handler::{FileBody, ResponseBody};
28use crate::js::{JsOptions, JsTool};
29use crate::reload::{self, SseBody};
30use crate::resolve;
31use crate::source::SourcePipeline;
32use crate::spa::{self, SpaTransition};
33use crate::tool;
34use crate::watcher::{start_watching, Broadcaster};
35
36const ACCEPT_BACKOFF_INITIAL: Duration = Duration::from_millis(10);
37const ACCEPT_BACKOFF_MAX: Duration = Duration::from_secs(1);
38
39/// Default maximum concurrent connections, overridable via `Server::with_max_connections`.
40const DEFAULT_MAX_CONNECTIONS: usize = 1024;
41
42/// A source of accepted TCP connections. Abstracted so the accept-error backoff below
43/// can be exercised against a listener that fails on demand, without needing to provoke
44/// real OS-level accept errors (e.g. EMFILE) in tests.
45trait TcpAccept {
46 async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)>;
47}
48
49impl TcpAccept for TcpListener {
50 async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)> {
51 TcpListener::accept(self).await
52 }
53}
54
55/// Accept a connection and reserve it a connection-limit permit.
56///
57/// `backoff` retries a failed `accept()` after an exponentially growing delay (reset on
58/// the next success, capped at `ACCEPT_BACKOFF_MAX`) instead of ending the accept loop,
59/// so a sustained failure — the process being out of file descriptors, say — degrades
60/// into periodic retries rather than a CPU-bound busy spin or a permanently dead server.
61///
62/// Returns `None` only if the semaphore itself has been closed (never happens in normal
63/// operation, since nothing ever calls `close()` on it — handled so a caller can still
64/// fail safely rather than panic).
65async fn accept_and_permit<L: TcpAccept>(
66 listener: &L,
67 backoff: &mut Duration,
68 semaphore: &Arc<Semaphore>,
69) -> Option<(TcpStream, OwnedSemaphorePermit)> {
70 loop {
71 let stream = match listener.accept().await {
72 Ok((stream, _)) => {
73 *backoff = ACCEPT_BACKOFF_INITIAL;
74 stream
75 }
76 Err(_) => {
77 tokio::time::sleep(*backoff).await;
78 *backoff = (*backoff * 2).min(ACCEPT_BACKOFF_MAX);
79 continue;
80 }
81 };
82 return semaphore
83 .clone()
84 .acquire_owned()
85 .await
86 .ok()
87 .map(|permit| (stream, permit));
88 }
89}
90
91/// A predicate deciding whether a resolved file path should get an immutable cache
92/// policy; see [`Server::with_immutable_assets`].
93type ImmutablePredicate = Arc<dyn Fn(&Path) -> bool + Send + Sync>;
94
95/// A static file server for serving files securely from a root directory.
96///
97/// `Server` canonicalizes the root directory once at creation time and uses the
98/// canonical form for all subsequent requests, avoiding repeated filesystem calls.
99///
100/// # Security
101///
102/// The server protects against:
103/// - Path traversal attacks (e.g., `../../etc/passwd`)
104/// - Accessing files outside the root via symlinks
105/// - Disclosing filesystem structure (traversal and missing files both return 404)
106///
107/// # Cloning
108///
109/// `Server` is cheap to clone: a `PathBuf`, a couple of primitives, and an `Arc`'d
110/// predicate closure. Multiple clones can be used concurrently in async tasks without
111/// synchronization overhead.
112///
113/// # Example
114///
115/// ```no_run
116/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
117/// use mini_static::Server;
118/// use std::path::Path;
119/// use std::time::Duration;
120///
121/// let server = Server::new(Path::new("./public"))?;
122/// let (port, _handle) = server.run(Duration::from_secs(30)).await?;
123/// println!("Server running on port {}", port);
124/// # Ok(())
125/// # }
126/// ```
127#[derive(Clone)]
128pub struct Server {
129 root_canon: PathBuf,
130 bundle_roots: Vec<PathBuf>,
131 max_connections: usize,
132 live_reload: bool,
133 broadcaster: Option<Broadcaster>,
134 spa_mode: bool,
135 spa_root: Option<String>,
136 spa_transition: SpaTransition,
137 immutable_predicate: Option<ImmutablePredicate>,
138 source_folders: Vec<PathBuf>,
139 asset_folders: Vec<PathBuf>,
140 output_dir: PathBuf,
141 css_tool: Option<(CssTool, CssOptions)>,
142 js_tool: Option<(JsTool, JsOptions)>,
143 prune_output: bool,
144}
145
146/// True when two canonical paths are the same path or one contains the other.
147///
148/// Used by the source/output overlap check: `Path::starts_with` compares component-wise, so
149/// `/a/b` neither equals nor contains their sibling `/a/b/c` itself. This is the single
150/// place the overlap rule is defined, so both `with_source_folder` and `with_output_dir`
151/// cannot drift apart.
152fn paths_overlap(a: &Path, b: &Path) -> bool {
153 a.starts_with(b) || b.starts_with(a)
154}
155
156impl Server {
157 /// Create a new server with the given root directory.
158 ///
159 /// Canonicalizes the root once at startup. All subsequent requests use the
160 /// canonical root without re-canonicalizing it, making this suitable for long-lived servers.
161 ///
162 /// # Errors
163 ///
164 /// Returns `Err(StaticError::Io)` if the root cannot be canonicalized (e.g., doesn't exist,
165 /// no read permissions).
166 pub fn new(root: &Path) -> Result<Self, StaticError> {
167 let root_canon = root.canonicalize().map_err(StaticError::Io)?;
168 let output_dir = root_canon.clone();
169 Ok(Server {
170 root_canon,
171 bundle_roots: Vec::new(),
172 max_connections: DEFAULT_MAX_CONNECTIONS,
173 live_reload: false,
174 broadcaster: None,
175 spa_mode: false,
176 spa_root: None,
177 spa_transition: SpaTransition::default(),
178 immutable_predicate: None,
179 source_folders: Vec::new(),
180 asset_folders: Vec::new(),
181 output_dir,
182 css_tool: None,
183 js_tool: None,
184 prune_output: false,
185 })
186 }
187
188 /// Set the maximum number of connections served concurrently (default 1024).
189 ///
190 /// Once this many connections are in flight, `run()`'s accept loop stops accepting
191 /// new ones — without pausing the accept loop, a client that opens a connection and
192 /// sends nothing (see the header-read timeout docs on [`Server::run_on`]) could
193 /// otherwise be used, in enough parallel copies, to exhaust the process's file
194 /// descriptors or memory with no bound at all.
195 pub fn with_max_connections(mut self, max: usize) -> Self {
196 self.max_connections = max;
197 self
198 }
199
200 /// Enable live-reload for this server (disabled by default).
201 ///
202 /// Once enabled, the `run*` methods start a background watcher (mtime polling,
203 /// bounded 500ms interval — see [`crate::start_watching`]) over the server's root
204 /// the first time the server actually starts accepting connections, and:
205 ///
206 /// - serve a live-reload SSE stream at [`crate::LIVE_RELOAD_PATH`], broadcasting a
207 /// change event (with [`crate::ChangeType`]) whenever a served file is added,
208 /// modified, or removed;
209 /// - inject a small `<script>` into every served `text/html` response that connects
210 /// to that stream and reloads the page (or hot-swaps stylesheet `<link>`s, for CSS
211 /// changes) — no manual client wiring required.
212 ///
213 /// This is meant for local development, not production: leave it disabled (the
214 /// default) for any server serving real traffic. A typical call site gates it behind
215 /// `#[cfg(debug_assertions)]` so a release build never pays for the watcher or the
216 /// injected script.
217 ///
218 /// # Example
219 ///
220 /// ```no_run
221 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
222 /// use mini_static::Server;
223 /// use std::path::Path;
224 ///
225 /// let server = Server::new(Path::new("./public"))?;
226 /// #[cfg(debug_assertions)]
227 /// let server = server.with_live_reload();
228 /// # Ok(())
229 /// # }
230 /// ```
231 pub fn with_live_reload(mut self) -> Self {
232 self.live_reload = true;
233 self
234 }
235
236 /// Enable spa-mode navigation for this server, swapping `document.body` on
237 /// each navigation (disabled by default).
238 ///
239 /// Once enabled, every served `text/html` response gets a small `<script>`
240 /// injected (see [`Server::with_spa_root`] for what it does) that treats
241 /// `document.body` as the swap target. Calling this after
242 /// [`Server::with_spa_root`] does not clear a previously configured root
243 /// selector — the two methods set independent fields, so
244 /// `.with_spa_root(sel).with_spa_mode()` and
245 /// `.with_spa_mode().with_spa_root(sel)` both end up with spa-mode on and
246 /// root `sel`. Use this one alone when there's no persistent chrome to
247 /// preserve across navigations.
248 ///
249 /// # Example
250 ///
251 /// ```no_run
252 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
253 /// use mini_static::Server;
254 /// use std::path::Path;
255 ///
256 /// let server = Server::new(Path::new("./public"))?.with_spa_mode();
257 /// # Ok(())
258 /// # }
259 /// ```
260 pub fn with_spa_mode(mut self) -> Self {
261 self.spa_mode = true;
262 self
263 }
264
265 /// Enable spa-mode navigation for this server, swapping only the element
266 /// matched by the CSS `selector` on each navigation (disabled by default;
267 /// also enables spa-mode the same as [`Server::with_spa_mode`]).
268 ///
269 /// Once enabled, every served `text/html` response gets a small `<script>`
270 /// injected that intercepts left-clicks on same-origin `<a href>`
271 /// elements (skipping links with a non-`_self` `target`, a `download`
272 /// attribute, `rel="external"`, a `data-no-spa` attribute, or a same-page
273 /// hash-only href) and, instead of a normal navigation:
274 ///
275 /// - fetches the target URL;
276 /// - on a non-OK or non-`text/html` response (or a fetch error), falls
277 /// back to a real `location.href` navigation — spa-mode never renders a
278 /// broken page;
279 /// - otherwise replaces the matched element's `innerHTML` with the
280 /// corresponding content from the fetched document, updates the page
281 /// title, and pushes the new URL via `history.pushState`, animating the
282 /// swap with `document.startViewTransition()` where supported;
283 /// - dispatches a `mini-static:navigate` `CustomEvent` on `window` after
284 /// every client-side navigation, so page scripts can re-run any
285 /// per-page initialization that would otherwise only execute once
286 /// (content swapped in via `innerHTML` never executes its own
287 /// `<script>` tags);
288 /// - handles browser back/forward by re-fetching and swapping to the new
289 /// `location.href`.
290 ///
291 /// `selector` is matched against both the current page and the fetched
292 /// page; a link click where the selector matches neither falls back to a
293 /// real navigation, same as a fetch failure. Choose a `selector` that
294 /// wraps only the content that varies between pages, leaving persistent
295 /// chrome (nav/header/footer) outside it so it survives navigation
296 /// untouched.
297 ///
298 /// This is meant to be usable in production, not just local development
299 /// (unlike [`Server::with_live_reload`]): a click on a link mini-static
300 /// doesn't intercept, or on a browser without JS or View Transitions
301 /// support, still works as a normal navigation.
302 ///
303 /// # Example
304 ///
305 /// ```no_run
306 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
307 /// use mini_static::Server;
308 /// use std::path::Path;
309 ///
310 /// let server = Server::new(Path::new("./public"))?.with_spa_root("#app");
311 /// # Ok(())
312 /// # }
313 /// ```
314 pub fn with_spa_root(mut self, selector: &str) -> Self {
315 self.spa_mode = true;
316 self.spa_root = Some(selector.to_string());
317 self
318 }
319
320 /// Set how spa-mode animates the swap between pages (also enables
321 /// spa-mode the same as [`Server::with_spa_mode`]; default
322 /// [`SpaTransition::Fade`] when spa-mode is enabled without calling this).
323 ///
324 /// [`SpaTransition::Slide`] injects its own `<style>` tag alongside the
325 /// spa-mode `<script>` — no site CSS is required. See [`SpaTransition`]
326 /// and [`SlideOptions`] for what each variant does and how to
327 /// configure the slide's duration, direction, and easing.
328 ///
329 /// # Example
330 ///
331 /// ```no_run
332 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
333 /// use mini_static::{Server, SlideOptions, SpaTransition};
334 /// use std::path::Path;
335 ///
336 /// let server = Server::new(Path::new("./public"))?
337 /// .with_spa_root("#app")
338 /// .with_spa_transition(SpaTransition::Slide(
339 /// SlideOptions::default().duration_ms(500),
340 /// ));
341 /// # Ok(())
342 /// # }
343 /// ```
344 pub fn with_spa_transition(mut self, transition: SpaTransition) -> Self {
345 self.spa_mode = true;
346 self.spa_transition = transition;
347 self
348 }
349
350 /// Serve files matching `predicate` with a long-lived, immutable cache policy
351 /// instead of the default `Cache-Control: no-cache`.
352 ///
353 /// `predicate` is evaluated against each resolved file's path; a match sends
354 /// `Cache-Control: public, max-age=31536000, immutable` on that file's 200 and 304
355 /// responses. This is correct only for fingerprinted assets (e.g.
356 /// `main.a1b2c3.js`) where a content change always produces a new filename —
357 /// caching a mutable filename indefinitely would serve stale content to every
358 /// client that already has it cached.
359 ///
360 /// # Example
361 ///
362 /// ```no_run
363 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
364 /// use mini_static::Server;
365 /// use std::path::Path;
366 ///
367 /// let server = Server::new(Path::new("./public"))?
368 /// .with_immutable_assets(|path| {
369 /// path.file_name()
370 /// .and_then(|name| name.to_str())
371 /// .is_some_and(|name| name.contains(".fingerprint."))
372 /// });
373 /// # Ok(())
374 /// # }
375 /// ```
376 pub fn with_immutable_assets<F>(mut self, predicate: F) -> Self
377 where
378 F: Fn(&Path) -> bool + Send + Sync + 'static,
379 {
380 self.immutable_predicate = Some(Arc::new(predicate));
381 self
382 }
383
384 /// The `Cache-Control` header value for a resolved file path: the immutable policy
385 /// if `with_immutable_assets`'s predicate matches, `no-cache` otherwise.
386 fn cache_control_for(&self, path: &Path) -> &'static str {
387 match &self.immutable_predicate {
388 Some(predicate) if predicate(path) => "public, max-age=31536000, immutable",
389 _ => "no-cache",
390 }
391 }
392
393 /// Register `path` as an additional directory whose changes should trigger a CSS
394 /// bundle rebuild, alongside the registered source folders.
395 ///
396 /// Useful for build pipelines where CSS partials referenced via `@import` live in a
397 /// separate directory tree from the source folders proper: without registering that
398 /// tree here, editing a partial wouldn't be noticed by the watcher and the bundle
399 /// would go stale until something else touched it.
400 ///
401 /// Files under `path` are never directly HTTP-servable: `Server::resolve` and the
402 /// request-handling path never consult bundle roots. This is purely a watch target,
403 /// not a second served root, and — since `@import` resolution is delegated entirely
404 /// to the configured [`CssTool`] (see [`Server::with_css_tool`]) — not an `@import`
405 /// traversal boundary either; the external tool resolves its own imports with no
406 /// root mini-static can enforce.
407 ///
408 /// This method is fallible and canonicalizes the path once at call time, matching
409 /// `Server::new`'s canonicalize-once policy. Call it multiple times to register
410 /// more than one external source tree.
411 ///
412 /// # Errors
413 ///
414 /// Returns `Err(StaticError::Io)` if the path cannot be canonicalized.
415 pub fn with_bundle_root(mut self, path: &Path) -> Result<Self, StaticError> {
416 let canon = path.canonicalize().map_err(StaticError::Io)?;
417 self.bundle_roots.push(canon);
418 Ok(self)
419 }
420
421 /// Designate `dir` as a source folder whose changes drive the build pipelines.
422 ///
423 /// Watched when `with_live_reload()` is enabled; `.css` files under it feed the single
424 /// CSS bundle, `.js`/`.mjs` files are minified per-file into the output dir.
425 ///
426 /// Rejected if `dir` overlaps the output dir or an already-registered source folder: a
427 /// source folder that is also the output would feed every pipeline its own output — the
428 /// feedback loop this layering exists to prevent.
429 ///
430 /// # Errors
431 ///
432 /// Returns `Err(StaticError::Io)` if `dir` cannot be canonicalized, or
433 /// `Err(StaticError::Traversal)` if it overlaps the output dir or another source folder.
434 pub fn with_source_folder(mut self, dir: &Path) -> Result<Self, StaticError> {
435 let canon = dir.canonicalize().map_err(StaticError::Io)?;
436
437 if paths_overlap(&canon, &self.output_dir) {
438 return Err(StaticError::Traversal(format!(
439 "source folder {} overlaps the output dir {}",
440 canon.display(),
441 self.output_dir.display()
442 )));
443 }
444 if self
445 .source_folders
446 .iter()
447 .chain(self.asset_folders.iter())
448 .any(|existing| paths_overlap(&canon, existing))
449 {
450 return Err(StaticError::Traversal(format!(
451 "source folder {} overlaps an already-registered source/asset folder",
452 canon.display()
453 )));
454 }
455
456 self.source_folders.push(canon);
457 Ok(self)
458 }
459
460 /// Designate `dir` as an asset source folder: every file under it (any extension)
461 /// is mirrored byte-identical into the output dir at server startup and on every
462 /// live-reload change — no CSS/JS transformation, just a flat copy preserving each
463 /// file's path relative to `dir`. Use this for hand-authored static files
464 /// (`index.html`, images) that should live outside the served/output dir as
465 /// source, the same source/output separation `with_source_folder`'s CSS/JS
466 /// pipelines already have.
467 ///
468 /// Rejected if `dir` overlaps the output dir or an already-registered
469 /// source/asset folder, for the same reason `with_source_folder` rejects it: a
470 /// folder that is also the output would feed the pipeline its own output.
471 ///
472 /// # Errors
473 ///
474 /// Returns `Err(StaticError::Io)` if `dir` cannot be canonicalized, or
475 /// `Err(StaticError::Traversal)` if it overlaps the output dir or another
476 /// registered source/asset folder.
477 pub fn with_asset_folder(mut self, dir: &Path) -> Result<Self, StaticError> {
478 let canon = dir.canonicalize().map_err(StaticError::Io)?;
479
480 if paths_overlap(&canon, &self.output_dir) {
481 return Err(StaticError::Traversal(format!(
482 "asset folder {} overlaps the output dir {}",
483 canon.display(),
484 self.output_dir.display()
485 )));
486 }
487 if self
488 .source_folders
489 .iter()
490 .chain(self.asset_folders.iter())
491 .any(|existing| paths_overlap(&canon, existing))
492 {
493 return Err(StaticError::Traversal(format!(
494 "asset folder {} overlaps an already-registered source/asset folder",
495 canon.display()
496 )));
497 }
498
499 self.asset_folders.push(canon);
500 Ok(self)
501 }
502
503 /// Designate `dir` as the output directory processed outputs are written to.
504 ///
505 /// Defaults to the served root. The output dir is never a watcher trigger: pipelines
506 /// react to source folders only, so a pipeline's own output can never re-trigger it.
507 /// Call this before `with_css_tool` so a bundle output path reflects the override.
508 ///
509 /// # Errors
510 ///
511 /// Returns `Err(StaticError::Io)` if `dir` cannot be canonicalized, or
512 /// `Err(StaticError::Traversal)` if it overlaps a registered source or asset folder.
513 pub fn with_output_dir(mut self, dir: &Path) -> Result<Self, StaticError> {
514 let canon = dir.canonicalize().map_err(StaticError::Io)?;
515
516 if self
517 .source_folders
518 .iter()
519 .chain(self.asset_folders.iter())
520 .any(|existing| paths_overlap(&canon, existing))
521 {
522 return Err(StaticError::Traversal(format!(
523 "output dir {} overlaps a registered source/asset folder",
524 canon.display()
525 )));
526 }
527
528 self.output_dir = canon;
529 Ok(self)
530 }
531
532 /// Configure CSS bundling/minification via an external tool (disabled by default).
533 ///
534 /// `tool` is a preset naming the CLI mini-static invokes (see [`CssTool`]) —
535 /// mini-static does not install or manage the binary, only looks it up on `PATH`;
536 /// [`Server::run_on`] fails fast at startup if it's missing. `options` selects
537 /// `bundle`/`minify` independently (see [`CssOptions`]):
538 ///
539 /// - Neither: every `.css` under the source folders is copied through unchanged,
540 /// mirrored into the output dir.
541 /// - `minify` only: each file is minified independently and mirrored (no `@import`
542 /// following).
543 /// - `bundle` only: every `.css` under the source folders is discovered,
544 /// `@import`-resolved, and concatenated into one output file, unminified.
545 /// - Both: the bundle above, minified.
546 ///
547 /// # Example
548 ///
549 /// ```no_run
550 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
551 /// use mini_static::{CssOptions, CssTool, Server};
552 /// use std::path::Path;
553 ///
554 /// let server = Server::new(Path::new("./public"))?
555 /// .with_css_tool(CssTool::LightningCss, CssOptions::new().bundle(true).minify(true));
556 /// # Ok(())
557 /// # }
558 /// ```
559 pub fn with_css_tool(mut self, tool: CssTool, options: CssOptions) -> Self {
560 self.css_tool = Some((tool, options));
561 self
562 }
563
564 /// Configure JS bundling/minification via an external tool (disabled by default).
565 ///
566 /// `tool` is a preset naming the CLI mini-static invokes (see [`JsTool`]) —
567 /// mini-static does not install or manage the binary, only looks it up on `PATH`;
568 /// [`Server::run_on`] fails fast at startup if it's missing. Unlike CSS, JS bundling
569 /// requires an explicit entry point ([`JsOptions::bundle_entry`]) since a JS module
570 /// graph has no well-defined "concatenate everything" meaning; without it, `options`
571 /// runs in per-file mode (every `.js`/`.mjs` under the source folders processed and
572 /// mirrored independently).
573 ///
574 /// # Errors
575 ///
576 /// Returns `Err(StaticError::Io)` if `options` specifies a bundle entry that cannot
577 /// be canonicalized, or `Err(StaticError::Traversal)` if it doesn't lie under a
578 /// registered source folder — checked eagerly here so a bad entry path fails at
579 /// configuration time, not on the first rebuild.
580 ///
581 /// # Example
582 ///
583 /// ```no_run
584 /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
585 /// use mini_static::{JsOptions, JsTool, Server};
586 /// use std::path::Path;
587 ///
588 /// let server = Server::new(Path::new("./public"))?
589 /// .with_source_folder(Path::new("./js-src"))?
590 /// .with_js_tool(
591 /// JsTool::Esbuild,
592 /// JsOptions::new()
593 /// .bundle_entry(Path::new("./js-src/main.js"), "bundle.js")
594 /// .minify(true),
595 /// )?;
596 /// # Ok(())
597 /// # }
598 /// ```
599 pub fn with_js_tool(mut self, tool: JsTool, options: JsOptions) -> Result<Self, StaticError> {
600 if let Some(entry) = options.entry() {
601 let entry_canon = entry.canonicalize().map_err(StaticError::Io)?;
602 let under_source_folder = self
603 .source_folders
604 .iter()
605 .any(|folder| entry_canon.starts_with(folder));
606 if !under_source_folder {
607 return Err(StaticError::Traversal(format!(
608 "js bundle entry {} is not under any registered source folder",
609 entry_canon.display()
610 )));
611 }
612 }
613
614 self.js_tool = Some((tool, options));
615 Ok(self)
616 }
617
618 /// Remove stale CSS bundle output at build time — specifically, delete the bundle file
619 /// when no CSS sources remain, rather than serving an orphan. Applies only to the
620 /// one-shot startup build, never during live-reload.
621 pub fn with_prune_output(mut self) -> Self {
622 self.prune_output = true;
623 self
624 }
625
626 /// True when any build pipeline is configured (a CSS/JS tool and/or a source
627 /// folder), i.e. the server should run a startup build.
628 fn has_pipeline(&self) -> bool {
629 self.css_tool.is_some()
630 || self.js_tool.is_some()
631 || !self.source_folders.is_empty()
632 || !self.asset_folders.is_empty()
633 }
634
635 /// Every external tool binary this configuration actually needs at some point
636 /// (bundle and/or minify enabled — a pure passthrough config never spawns its
637 /// configured tool, so it has nothing to fail-fast on), paired with its
638 /// human-readable install hint for a fail-fast startup error.
639 fn required_tool_binaries(&self) -> Vec<(&'static str, &'static str)> {
640 let mut required = Vec::new();
641 if let Some((css_tool, options)) = &self.css_tool {
642 if options.is_bundle() || options.is_minify() {
643 required.push((css_tool.binary_name(), css_tool.install_hint()));
644 }
645 }
646 if let Some((js_tool, options)) = &self.js_tool {
647 if options.is_bundle() || options.is_minify() {
648 required.push((js_tool.binary_name(), js_tool.install_hint()));
649 }
650 }
651 required
652 }
653
654 /// Every directory to watch for source changes: the source folders, the CSS
655 /// `@import` roots, and the asset folders, deduplicated so a directory registered
656 /// under more than one role is watched once.
657 fn watch_targets(&self) -> Vec<PathBuf> {
658 let mut targets = Vec::new();
659 for dir in self
660 .source_folders
661 .iter()
662 .chain(self.bundle_roots.iter())
663 .chain(self.asset_folders.iter())
664 {
665 if !targets.contains(dir) {
666 targets.push(dir.clone());
667 }
668 }
669 targets
670 }
671
672 /// Run every configured build pipeline (CSS/JS tools, asset folders) once and
673 /// return, without starting the HTTP server. A one-shot equivalent of the
674 /// startup build `run*` does automatically — for deploy tooling that wants to
675 /// populate the output dir ahead of time (e.g. a `cargo run --bin build_static`
676 /// step before baking a Docker image), mirroring a one-shot content
677 /// builder's `build()` (e.g. `mini_docs::Builder::build()`).
678 ///
679 /// # Errors
680 ///
681 /// - `Err(StaticError::PipelineSetup)` if a configured tool's binary that's
682 /// actually needed (bundle or minify enabled) is missing from `PATH` — checked
683 /// before anything runs, same as [`Server::run_on`].
684 /// - `Err(StaticError::Build)` if a configured pipeline step fails (a tool
685 /// invocation error, a filesystem error writing output, etc.).
686 ///
687 /// # Example
688 ///
689 /// ```no_run
690 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
691 /// use mini_static::Server;
692 /// use std::path::Path;
693 ///
694 /// let server = Server::new(Path::new("./public"))?;
695 /// server.build().await?;
696 /// # Ok(())
697 /// # }
698 /// ```
699 pub async fn build(&self) -> Result<(), StaticError> {
700 for (binary, install_hint) in self.required_tool_binaries() {
701 if !tool::locate_on_path(binary) {
702 return Err(StaticError::PipelineSetup(format!(
703 "{binary} not found on PATH ({install_hint})"
704 )));
705 }
706 }
707
708 let pipeline = SourcePipeline::new(
709 self.source_folders.clone(),
710 self.bundle_roots.clone(),
711 self.asset_folders.clone(),
712 self.output_dir.clone(),
713 self.css_tool.clone(),
714 self.js_tool.clone(),
715 self.prune_output,
716 Broadcaster::new(),
717 );
718 pipeline
719 .full_build()
720 .await
721 .map_err(|e| StaticError::Build(e.to_string()))
722 }
723
724 /// Resolve a request path under the server's root.
725 ///
726 /// This is a lower-level API for resolving paths without generating HTTP responses.
727 /// For most use cases, prefer [`Server::handle_request`] or the `run*` methods.
728 ///
729 /// # Returns
730 ///
731 /// - `Ok(PathBuf)` if the path resolves to a file within root.
732 /// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
733 pub fn resolve(&self, request_path: &str) -> Result<PathBuf, StaticError> {
734 resolve::resolve_with_canonical_root(&self.root_canon, request_path)
735 }
736
737 /// Run the server on a specific address with a configurable header-read timeout.
738 ///
739 /// Spawns the server in a background Tokio task and returns immediately with the
740 /// assigned port number and a [`ServerHandle`]. Call `handle.shutdown().await` to
741 /// stop accepting new connections and wait for in-flight connections to finish.
742 /// Dropping the handle instead leaves the server running for the life of the process.
743 ///
744 /// # Header-Read Timeout
745 ///
746 /// Connections that don't send complete HTTP headers within `header_timeout` are closed.
747 /// This prevents slowloris attacks and resource exhaustion from incomplete requests. The
748 /// timeout applies only to the header-read phase — once a complete header block has been
749 /// read, the connection is handed off with no further time bound, so long-lived response
750 /// bodies (e.g. the live-reload SSE stream from [`Server::with_live_reload`]) are not cut
751 /// off mid-stream.
752 ///
753 /// # Precompressed Sidecars
754 ///
755 /// If a request's `Accept-Encoding` allows `br` or `gzip` (preferring `br`) and a
756 /// sibling `<path>.br`/`<path>.gz` exists next to the resolved file, its bytes are
757 /// served instead with a matching `Content-Encoding`. Every file response carries
758 /// `Vary: Accept-Encoding` so intermediate caches don't serve the wrong variant to a
759 /// differently-capable client.
760 ///
761 /// # Arguments
762 ///
763 /// * `addr` - Socket address to bind to (e.g., `127.0.0.1:0` for loopback ephemeral,
764 /// or `0.0.0.0:8080` to bind all interfaces on a fixed port).
765 /// * `header_timeout` - Maximum time to wait for complete HTTP headers on each connection.
766 ///
767 /// # Returns
768 ///
769 /// - `Ok((u16, ServerHandle))` with the assigned port number and a handle for graceful shutdown.
770 /// - `Err(StaticError::Io)` if binding to the socket fails.
771 /// - `Err(StaticError::PipelineSetup)` if a configured [`CssTool`]/[`JsTool`]'s binary
772 /// is not found on `PATH`. Checked before the listener binds: a deployment whose
773 /// configured pipeline can never run should fail visibly at boot, not be discovered
774 /// later as a missing/stale asset.
775 pub async fn run_on(
776 &self,
777 addr: SocketAddr,
778 header_timeout: Duration,
779 ) -> Result<(u16, ServerHandle), StaticError> {
780 for (binary, install_hint) in self.required_tool_binaries() {
781 if !tool::locate_on_path(binary) {
782 return Err(StaticError::PipelineSetup(format!(
783 "{binary} not found on PATH ({install_hint})"
784 )));
785 }
786 }
787
788 let listener = TcpListener::bind(addr).await.map_err(StaticError::Io)?;
789 let port = listener.local_addr().map_err(StaticError::Io)?.port();
790
791 let mut server = self.clone();
792 if server.live_reload {
793 let broadcaster = Broadcaster::new();
794
795 // The build pipelines react to SOURCE folders only; the output dir is never
796 // watched. Watching the output would feed each pipeline its own writes back
797 // into its trigger — the feedback loop this layering exists to prevent.
798 if server.has_pipeline() {
799 let pipeline = Arc::new(SourcePipeline::new(
800 server.source_folders.clone(),
801 server.bundle_roots.clone(),
802 server.asset_folders.clone(),
803 server.output_dir.clone(),
804 server.css_tool.clone(),
805 server.js_tool.clone(),
806 server.prune_output,
807 broadcaster.clone(),
808 ));
809 let mut rx = broadcaster.subscribe();
810 tokio::spawn(async move {
811 // One-shot startup build (and optional prune) first, so the earliest
812 // request already sees fresh output rather than yesterday's.
813 if let Err(e) = pipeline.full_build().await {
814 eprintln!("source pipeline build error: {e}");
815 }
816 while let Some(event) = rx.recv().await {
817 if let Err(e) = pipeline
818 .process_change(&event.path, &event.change_type)
819 .await
820 {
821 eprintln!("source pipeline error: {e}");
822 }
823 }
824 });
825 }
826
827 for dir in server.watch_targets() {
828 start_watching(Arc::new(dir), broadcaster.clone());
829 }
830
831 server.broadcaster = Some(broadcaster);
832 } else if server.has_pipeline() {
833 // No live-reload: still run the one-shot build so a release boot reflects the
834 // current sources. The broadcaster is a throwaway — there is no browser to
835 // notify, so broadcasting into it is a no-op.
836 let pipeline = Arc::new(SourcePipeline::new(
837 server.source_folders.clone(),
838 server.bundle_roots.clone(),
839 server.asset_folders.clone(),
840 server.output_dir.clone(),
841 server.css_tool.clone(),
842 server.js_tool.clone(),
843 server.prune_output,
844 Broadcaster::new(),
845 ));
846 tokio::spawn(async move {
847 if let Err(e) = pipeline.full_build().await {
848 eprintln!("source pipeline build error: {e}");
849 }
850 });
851 }
852 let semaphore = Arc::new(Semaphore::new(server.max_connections));
853 let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
854
855 let accept_task = tokio::spawn(async move {
856 let mut backoff = ACCEPT_BACKOFF_INITIAL;
857 let mut join_set: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
858 let mut shutdown_pin = std::pin::pin!(shutdown_rx);
859 let mut shutting_down = false;
860
861 loop {
862 if !shutting_down {
863 // The accept-and-permit step and the shutdown signal race in a single
864 // `select!` so shutdown can preempt a pending accept or a permit wait
865 // cleanly, at any point — not just between loop iterations.
866 tokio::select! {
867 accepted = accept_and_permit(&listener, &mut backoff, &semaphore) => {
868 match accepted {
869 Some((stream, permit)) => {
870 let server = server.clone();
871 join_set.spawn(async move {
872 let _permit = permit;
873 serve_connection(stream, server, header_timeout).await;
874 });
875 }
876 None => shutting_down = true,
877 }
878 }
879 _ = shutdown_pin.as_mut() => {
880 shutting_down = true;
881 }
882 }
883 continue;
884 }
885
886 // Stop accepting; drain already-spawned connections before returning.
887 match join_set.join_next().await {
888 Some(_) => continue,
889 None => break,
890 }
891 }
892 });
893
894 Ok((
895 port,
896 ServerHandle {
897 shutdown_tx: Some(shutdown_tx),
898 accept_task,
899 },
900 ))
901 }
902
903 /// Run the server on loopback (127.0.0.1), binding an ephemeral port.
904 ///
905 /// Thin wrapper around [`Server::run_on`] — see it for the header-read timeout and
906 /// sidecar semantics, and for what the returned [`ServerHandle`] does.
907 pub async fn run(&self, header_timeout: Duration) -> Result<(u16, ServerHandle), StaticError> {
908 self.run_on(([127, 0, 0, 1], 0).into(), header_timeout)
909 .await
910 }
911
912 /// Run the server on all interfaces (0.0.0.0) at `port` (0 for an ephemeral port).
913 ///
914 /// Useful for containerized deployments and reverse-proxy setups. Thin wrapper
915 /// around [`Server::run_on`] — see it for the header-read timeout and sidecar
916 /// semantics, and for what the returned [`ServerHandle`] does.
917 pub async fn run_all(
918 &self,
919 port: u16,
920 header_timeout: Duration,
921 ) -> Result<(u16, ServerHandle), StaticError> {
922 self.run_on(([0, 0, 0, 0], port).into(), header_timeout)
923 .await
924 }
925
926 /// Run the server on loopback with the default 30-second header-read timeout.
927 ///
928 /// The recommended entry point for tests and lightweight services that don't need a
929 /// custom timeout. Thin wrapper around [`Server::run`].
930 ///
931 /// # Example
932 ///
933 /// ```no_run
934 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
935 /// use mini_static::Server;
936 /// use std::path::Path;
937 ///
938 /// let server = Server::new(Path::new("./public"))?;
939 /// let (port, handle) = server.run_ephemeral().await?;
940 /// println!("Server ready on http://127.0.0.1:{}", port);
941 /// handle.shutdown().await;
942 /// # Ok(())
943 /// # }
944 /// ```
945 pub async fn run_ephemeral(&self) -> Result<(u16, ServerHandle), StaticError> {
946 self.run(DEFAULT_HEADER_TIMEOUT).await
947 }
948
949 /// Produce the HTTP response for a request, streaming file bodies to the client.
950 ///
951 /// This is the crate's single request-handling path: the `run*` accept loop calls it,
952 /// and so should any async server embedding `mini-static` as a fallback route (e.g.
953 /// `mini-unified`). It never blocks the calling task — path resolution runs on Tokio's
954 /// blocking-thread pool via `spawn_blocking`, and the file is read via async I/O.
955 ///
956 /// File responses are backed by `FileBody`, which hands hyper one 64 KB chunk at a
957 /// time as `poll_frame` is driven: memory use stays bounded to one chunk per in-flight
958 /// response regardless of file size.
959 ///
960 /// `headers` are the request's headers; `If-None-Match` (304 on a matching ETag) and
961 /// `Accept-Encoding` (precompressed sidecar selection, see [`Server::run_on`]) are the
962 /// ones read today. Only `GET` and `HEAD` are allowed; anything else gets a 405 with an
963 /// `Allow` header. Missing files and traversal attempts both get an identical 404, so a
964 /// response never discloses whether a path exists outside the root.
965 pub async fn handle_request(
966 &self,
967 method: &Method,
968 request_path: &str,
969 headers: &HeaderMap,
970 ) -> Response<ResponseBody> {
971 if method != Method::GET && method != Method::HEAD {
972 return text(
973 response(StatusCode::METHOD_NOT_ALLOWED).header("Allow", "GET, HEAD"),
974 "method not allowed\n",
975 );
976 }
977
978 // Live-reload SSE stream — only reachable when `with_live_reload()` was called
979 // and the server was started via a `run*` method (those are the only paths that
980 // populate `broadcaster`).
981 if *method == Method::GET && request_path == reload::LIVE_RELOAD_PATH {
982 if let Some(broadcaster) = &self.broadcaster {
983 return finish(
984 response(StatusCode::OK)
985 .header("Content-Type", "text/event-stream")
986 .header("Cache-Control", "no-cache")
987 .header("Connection", "keep-alive")
988 .body(ResponseBody::Sse(SseBody::new(broadcaster.subscribe()))),
989 );
990 }
991 }
992
993 // `resolve()` does blocking filesystem syscalls (`canonicalize()`, up to two per
994 // request). Running those directly in this `async fn` would block whichever
995 // Tokio worker thread happens to be driving it, stalling every other task
996 // scheduled on that thread for the duration of the syscalls. `spawn_blocking`
997 // moves the work onto Tokio's dedicated blocking thread pool instead.
998 let server = self.clone();
999 let owned_request_path = request_path.to_string();
1000 let resolved =
1001 tokio::task::spawn_blocking(move || server.resolve(&owned_request_path)).await;
1002 let path = match resolved {
1003 Err(_) => return internal_error_response(),
1004 Ok(Err(e)) => {
1005 return text(
1006 response(StatusCode::NOT_FOUND),
1007 format!("{}\n", e.user_message()),
1008 )
1009 }
1010 Ok(Ok(path)) => path,
1011 };
1012
1013 // A directory served via its `index.html` needs a trailing slash to establish the
1014 // correct base for the page's relative links. Compare against the *decoded*
1015 // request path so a percent-encoded explicit request for index.html (e.g.
1016 // `/docs/index.htm%6c`) is recognized as such instead of producing a redirect to a
1017 // still-encoded, broken Location.
1018 let decoded_request_path = resolve::decode_request_path(request_path);
1019 if path.file_name().is_some_and(|name| name == "index.html")
1020 && !decoded_request_path.ends_with('/')
1021 && !decoded_request_path.ends_with("index.html")
1022 {
1023 // `location` is built from the (attacker-controlled) request path; `finish()`
1024 // degrades to 400 instead of panicking if it ever contains bytes invalid in a
1025 // header value.
1026 let location = format!("{}/", request_path.trim_end_matches('/'));
1027 return text(
1028 response(StatusCode::MOVED_PERMANENTLY).header("Location", location),
1029 "moved\n",
1030 );
1031 }
1032
1033 let Ok(file) = File::open(&path).await else {
1034 return internal_error_response();
1035 };
1036 let Ok(metadata) = file.metadata().await else {
1037 return internal_error_response();
1038 };
1039
1040 let content_type = mime_type_for_path(&path);
1041 // Live-reload and spa-mode HTML injection both need the original, uncompressed
1042 // bytes to splice their script into — never substitute a precompressed sidecar on
1043 // this path. `broadcaster` is only `Some` when live-reload is enabled (see
1044 // `Server::with_live_reload`); `spa_mode` is independent of it (see
1045 // `Server::with_spa_mode`/`with_spa_root`) — either alone is enough to trigger
1046 // injection.
1047 let html_injection =
1048 (self.broadcaster.is_some() || self.spa_mode) && content_type.starts_with("text/html");
1049
1050 let range_header = header_str(headers, "range");
1051 let if_range_header = header_str(headers, "if-range");
1052
1053 let accept_encoding = header_str(headers, "accept-encoding");
1054 // Skip precompressed sidecars when Range is requested (serve original file instead).
1055 let sidecar = if html_injection || range_header.is_some() {
1056 None
1057 } else {
1058 select_precompressed_sidecar(&path, accept_encoding).await
1059 };
1060 let (mut file, metadata, content_encoding) = match sidecar {
1061 Some((sidecar_file, sidecar_metadata, encoding)) => {
1062 (sidecar_file, sidecar_metadata, Some(encoding))
1063 }
1064 None => (file, metadata, None),
1065 };
1066
1067 // HTML injection is skipped for a served precompressed sidecar (already final
1068 // bytes from a build step) — see `html_injection`'s definition above.
1069 let etag = generate_etag(&metadata);
1070 let cache_control = self.cache_control_for(&path);
1071
1072 if header_str(headers, "if-none-match").is_some_and(|value| is_etag_match(value, &etag)) {
1073 return finish(
1074 Response::builder()
1075 .status(StatusCode::NOT_MODIFIED)
1076 .header("Cache-Control", cache_control)
1077 .header("Vary", "Accept-Encoding")
1078 .header("ETag", etag)
1079 .header("Accept-Ranges", "bytes")
1080 .body(ResponseBody::Buffered(Full::new(Bytes::new()))),
1081 );
1082 }
1083
1084 // `Some` when the served representation differs from the file's raw bytes and had
1085 // to be built in memory; `None` means stream the open file as-is. Computed before
1086 // the HEAD check below because RFC 9110 requires a HEAD response's headers —
1087 // `Content-Length` included — to match what a GET would send, even though the body
1088 // itself is dropped.
1089 let transformed: Option<Bytes> = if html_injection {
1090 let mut html = Vec::with_capacity(metadata.len() as usize);
1091 if file.read_to_end(&mut html).await.is_err() {
1092 return internal_error_response();
1093 }
1094 if self.broadcaster.is_some() {
1095 reload::inject_reload_script(&mut html);
1096 }
1097 if self.spa_mode {
1098 spa::inject_spa_script(&mut html, self.spa_root.as_deref(), &self.spa_transition);
1099 }
1100 Some(Bytes::from(html))
1101 } else {
1102 None
1103 };
1104
1105 let file_size = transformed
1106 .as_ref()
1107 .map_or(metadata.len(), |bytes| bytes.len() as u64);
1108
1109 // Handle Range requests.
1110 let range_outcome = range_header.map(|h| parse_range_header(h, file_size));
1111 let range_check = if let Some(outcome) = &range_outcome {
1112 match outcome {
1113 RangeOutcome::Satisfiable(start, end) => {
1114 // If-Range validation: stale If-Range ignores Range, serves full 200.
1115 if let Some(if_range) = if_range_header {
1116 if !if_range_valid(if_range, &etag) {
1117 RangeCheck::IgnoreRange
1118 } else {
1119 RangeCheck::Satisfiable(*start, *end)
1120 }
1121 } else {
1122 RangeCheck::Satisfiable(*start, *end)
1123 }
1124 }
1125 RangeOutcome::MultiRangeIgnored => RangeCheck::IgnoreRange,
1126 RangeOutcome::Unsatisfiable => RangeCheck::Unsatisfiable,
1127 RangeOutcome::NoRange => RangeCheck::IgnoreRange,
1128 }
1129 } else {
1130 RangeCheck::IgnoreRange
1131 };
1132
1133 match &range_check {
1134 RangeCheck::Unsatisfiable => {
1135 return finish(
1136 Response::builder()
1137 .status(StatusCode::RANGE_NOT_SATISFIABLE)
1138 .header("Content-Range", format!("bytes */{}", file_size))
1139 .header("Accept-Ranges", "bytes")
1140 .body(ResponseBody::Buffered(Full::new(Bytes::new()))),
1141 );
1142 }
1143 RangeCheck::Satisfiable(start, end) => {
1144 let range_len = end - start + 1;
1145
1146 // Seek to start position; if sidecar, we already skipped it above.
1147 if transformed.is_none()
1148 && file.seek(std::io::SeekFrom::Start(*start)).await.is_err()
1149 {
1150 return internal_error_response();
1151 }
1152
1153 // HEAD must not return a body (RFC 9110).
1154 let body = if *method == Method::HEAD {
1155 ResponseBody::Buffered(Full::new(Bytes::new()))
1156 } else {
1157 match transformed {
1158 Some(ref bytes) => ResponseBody::Buffered(Full::new(
1159 bytes.slice(*start as usize..(*end as usize + 1)),
1160 )),
1161 None => ResponseBody::Streamed(FileBody::new_ranged(file, range_len)),
1162 }
1163 };
1164
1165 let mut builder = Response::builder()
1166 .status(StatusCode::PARTIAL_CONTENT)
1167 .header("Content-Type", content_type)
1168 .header("Content-Length", range_len.to_string())
1169 .header(
1170 "Content-Range",
1171 format!("bytes {}-{}/{}", start, end, file_size),
1172 )
1173 .header("Cache-Control", cache_control)
1174 .header("Vary", "Accept-Encoding")
1175 .header("ETag", etag)
1176 .header("Accept-Ranges", "bytes");
1177 if let Some(encoding) = content_encoding {
1178 builder = builder.header("Content-Encoding", encoding);
1179 }
1180 return finish(builder.body(body));
1181 }
1182 RangeCheck::IgnoreRange => {}
1183 }
1184
1185 // HEAD must not return a body (RFC 9110).
1186 let body = if *method == Method::HEAD {
1187 ResponseBody::Buffered(Full::new(Bytes::new()))
1188 } else {
1189 match transformed {
1190 Some(bytes) => ResponseBody::Buffered(Full::new(bytes)),
1191 None => ResponseBody::Streamed(FileBody::new(file)),
1192 }
1193 };
1194
1195 let mut builder = response(StatusCode::OK)
1196 .header("Content-Type", content_type)
1197 .header("Content-Length", file_size.to_string())
1198 .header("Cache-Control", cache_control)
1199 .header("Vary", "Accept-Encoding")
1200 .header("ETag", etag)
1201 .header("Accept-Ranges", "bytes");
1202 if let Some(encoding) = content_encoding {
1203 builder = builder.header("Content-Encoding", encoding);
1204 }
1205 finish(builder.body(body))
1206 }
1207}
1208
1209/// Ceiling on how many bytes `read_header_prefix` buffers before giving up. Without this,
1210/// a client that trickles bytes forever without ever sending the terminating blank line
1211/// could grow the buffer without limit — the header-read timeout alone doesn't bound
1212/// memory, only wall-clock time, and a sufficiently patient sender could still send
1213/// unbounded data before the deadline fires.
1214const MAX_HEADER_BYTES: usize = 64 * 1024;
1215
1216/// Why `read_header_prefix` gave up before seeing a complete header block. Every variant
1217/// is a legitimate reason to drop the connection — none is treated specially by the
1218/// caller today, but the distinction is worth preserving for anyone debugging this later.
1219#[derive(Debug)]
1220enum HeaderReadError {
1221 /// The client closed the connection (or shut down its write half) before sending a
1222 /// complete header block.
1223 ConnectionClosed,
1224 /// More than `MAX_HEADER_BYTES` were buffered without seeing `\r\n\r\n`.
1225 TooLarge,
1226 /// The underlying socket read failed. Kept rather than discarded so a future `log`
1227 /// feature has the real I/O error to report instead of an opaque unit variant.
1228 #[allow(dead_code)]
1229 Io(std::io::Error),
1230}
1231
1232/// Reads from `stream` until a complete HTTP header block (`\r\n\r\n`) has been buffered,
1233/// returning every byte read so far — which may include bytes past the header block
1234/// (request body, or a second pipelined request) if the client sent them in the same
1235/// read. Callers pair this with `tokio::time::timeout` to bound how long the header phase
1236/// itself may take; this function has no timeout of its own, only the size ceiling in
1237/// `MAX_HEADER_BYTES`.
1238async fn read_header_prefix(stream: &mut TcpStream) -> Result<Vec<u8>, HeaderReadError> {
1239 let mut buf = Vec::new();
1240 let mut chunk = [0u8; 4096];
1241
1242 loop {
1243 let n = stream.read(&mut chunk).await.map_err(HeaderReadError::Io)?;
1244 if n == 0 {
1245 return Err(HeaderReadError::ConnectionClosed);
1246 }
1247 buf.extend_from_slice(&chunk[..n]);
1248
1249 if buf.len() > MAX_HEADER_BYTES {
1250 return Err(HeaderReadError::TooLarge);
1251 }
1252 // Only the tail can hold a terminator this read completed: the `n` new bytes plus
1253 // the 3 before them. Rescanning the whole buffer every time would make the header
1254 // read quadratic in the bytes received.
1255 let scan_from = buf.len().saturating_sub(n + 3);
1256 if buf[scan_from..].windows(4).any(|w| w == b"\r\n\r\n") {
1257 return Ok(buf);
1258 }
1259 }
1260}
1261
1262/// Wraps an accepted `TcpStream` whose header block has already been drained into
1263/// `prefix` (by `read_header_prefix`, ahead of the connection being handed to hyper).
1264/// Reads replay `prefix` first, then fall through to the live socket — so hyper sees
1265/// exactly the byte stream it would have seen without the pre-read, just sourced from two
1266/// buffers back-to-back instead of one continuous one. Writes pass straight through.
1267struct PrefixedIo {
1268 prefix: Bytes,
1269 prefix_pos: usize,
1270 inner: TcpStream,
1271}
1272
1273impl PrefixedIo {
1274 fn new(prefix: Vec<u8>, inner: TcpStream) -> Self {
1275 PrefixedIo {
1276 prefix: Bytes::from(prefix),
1277 prefix_pos: 0,
1278 inner,
1279 }
1280 }
1281}
1282
1283impl AsyncRead for PrefixedIo {
1284 fn poll_read(
1285 self: Pin<&mut Self>,
1286 cx: &mut Context<'_>,
1287 buf: &mut ReadBuf<'_>,
1288 ) -> Poll<std::io::Result<()>> {
1289 let this = self.get_mut();
1290 if this.prefix_pos < this.prefix.len() {
1291 let remaining = &this.prefix[this.prefix_pos..];
1292 let n = remaining.len().min(buf.remaining());
1293 buf.put_slice(&remaining[..n]);
1294 this.prefix_pos += n;
1295 return Poll::Ready(Ok(()));
1296 }
1297 Pin::new(&mut this.inner).poll_read(cx, buf)
1298 }
1299}
1300
1301impl AsyncWrite for PrefixedIo {
1302 fn poll_write(
1303 self: Pin<&mut Self>,
1304 cx: &mut Context<'_>,
1305 buf: &[u8],
1306 ) -> Poll<std::io::Result<usize>> {
1307 Pin::new(&mut self.get_mut().inner).poll_write(cx, buf)
1308 }
1309
1310 fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
1311 Pin::new(&mut self.get_mut().inner).poll_flush(cx)
1312 }
1313
1314 fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
1315 Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
1316 }
1317}
1318
1319/// Wires an accepted connection up to the hyper HTTP/1 service.
1320///
1321/// `header_timeout` bounds only the header-read phase (`read_header_prefix`, run before
1322/// hyper ever sees the connection). Once a complete header block has been read, the
1323/// connection is handed to hyper with no further time bound — deliberately, since a
1324/// response body may legitimately outlive `header_timeout` by design (the live-reload SSE
1325/// stream is the motivating case: it stays open until a watched file changes, which may
1326/// be minutes or hours after the request). Wrapping the whole connection lifetime in
1327/// `header_timeout` — the prior implementation — silently truncated exactly that stream
1328/// once `header_timeout` elapsed, aborting the response mid-write after headers had
1329/// already been sent (the client observes this as a chunked-encoding error, not a clean
1330/// close). The connection-count ceiling (`Server::with_max_connections`) is what bounds
1331/// resource use from connections held open indefinitely, not this timeout.
1332async fn serve_connection(mut stream: TcpStream, server: Server, header_timeout: Duration) {
1333 let prefix = match timeout(header_timeout, read_header_prefix(&mut stream)).await {
1334 Ok(Ok(prefix)) => prefix,
1335 Ok(Err(_)) | Err(_) => return,
1336 };
1337
1338 let io = TokioIo::new(PrefixedIo::new(prefix, stream));
1339 let svc = service_fn(move |req: Request<Incoming>| {
1340 let server = server.clone();
1341 async move {
1342 let resp = server
1343 .handle_request(req.method(), req.uri().path(), req.headers())
1344 .await;
1345 Ok::<_, Infallible>(resp)
1346 }
1347 });
1348 let _ = AutoBuilder::new(TokioExecutor::new())
1349 .serve_connection(io, svc)
1350 .await;
1351}
1352
1353/// Default header-read timeout used by [`Server::run_ephemeral`].
1354const DEFAULT_HEADER_TIMEOUT: Duration = Duration::from_secs(30);
1355
1356/// Default grace period `ServerHandle::shutdown()` waits for in-flight connections to
1357/// finish on their own before aborting whatever is left. A connection with no
1358/// self-imposed end — an open live-reload SSE stream, or any keep-alive connection whose
1359/// peer simply never closes it — would otherwise let `shutdown()` hang forever waiting
1360/// for it to finish naturally. Every wait in this crate has a stated upper bound;
1361/// shutdown is no exception.
1362const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
1363
1364/// A handle to a server started by one of the `Server::run*` methods.
1365///
1366/// Dropping this handle without calling `shutdown()` leaves the server running in the
1367/// background for the life of the process. Call `shutdown()` to stop accepting new
1368/// connections and wait for already-accepted connections to finish before returning.
1369pub struct ServerHandle {
1370 shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
1371 accept_task: tokio::task::JoinHandle<()>,
1372}
1373
1374impl ServerHandle {
1375 /// Stop accepting new connections and wait up to `DEFAULT_SHUTDOWN_DRAIN_TIMEOUT`
1376 /// (5s) for in-flight connections to finish on their own. Equivalent to
1377 /// `shutdown_with_timeout(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT)` — see that method for what
1378 /// happens to connections still open once the grace period elapses.
1379 pub async fn shutdown(self) {
1380 self.shutdown_with_timeout(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT)
1381 .await;
1382 }
1383
1384 /// Stop accepting new connections and wait up to `drain_timeout` for in-flight
1385 /// connections to finish on their own.
1386 ///
1387 /// Connections still open once `drain_timeout` elapses are aborted rather than
1388 /// waited on further: dropping the accept task drops its `JoinSet`, which aborts
1389 /// every task still tracked in it (see `tokio::task::JoinSet`'s own drop behavior) —
1390 /// which in turn drops each connection's socket, closing it. This is what bounds
1391 /// shutdown when a connection has no natural end of its own (the live-reload SSE
1392 /// stream is the motivating case: it stays open until a watched file changes, which
1393 /// may never happen before the process needs to exit).
1394 pub async fn shutdown_with_timeout(mut self, drain_timeout: Duration) {
1395 if let Some(tx) = self.shutdown_tx.take() {
1396 let _ = tx.send(());
1397 }
1398 if timeout(drain_timeout, &mut self.accept_task).await.is_err() {
1399 self.accept_task.abort();
1400 }
1401 }
1402}
1403
1404/// Read a request header as a `&str`, or `None` if it's absent or not valid ASCII.
1405fn header_str<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> {
1406 headers.get(name).and_then(|value| value.to_str().ok())
1407}
1408
1409/// Start a response carrying the baseline security header every response in this crate
1410/// sends. The 304 path is the one exception and builds its own — a 304 repeats only the
1411/// caching validators, not the full header set.
1412fn response(status: StatusCode) -> Builder {
1413 Response::builder()
1414 .status(status)
1415 .header("X-Content-Type-Options", "nosniff")
1416}
1417
1418/// Finish `builder` with a plain-text body. `&'static str` bodies borrow rather than
1419/// allocate; `String` bodies (the 404 message) are moved in.
1420fn text(builder: Builder, body: impl Into<Bytes>) -> Response<ResponseBody> {
1421 finish(builder.body(ResponseBody::Buffered(Full::new(body.into()))))
1422}
1423
1424/// Finishes building a response, degrading to a generic 400 instead of panicking if any
1425/// header value turns out to be invalid for use as an HTTP header value.
1426///
1427/// Every header value that reaches `Response::builder()` in this module is either a
1428/// static string or formatted from internal, already-validated data (a byte count, an
1429/// mtime, a fixed method list) — none of it can actually fail today. But `.unwrap()`
1430/// on that assumption is exactly the kind of thing that turns "can't happen" into a
1431/// production panic the day someone adds a header built from new input without
1432/// re-deriving that guarantee. Routing every response through this one fallible path
1433/// means that mistake fails safe instead of panicking.
1434fn finish(built: Result<Response<ResponseBody>, hyper::http::Error>) -> Response<ResponseBody> {
1435 built.unwrap_or_else(|_| bad_request_response())
1436}
1437
1438// `internal_error_response()` and `bad_request_response()` are the fallback responses
1439// `finish()` itself degrades to — every header and body here is a fixed string with no
1440// external input, so `.body(...)` cannot fail. They can't be routed through `finish()`
1441// without it degrading to itself on failure.
1442fn internal_error_response() -> Response<ResponseBody> {
1443 response(StatusCode::INTERNAL_SERVER_ERROR)
1444 .body(ResponseBody::Buffered(Full::new(Bytes::from_static(
1445 b"internal server error\n",
1446 ))))
1447 .unwrap()
1448}
1449
1450fn bad_request_response() -> Response<ResponseBody> {
1451 response(StatusCode::BAD_REQUEST)
1452 .body(ResponseBody::Buffered(Full::new(Bytes::from_static(
1453 b"bad request\n",
1454 ))))
1455 .unwrap()
1456}
1457
1458/// `Content-Encoding` name and sidecar file extension for each supported precompressed
1459/// variant, in preference order — brotli wins when a client accepts both and both
1460/// sidecars exist.
1461const SIDECAR_ENCODINGS: [(&str, &str); 2] = [("br", ".br"), ("gzip", ".gz")];
1462
1463/// Whether `accept_encoding` allows `encoding`.
1464///
1465/// Matches by substring rather than parsing `q`-value weights or the `identity`/`*`
1466/// directives — a lighter-weight negotiation than a general HTTP client would need,
1467/// sufficient for deciding between two static sidecar files.
1468fn accepts_encoding(accept_encoding: Option<&str>, encoding: &str) -> bool {
1469 accept_encoding.is_some_and(|header| header.contains(encoding))
1470}
1471
1472/// Look for a precompressed sidecar (`<path>.br` / `<path>.gz`) matching the client's
1473/// `Accept-Encoding`, and return its open file, metadata, and encoding name if found.
1474///
1475/// `path` must already be the fully resolved, canonicalized path `resolve()` produced.
1476/// The sidecar path is built by appending an extension to it — never by re-resolving a
1477/// modified request path — so this lookup can't become a second traversal surface: any
1478/// path this function reads is provably a sibling of a path `resolve()` already cleared.
1479async fn select_precompressed_sidecar(
1480 path: &Path,
1481 accept_encoding: Option<&str>,
1482) -> Option<(File, fs::Metadata, &'static str)> {
1483 for (encoding, ext) in SIDECAR_ENCODINGS {
1484 if !accepts_encoding(accept_encoding, encoding) {
1485 continue;
1486 }
1487 let mut sidecar = path.as_os_str().to_os_string();
1488 sidecar.push(ext);
1489 let sidecar_path = PathBuf::from(sidecar);
1490
1491 // Tripwire for the traversal boundary: a sidecar path built by appending a suffix
1492 // must stay in the same directory as `path` (which `resolve()` already proved is
1493 // inside root). `ext` is always one of the two static literals in
1494 // `SIDECAR_ENCODINGS`, never derived from request input, so this can only fire if
1495 // a future change starts deriving `sidecar` some other way.
1496 debug_assert_eq!(
1497 sidecar_path.parent(),
1498 path.parent(),
1499 "sidecar path must stay in the same directory as the already-resolved path"
1500 );
1501
1502 if let Ok(sidecar_file) = File::open(&sidecar_path).await {
1503 if let Ok(sidecar_metadata) = sidecar_file.metadata().await {
1504 return Some((sidecar_file, sidecar_metadata, encoding));
1505 }
1506 }
1507 }
1508 None
1509}
1510
1511/// Generate an ETag for a file based on modification time and size.
1512///
1513/// Format: `"<size>-<mtime_secs>"`
1514fn generate_etag(metadata: &fs::Metadata) -> String {
1515 let mtime = metadata
1516 .modified()
1517 .ok()
1518 .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
1519 .map(|d| d.as_secs())
1520 .unwrap_or(0);
1521 format!("\"{}-{}\"", metadata.len(), mtime)
1522}
1523
1524/// Determine MIME type from file path extension.
1525fn mime_type_for_path(path: &Path) -> &'static str {
1526 let ext = path
1527 .extension()
1528 .and_then(|ext| ext.to_str())
1529 .unwrap_or_default()
1530 .to_lowercase();
1531
1532 match ext.as_str() {
1533 "html" | "htm" => "text/html; charset=utf-8",
1534 "css" => "text/css; charset=utf-8",
1535 "js" => "application/javascript; charset=utf-8",
1536 "json" => "application/json; charset=utf-8",
1537 "svg" => "image/svg+xml",
1538 "png" => "image/png",
1539 "jpg" | "jpeg" => "image/jpeg",
1540 "gif" => "image/gif",
1541 "webp" => "image/webp",
1542 "ico" => "image/x-icon",
1543 "woff" => "font/woff",
1544 "woff2" => "font/woff2",
1545 "ttf" => "font/ttf",
1546 "md" | "markdown" => "text/markdown; charset=utf-8",
1547 "txt" => "text/plain; charset=utf-8",
1548 "xml" => "application/xml",
1549 "pdf" => "application/pdf",
1550 "zip" => "application/zip",
1551 _ => "application/octet-stream",
1552 }
1553}
1554
1555/// Check if the If-None-Match header matches the current ETag.
1556/// Handles both exact match and wildcard (*) comparison per RFC 9110.
1557fn is_etag_match(if_none_match: &str, etag: &str) -> bool {
1558 if if_none_match == "*" {
1559 return true;
1560 }
1561 if_none_match.split(',').any(|tag| tag.trim() == etag)
1562}
1563
1564#[derive(Debug)]
1565enum RangeOutcome {
1566 NoRange,
1567 Satisfiable(u64, u64),
1568 Unsatisfiable,
1569 MultiRangeIgnored,
1570}
1571
1572enum RangeCheck {
1573 IgnoreRange,
1574 Satisfiable(u64, u64),
1575 Unsatisfiable,
1576}
1577
1578fn parse_range_header(header: &str, file_size: u64) -> RangeOutcome {
1579 let header = header.trim();
1580 if !header.starts_with("bytes=") {
1581 return RangeOutcome::NoRange;
1582 }
1583
1584 let range_spec = &header[6..];
1585
1586 if range_spec.contains(',') {
1587 return RangeOutcome::MultiRangeIgnored;
1588 }
1589
1590 if let Some(suffix_pos) = range_spec.find('-') {
1591 if suffix_pos == 0 {
1592 let suffix_len_str = &range_spec[1..];
1593 if let Ok(suffix_len) = suffix_len_str.parse::<u64>() {
1594 if suffix_len == 0 {
1595 return RangeOutcome::Unsatisfiable;
1596 }
1597 if suffix_len >= file_size {
1598 return RangeOutcome::Satisfiable(0, file_size - 1);
1599 }
1600 return RangeOutcome::Satisfiable(file_size - suffix_len, file_size - 1);
1601 }
1602 return RangeOutcome::Unsatisfiable;
1603 }
1604
1605 let start_str = &range_spec[..suffix_pos];
1606 let end_str = &range_spec[suffix_pos + 1..];
1607
1608 if let Ok(start) = start_str.parse::<u64>() {
1609 if start >= file_size {
1610 return RangeOutcome::Unsatisfiable;
1611 }
1612
1613 if end_str.is_empty() {
1614 return RangeOutcome::Satisfiable(start, file_size - 1);
1615 }
1616
1617 if let Ok(end) = end_str.parse::<u64>() {
1618 if end < start {
1619 return RangeOutcome::Unsatisfiable;
1620 }
1621 let clamped_end = (end + 1).min(file_size) - 1;
1622 if start > clamped_end {
1623 return RangeOutcome::Unsatisfiable;
1624 }
1625 return RangeOutcome::Satisfiable(start, clamped_end);
1626 }
1627 }
1628 }
1629
1630 RangeOutcome::Unsatisfiable
1631}
1632
1633fn if_range_valid(if_range_header: &str, current_etag: &str) -> bool {
1634 if_range_header.trim() == current_etag
1635}
1636
1637#[cfg(test)]
1638#[path = "../tests/unit/server/precompressed_sidecar.rs"]
1639mod precompressed_sidecar_tests;
1640
1641#[cfg(test)]
1642#[path = "../tests/unit/server/file_body.rs"]
1643mod file_body_tests;
1644
1645#[cfg(test)]
1646#[path = "../tests/unit/server/accept.rs"]
1647mod accept_tests;
1648
1649#[cfg(test)]
1650#[path = "../tests/unit/server/finish.rs"]
1651mod finish_tests;
1652
1653#[cfg(test)]
1654#[path = "../tests/unit/server/header_prefix.rs"]
1655mod header_prefix_tests;
1656
1657#[cfg(test)]
1658#[path = "../tests/unit/server/css_bundle.rs"]
1659mod css_bundle_tests;
1660
1661#[cfg(test)]
1662#[path = "../tests/unit/server/asset_folder.rs"]
1663mod asset_folder_tests;
1664
1665#[cfg(test)]
1666#[path = "../tests/unit/server/build_once.rs"]
1667mod build_once_tests;
1668
1669#[cfg(test)]
1670#[path = "../tests/unit/server/range_header.rs"]
1671mod range_header_tests;