use std::cell::RefCell;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use parse_net::{ByteRange, EntityTag, HttpDate, RangeOutcome};
use serve_net::{HttpReply, HttpRequest, Method, Outcome};
use crate::url;
pub const INLINE_LIMIT: u64 = 1 << 20;
const PART: usize = 64 << 10;
const ABORT: Outcome = Outcome::Deferred;
pub(crate) type StreamKey = (u64, u32);
const MAX_IN_FLIGHT: usize = 256;
thread_local! {
static IN_FLIGHT: RefCell<Vec<(StreamKey, String)>> = const { RefCell::new(Vec::new()) };
}
fn begin(key: StreamKey, tag: &str) {
IN_FLIGHT.with(|m| {
let mut m = m.borrow_mut();
m.retain(|(k, _)| *k != key);
if m.len() >= MAX_IN_FLIGHT {
m.remove(0);
}
m.push((key, tag.to_owned()));
});
}
fn end(key: StreamKey) {
IN_FLIGHT.with(|m| m.borrow_mut().retain(|(k, _)| *k != key));
}
pub(crate) fn continuing(key: StreamKey) -> Option<String> {
IN_FLIGHT.with(|m| {
m.borrow()
.iter()
.find(|(k, _)| *k == key)
.map(|(_, t)| t.clone())
})
}
pub(crate) fn next_part(
key: StreamKey,
tag: &str,
found: Option<&Found>,
req: &HttpRequest<'_>,
reply: &mut HttpReply,
) -> Outcome {
let Some(found) = found.filter(|f| etag(f) == tag) else {
end(key);
return ABORT;
};
let (start, len) = match req.header("range").map(|v| {
let mut out = [ByteRange { start: 0, end: 0 }];
(parse_net::byte_ranges(v, found.len, &mut out), out[0])
}) {
Some((Ok(RangeOutcome::Ranges(1)), r)) if if_range_holds(found, tag, req) => {
(r.start, r.end - r.start + 1)
}
_ => (0, found.len),
};
let sent = reply.stream().sent();
let outcome = send_part(found, start, len, sent, reply);
if outcome != Outcome::More {
end(key);
}
outcome
}
fn if_range_holds(found: &Found, tag: &str, req: &HttpRequest<'_>) -> bool {
let Some(v) = req.header("if-range") else {
return true;
};
let current = EntityTag::strong(&tag.as_bytes()[1..tag.len() - 1]).ok();
let modified = found
.modified
.and_then(|m| HttpDate::from_system_time(m).ok());
parse_net::range::parse_if_range(v)
.map(|ir| ir.matches(current.as_ref(), modified))
.unwrap_or(false)
}
#[derive(Clone, Debug)]
pub struct Assets {
pub(crate) mount: String,
pub(crate) dir: PathBuf,
pub(crate) root: PathBuf,
pub(crate) cache_control: Box<str>,
pub(crate) index: Option<Box<str>>,
pub(crate) precompressed: bool,
pub(crate) hidden: bool,
}
impl Assets {
#[must_use]
pub fn new(mount: &str, dir: impl Into<PathBuf>) -> Self {
Self {
mount: mount.trim_end_matches('/').to_owned(),
dir: dir.into(),
root: PathBuf::new(),
cache_control: "no-cache".into(),
index: None,
precompressed: true,
hidden: false,
}
}
#[must_use]
pub fn cache_control(mut self, value: &str) -> Self {
self.cache_control = value.into();
self
}
#[must_use]
pub fn index(mut self, name: &str) -> Self {
self.index = Some(name.into());
self
}
#[must_use]
pub fn precompressed(mut self, on: bool) -> Self {
self.precompressed = on;
self
}
#[must_use]
pub fn hidden_files(mut self, on: bool) -> Self {
self.hidden = on;
self
}
pub(crate) fn strip<'p>(&self, path: &'p str) -> Option<&'p str> {
let rest = path.strip_prefix(self.mount.as_str())?;
(rest.is_empty() || rest.starts_with('/')).then_some(rest)
}
}
fn is_device_name(seg: &str) -> bool {
let stem = seg
.split('.')
.next()
.unwrap_or(seg)
.trim_end()
.to_ascii_uppercase();
if matches!(
stem.as_str(),
"CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
) {
return true;
}
let Some(port) = stem
.strip_prefix("COM")
.or_else(|| stem.strip_prefix("LPT"))
else {
return false;
};
let mut chars = port.chars();
matches!(
(chars.next(), chars.next()),
(Some('0'..='9' | '¹' | '²' | '³'), None)
)
}
fn safe_segment(seg: &str, hidden: bool) -> bool {
!seg.is_empty()
&& (hidden || !seg.starts_with('.'))
&& !seg.contains([':', '\\', '/', '\0'])
&& !seg.ends_with(['.', ' '])
&& !is_device_name(seg)
}
pub(crate) struct Found {
path: PathBuf,
len: u64,
modified: Option<SystemTime>,
encoding: Option<&'static str>,
mime: &'static str,
vary: bool,
}
pub(crate) fn find(assets: &Assets, rel: &str, accept_encoding: Option<&[u8]>) -> Option<Found> {
let mut path = assets.root.clone();
for raw in rel.split('/').filter(|s| !s.is_empty()) {
let seg = url::decode(raw);
if !safe_segment(&seg, assets.hidden) {
return None;
}
path.push(seg.as_ref());
}
let mut meta = inside(&assets.root, &path, assets.hidden)?;
if meta.1.is_dir() {
let index = assets.index.as_deref()?;
path = meta.0.join(index);
meta = inside(&assets.root, &path, assets.hidden)?;
}
let (file, md) = meta;
if !md.is_file() {
return None;
}
let mime = mime_for(&file);
let mut found = Found {
len: md.len(),
modified: md.modified().ok(),
path: file,
encoding: None,
mime,
vary: false,
};
if assets.precompressed {
found.vary = true;
let offers = ["br", "gzip", "identity"];
let pick = accept_encoding.and_then(|v| parse_net::best_encoding(Some(v), &offers));
let ext = match pick {
Some(0) => Some(("br", "br")),
Some(1) => Some(("gzip", "gz")),
_ => None,
};
if let Some((coding, ext)) = ext {
let mut alt = found.path.clone().into_os_string();
alt.push(".");
alt.push(ext);
if let Some((p, m)) = inside(&assets.root, Path::new(&alt), assets.hidden) {
if m.is_file() {
found.path = p;
found.len = m.len();
found.modified = m.modified().ok();
found.encoding = Some(coding);
}
}
}
}
Some(found)
}
fn inside(root: &Path, path: &Path, hidden: bool) -> Option<(PathBuf, std::fs::Metadata)> {
let real = std::fs::canonicalize(path).ok()?;
let below = real.strip_prefix(root).ok()?;
for part in below.components() {
let std::path::Component::Normal(name) = part else {
return None;
};
if !name.to_str().is_some_and(|n| safe_segment(n, hidden)) {
return None;
}
}
let md = std::fs::metadata(&real).ok()?;
Some((real, md))
}
fn etag(found: &Found) -> String {
let nanos = found
.modified
.and_then(|m| m.duration_since(SystemTime::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos());
let coding = match found.encoding {
Some("br") => "-br",
Some(_) => "-gz",
None => "",
};
format!("\"{:x}-{:x}{coding}\"", found.len, nanos)
}
pub(crate) fn serve(
assets: &Assets,
found: &Found,
key: StreamKey,
req: &HttpRequest<'_>,
reply: &mut HttpReply,
) -> Option<Outcome> {
let tag = etag(found);
let opaque = &tag.as_bytes()[1..tag.len() - 1];
let current = EntityTag::strong(opaque).ok();
let last_modified = found
.modified
.and_then(|m| HttpDate::from_system_time(m).ok());
let head = |reply: &mut HttpReply, status: u16| {
reply
.status(status)
.header("etag", tag.as_bytes())
.header("cache-control", assets.cache_control.as_bytes())
.header("x-content-type-options", "nosniff");
if let Some(d) = last_modified {
reply.header("last-modified", d.format());
}
if found.vary {
reply.header("vary", "accept-encoding");
}
};
if let (Some(inm), Some(cur)) = (req.header("if-none-match"), current.as_ref()) {
if parse_net::if_none_match(inm, cur).unwrap_or(false) {
head(reply, 304);
return Some(Outcome::Done);
}
} else if let (Some(ims), Some(lm)) = (req.header("if-modified-since"), last_modified) {
if let Ok(since) = parse_net::http_date(ims) {
if lm <= since {
head(reply, 304);
return Some(Outcome::Done);
}
}
}
let mut range: Option<ByteRange> = None;
if req.method() == Method::Get {
if let Some(value) = req.header("range") {
let if_range_ok = if_range_holds(found, &tag, req);
if if_range_ok {
let mut out = [ByteRange { start: 0, end: 0 }];
match parse_net::byte_ranges(value, found.len, &mut out) {
Ok(RangeOutcome::Ranges(1)) => range = Some(out[0]),
Ok(RangeOutcome::Unsatisfiable) => {
head(reply, 416);
reply.header("content-range", format!("bytes */{}", found.len));
return Some(Outcome::Done);
}
_ => {}
}
}
}
}
let (status, start, len) = match range {
Some(r) => (206, r.start, r.end - r.start + 1),
None => (200, 0, found.len),
};
let inline = if len <= INLINE_LIMIT {
Some(read_at(&found.path, start, len as usize)?)
} else {
drop(File::open(&found.path).ok()?);
None
};
head(reply, status);
reply
.header("content-type", found.mime)
.header("accept-ranges", "bytes");
if let Some(c) = found.encoding {
reply.header("content-encoding", c);
}
if let Some(r) = range {
reply.header(
"content-range",
format!("bytes {}-{}/{}", r.start, r.end, found.len),
);
}
if let Some(bytes) = inline {
reply.body(&bytes);
return Some(Outcome::Done);
}
if req.method() == Method::Head {
reply.stream();
return Some(Outcome::Done);
}
begin(key, &tag);
let outcome = send_part(found, start, len, 0, reply);
if outcome != Outcome::More {
end(key);
}
Some(outcome)
}
fn send_part(found: &Found, start: u64, len: u64, sent: u64, reply: &mut HttpReply) -> Outcome {
if sent >= len {
return Outcome::Done;
}
let want = (len - sent).min(PART as u64) as usize;
let Some(bytes) = read_at(&found.path, start + sent, want) else {
return ABORT;
};
if bytes.len() != want {
return ABORT;
}
reply.stream().send(&bytes);
if sent + want as u64 >= len {
Outcome::Done
} else {
Outcome::More
}
}
fn read_at(path: &Path, start: u64, len: usize) -> Option<Vec<u8>> {
let mut f = File::open(path).ok()?;
if start > 0 {
f.seek(SeekFrom::Start(start)).ok()?;
}
let mut buf = Vec::with_capacity(len);
f.take(len as u64).read_to_end(&mut buf).ok()?;
Some(buf)
}
#[must_use]
pub fn mime_for(path: &Path) -> &'static str {
let ext = path
.extension()
.and_then(|e| e.to_str())
.map(str::to_ascii_lowercase)
.unwrap_or_default();
match ext.as_str() {
"html" | "htm" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" | "mjs" => "text/javascript; charset=utf-8",
"json" | "map" => "application/json",
"txt" => "text/plain; charset=utf-8",
"md" => "text/markdown; charset=utf-8",
"csv" => "text/csv; charset=utf-8",
"xml" => "application/xml",
"svg" => "image/svg+xml",
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"webp" => "image/webp",
"avif" => "image/avif",
"ico" => "image/x-icon",
"bmp" => "image/bmp",
"woff" => "font/woff",
"woff2" => "font/woff2",
"ttf" => "font/ttf",
"otf" => "font/otf",
"pdf" => "application/pdf",
"wasm" => "application/wasm",
"zip" => "application/zip",
"gz" => "application/gzip",
"mp4" => "video/mp4",
"webm" => "video/webm",
"mp3" => "audio/mpeg",
"ogg" => "audio/ogg",
"wav" => "audio/wav",
"webmanifest" => "application/manifest+json",
"rss" => "application/rss+xml",
"atom" => "application/atom+xml",
_ => "application/octet-stream",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unsafe_segments() {
for bad in [
".env",
".git",
"a:b",
"file.txt::$DATA",
"c:",
"x.",
"x ",
"CON",
"con.txt",
"Nul",
"COM1",
"lpt9.log",
"a\\b",
"",
] {
assert!(!safe_segment(bad, false), "{bad:?}");
}
for ok in [
"a.css",
"index.html",
"COM",
"COM10",
"console.js",
"a b.txt",
] {
assert!(safe_segment(ok, false), "{ok:?}");
}
assert!(safe_segment(".well-known", true));
}
#[test]
fn test_mime() {
assert_eq!(mime_for(Path::new("a/B.CSS")), "text/css; charset=utf-8");
assert_eq!(mime_for(Path::new("x")), "application/octet-stream");
assert_eq!(mime_for(Path::new("x.woff2")), "font/woff2");
}
#[test]
fn test_strip() {
let a = Assets::new("/static/", ".");
assert_eq!(a.strip("/static/a.css"), Some("/a.css"));
assert_eq!(a.strip("/static"), Some(""));
assert_eq!(a.strip("/statics/a"), None);
}
}