use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use anyhow::{Context, Result};
use axum::body::Body;
use axum::extract::{Json, Path as AxPath, State};
use axum::http::{HeaderMap, Method, StatusCode, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
#[derive(Debug, Clone)]
pub struct ServeOptions {
pub dir: PathBuf,
pub host: String,
pub port: u16,
}
pub fn router(root: PathBuf) -> axum::Router {
axum::Router::new()
.route("/", get(handle_root).head(handle_root))
.route("/{*path}", get(handle).head(handle))
.route("/link", axum::routing::post(handle_link))
.with_state(Arc::new(root))
}
async fn handle_link(
State(root): State<Arc<PathBuf>>,
body: axum::body::Bytes,
) -> impl IntoResponse {
match crate::hook::parse_link_body(&body) {
Ok(url) => match crate::hook::enqueue_link(&url, &root) {
Ok(id) => (
StatusCode::OK,
Json(serde_json::json!({"queued": id, "url": url})),
)
.into_response(),
Err(e) => (
StatusCode::INTERNAL_SERVER_ERROR,
format!("queue failed: {e:#}"),
)
.into_response(),
},
Err(e) => (StatusCode::BAD_REQUEST, format!("bad /link request: {e:#}")).into_response(),
}
}
pub async fn run(opts: ServeOptions) -> Result<()> {
let root = opts
.dir
.canonicalize()
.with_context(|| format!("cannot open {}", opts.dir.display()))?;
if !root.is_dir() {
anyhow::bail!("not a directory: {}", opts.dir.display());
}
let addr: SocketAddr = format!("{}:{}", opts.host, opts.port)
.parse()
.with_context(|| format!("bad listen address {}:{}", opts.host, opts.port))?;
let listener = tokio::net::TcpListener::bind(addr)
.await
.with_context(|| format!("cannot listen on {addr}"))?;
let local = listener.local_addr()?;
println!(
"xget serve: {} -> http://{local}/ (Ctrl-C stops)",
root.display()
);
axum::serve(listener, router(root))
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await
.context("serve failed")?;
Ok(())
}
async fn handle_root(
State(root): State<Arc<PathBuf>>,
method: Method,
headers: HeaderMap,
) -> Response {
handle_impl(&root, "", method, headers).await
}
async fn handle(
State(root): State<Arc<PathBuf>>,
AxPath(req_path): AxPath<String>,
method: Method,
headers: HeaderMap,
) -> Response {
handle_impl(&root, &req_path, method, headers).await
}
async fn handle_impl(root: &Path, req_path: &str, method: Method, headers: HeaderMap) -> Response {
let is_head = method == Method::HEAD;
match serve_path(root, req_path, headers.get(header::RANGE), is_head).await {
Ok(r) => r,
Err(status) => plain(status, &format!("{status}")),
}
}
async fn serve_path(
root: &Path,
req_path: &str,
range: Option<&axum::http::HeaderValue>,
is_head: bool,
) -> Result<Response, StatusCode> {
let decoded = percent_decode(req_path);
let mut full = root.to_path_buf();
for seg in decoded.split('/').filter(|s| !s.is_empty()) {
if seg == "." || seg == ".." {
continue;
}
full.push(seg);
}
let canon = full.canonicalize().map_err(|_| StatusCode::NOT_FOUND)?;
if !canon.starts_with(root) {
return Err(StatusCode::FORBIDDEN);
}
let meta = tokio::fs::metadata(&canon)
.await
.map_err(|_| StatusCode::NOT_FOUND)?;
if meta.is_dir() {
let body = listing_html(root, &canon, req_path);
return Ok(html(StatusCode::OK, body, is_head));
}
let len = meta.len();
let ctype = content_type(&canon);
match range.map(|v| v.to_str().unwrap_or("").to_string()) {
None => {
let stream = file_stream(&canon, 0, len)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
reply(StatusCode::OK, ctype, len, None, stream, is_head)
}
Some(spec) => {
let (from, to) = parse_range(&spec, len).ok_or(StatusCode::RANGE_NOT_SATISFIABLE)?;
if from >= len {
return Err(StatusCode::RANGE_NOT_SATISFIABLE);
}
let to = to.min(len - 1);
if from > to {
return Err(StatusCode::RANGE_NOT_SATISFIABLE);
}
let stream = file_stream(&canon, from, to - from + 1)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let cr = format!("bytes {from}-{to}/{len}");
reply(
StatusCode::PARTIAL_CONTENT,
ctype,
to - from + 1,
Some(cr),
stream,
is_head,
)
}
}
}
fn parse_range(spec: &str, len: u64) -> Option<(u64, u64)> {
let spec = spec.trim().strip_prefix("bytes=")?;
let spec = spec.split(',').next()?.trim();
if let Some(suf) = spec.strip_prefix('-') {
let n: u64 = suf.trim().parse().ok()?;
if n == 0 || len == 0 {
return None;
}
let n = n.min(len);
return Some((len - n, len - 1));
}
let (a, b) = spec.split_once('-')?;
let from: u64 = a.trim().parse().ok()?;
if b.trim().is_empty() {
return Some((from, len.saturating_sub(1)));
}
let to: u64 = b.trim().parse().ok()?;
Some((from, to))
}
async fn file_stream(
path: &Path,
offset: u64,
len: u64,
) -> std::io::Result<futures::stream::BoxStream<'static, std::io::Result<axum::body::Bytes>>> {
use futures::StreamExt;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
let mut f = tokio::fs::File::open(path).await?;
f.seek(std::io::SeekFrom::Start(offset)).await?;
let stream = futures::stream::unfold((f, len), |(mut f, mut left)| async move {
if left == 0 {
return None;
}
let mut buf = vec![0u8; 64 * 1024];
let want = left.min(buf.len() as u64) as usize;
match f.read(&mut buf[..want]).await {
Ok(0) => None,
Ok(n) => {
left -= n as u64;
Some((Ok(axum::body::Bytes::from(buf[..n].to_vec())), (f, left)))
}
Err(e) => Some((Err(e), (f, 0))),
}
});
Ok(stream.boxed())
}
fn reply(
status: StatusCode,
ctype: &str,
len: u64,
content_range: Option<String>,
stream: futures::stream::BoxStream<'static, std::io::Result<axum::body::Bytes>>,
is_head: bool,
) -> Result<Response, StatusCode> {
let mut b = Response::builder()
.status(status)
.header(header::ACCEPT_RANGES, "bytes")
.header(header::CONTENT_TYPE, ctype)
.header(header::CONTENT_LENGTH, len.to_string());
if let Some(cr) = content_range {
b = b.header(header::CONTENT_RANGE, cr);
}
let body = if is_head {
Body::empty()
} else {
Body::from_stream(stream)
};
b.body(body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
}
fn plain(status: StatusCode, msg: &str) -> Response {
Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
.body(Body::from(msg.to_string()))
.unwrap()
}
fn html(status: StatusCode, body: String, is_head: bool) -> Response {
let len = body.len();
let mut b = Response::builder()
.status(status)
.header(header::CONTENT_TYPE, "text/html; charset=utf-8")
.header(header::CONTENT_LENGTH, len.to_string());
if status == StatusCode::PARTIAL_CONTENT {
b = b.header(header::ACCEPT_RANGES, "bytes");
}
let bb = if is_head {
Body::empty()
} else {
Body::from(body)
};
b.body(bb).unwrap()
}
fn listing_html(root: &Path, dir: &Path, req_path: &str) -> String {
let mut out = format!(
"<!doctype html><html><head><meta charset=utf-8><title>/{req_path}</title></head><body><h1>/{req_path}</h1><ul>"
);
if !req_path.is_empty() {
out.push_str("<li><a href=\"..\">..</a></li>");
}
if let Ok(rd) = std::fs::read_dir(dir) {
let mut names: Vec<String> = rd
.flatten()
.map(|e| e.file_name().to_string_lossy().to_string())
.collect();
names.sort();
for n in names {
let full = dir.join(&n);
let disp = if full.is_dir() {
format!("{n}/")
} else {
n.clone()
};
let href = encode_segment(&n) + if full.is_dir() { "/" } else { "" };
out.push_str(&format!("<li><a href=\"{href}\">{disp}</a></li>"));
}
}
let _ = root;
out.push_str("</ul></body></html>");
out
}
fn content_type(p: &Path) -> &'static str {
match p
.extension()
.and_then(|e| e.to_str())
.map(|s| s.to_lowercase())
.as_deref()
{
Some("html" | "htm") => "text/html; charset=utf-8",
Some("txt" | "log" | "md") => "text/plain; charset=utf-8",
Some("json") => "application/json",
Some("xml" | "metalink" | "meta4") => "application/xml",
Some("iso") => "application/octet-stream",
Some("zip") => "application/zip",
Some("gz" | "tgz") => "application/gzip",
Some("xz") => "application/x-xz",
Some("zst") => "application/zstd",
Some("mp4") => "video/mp4",
Some("mkv") => "video/x-matroska",
Some("mp3") => "audio/mpeg",
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("pdf") => "application/pdf",
_ => "application/octet-stream",
}
}
fn percent_decode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let b = s.as_bytes();
let mut i = 0;
while i < b.len() {
if b[i] == b'%'
&& i + 2 < b.len()
&& let (Some(h), Some(l)) = (hex(b[i + 1]), hex(b[i + 2]))
{
out.push((h * 16 + l) as char);
i += 3;
continue;
}
out.push(b[i] as char);
i += 1;
}
out
}
fn hex(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn encode_segment(s: &str) -> String {
let mut out = String::new();
for b in s.as_bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(*b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
async fn start(root: PathBuf) -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move {
let _ = axum::serve(listener, router(root)).await;
});
format!("http://{addr}")
}
fn fixture(tag: &str) -> (tempfile_like::Guard, PathBuf) {
let dir = std::env::temp_dir().join(format!("xget-serve-{}-{tag}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("sub")).unwrap();
std::fs::write(
dir.join("hello.bin"),
(0..100_000u32).map(|i| (i % 251) as u8).collect::<Vec<_>>(),
)
.unwrap();
std::fs::write(dir.join("sub").join("note.txt"), b"hello serve").unwrap();
(tempfile_like::Guard(dir.clone()), dir)
}
mod tempfile_like {
pub struct Guard(pub std::path::PathBuf);
impl Drop for Guard {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[test]
fn range_parser_shapes() {
assert_eq!(parse_range("bytes=0-99", 1000), Some((0, 99)));
assert_eq!(parse_range("bytes=500-", 1000), Some((500, 999)));
assert_eq!(parse_range("bytes=-100", 1000), Some((900, 999)));
assert_eq!(parse_range("bytes=0-0", 1), Some((0, 0)));
assert_eq!(parse_range("bytes=999-", 1000), Some((999, 999)));
assert!(parse_range("items=0-1", 100).is_none());
assert!(parse_range("bytes=-0", 100).is_none());
}
#[tokio::test]
async fn serves_files_head_and_ranges() {
let (_g, dir) = fixture("ranges");
let base = start(dir.clone()).await;
let client = reqwest::Client::new();
let full = client
.get(format!("{base}/hello.bin"))
.send()
.await
.unwrap();
assert_eq!(full.status(), 200);
assert_eq!(full.headers()["accept-ranges"], "bytes");
let body = full.bytes().await.unwrap();
assert_eq!(body, std::fs::read(dir.join("hello.bin")).unwrap());
let part = client
.get(format!("{base}/hello.bin"))
.header("Range", "bytes=10-99")
.send()
.await
.unwrap();
assert_eq!(part.status(), 206);
assert_eq!(part.headers()["content-range"], "bytes 10-99/100000");
assert_eq!(&part.bytes().await.unwrap()[..], &body[10..100]);
let suf = client
.get(format!("{base}/hello.bin"))
.header("Range", "bytes=-10")
.send()
.await
.unwrap();
assert_eq!(suf.status(), 206);
assert_eq!(suf.bytes().await.unwrap().len(), 10);
let head = client
.head(format!("{base}/hello.bin"))
.send()
.await
.unwrap();
assert_eq!(head.headers()["content-length"], "100000");
assert!(head.bytes().await.unwrap().is_empty());
let bad = client
.get(format!("{base}/hello.bin"))
.header("Range", "bytes=999999-")
.send()
.await
.unwrap();
assert_eq!(bad.status(), 416);
assert_eq!(
client
.get(format!("{base}/nope.bin"))
.send()
.await
.unwrap()
.status(),
404
);
let trav = client
.get(format!("{base}/..%2f..%2fetc%2fpasswd"))
.send()
.await
.unwrap();
assert!(
trav.status() == 404 || trav.status() == 403,
"traversal zablokowany: {}",
trav.status()
);
let list = client
.get(format!("{base}/sub"))
.send()
.await
.unwrap()
.text()
.await
.unwrap();
assert!(list.contains("note.txt"), "listing ma <a href>: {list}");
let root = client.get(format!("{base}/")).send().await.unwrap();
assert_eq!(root.status(), 200);
let root = root.text().await.unwrap();
assert!(root.contains("hello.bin"), "root listing: {root}");
assert!(
root.contains("sub/"),
"root listing z podkatalogiem: {root}"
);
}
#[tokio::test]
async fn downloader_probes_work_against_serve() {
use crate::engine::Input;
let (_g, dir) = fixture("probes");
let base = start(dir).await;
let input = crate::inputs::HttpInput::new(format!("{base}/hello.bin"));
assert_eq!(input.size().await.unwrap(), Some(100_000));
let chunk = input.read_range(1000, 4096).await.unwrap();
let want: Vec<u8> = (1000..5096u32).map(|i| (i % 251) as u8).collect();
assert_eq!(chunk, want);
}
}