//! HTTP/1.1 by hand: full control of every byte, so faults can be exact. use std::io; use std::net::IpAddr; use std::sync::Arc; use std::time::Duration; use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader}; use tokio::time::{Instant, sleep, sleep_until}; use crate::content::{self, Source, base64, md5_hex}; use crate::faults::Faults; use crate::{Request, State}; const REALM: &str = "medlar-test"; const NONCE: &str = "dcd98b7102dd2f0e8b11d0f600bfb0c093"; const CHUNK: usize = 16 * 1024; /// What a route decided to answer, before faults and ranges. pub struct Reply { pub status: u16, pub headers: Vec<(String, String)>, pub source: Source, pub ctype: String, /// A file: ranges, ETag and Last-Modified apply. pub file: bool, /// Identity for the ETag. pub id: String, pub chunked: bool, pub no_length: bool, pub etag: bool, pub last_modified: bool, pub weak: bool, } impl Reply { pub fn text(status: u16, ctype: &str, body: impl Into>) -> Reply { Reply { status, headers: Vec::new(), source: Source::bytes(body), ctype: ctype.into(), file: false, id: String::new(), chunked: false, no_length: false, etag: true, last_modified: true, weak: false, } } fn file(source: Source, ctype: &str, id: String) -> Reply { Reply { file: true, id, source, ..Reply::text(200, ctype, Vec::new()) } } fn with(mut self, k: &str, v: impl Into) -> Reply { self.headers.push((k.into(), v.into())); self } } struct Ctx<'a> { req: &'a Request, query: Vec<(String, String)>, st: &'a State, scheme: &'a str, } impl Ctx<'_> { fn q(&self, k: &str) -> Option<&str> { self.query.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str()) } fn base(&self) -> String { format!("{}://{}", self.scheme, self.req.header("host").unwrap_or("127.0.0.1")) } } pub fn pct_decode(s: &str) -> String { let b = s.as_bytes(); let mut out = Vec::new(); let mut i = 0; while i < b.len() { let hex = (b[i] == b'%' && i + 2 < b.len()) .then(|| std::str::from_utf8(&b[i + 1..i + 3]).ok().and_then(|h| u8::from_str_radix(h, 16).ok())) .flatten(); if let Some(v) = hex { out.push(v); i += 3; } else { out.push(if b[i] == b'+' { b' ' } else { b[i] }); i += 1; } } String::from_utf8_lossy(&out).into_owned() } fn split_target(target: &str) -> (&str, Vec<(String, String)>) { let (path, q) = target.split_once('?').unwrap_or((target, "")); let query = q .split('&') .filter(|p| !p.is_empty()) .map(|p| { let (k, v) = p.split_once('=').unwrap_or((p, "")); (pct_decode(k), pct_decode(v)) }) .collect(); (path, query) } fn unauthorized(scheme: &str) -> Reply { Reply::text(401, "text/plain", "login needed").with("WWW-Authenticate", scheme) } fn kv_params(s: &str) -> Vec<(String, String)> { let mut out = Vec::new(); let (mut cur, mut quoted) = (String::new(), false); for c in s.chars().chain(std::iter::once(',')) { match c { '"' => quoted = !quoted, ',' if !quoted => { if let Some((k, v)) = cur.split_once('=') { out.push((k.trim().to_lowercase(), v.trim().to_string())); } cur.clear(); } _ => cur.push(c), } } out } fn digest_ok(auth: &str, method: &str, user: &str, pass: &str) -> bool { let Some(rest) = auth.strip_prefix("Digest ") else { return false }; let p = kv_params(rest); let get = |k: &str| p.iter().find(|(a, _)| a == k).map(|(_, v)| v.as_str()).unwrap_or(""); if get("username") != user || get("nonce") != NONCE || get("realm") != REALM { return false; } let ha1 = md5_hex(format!("{user}:{REALM}:{pass}").as_bytes()); let ha2 = md5_hex(format!("{method}:{}", get("uri")).as_bytes()); let want = if get("qop") == "auth" { md5_hex(format!("{ha1}:{NONCE}:{}:{}:auth:{ha2}", get("nc"), get("cnonce")).as_bytes()) } else { md5_hex(format!("{ha1}:{NONCE}:{ha2}").as_bytes()) }; get("response") == want } fn pct_encode(s: &str) -> String { s.bytes() .map(|b| if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { (b as char).to_string() } else { format!("%{b:02X}") }) .collect() } fn disposition(kind: &str, name: &str) -> Option { let star = format!("UTF-8''{}", pct_encode("naïve file.bin")); Some(match kind { "attachment" => format!("attachment; filename=\"{name}\""), "bare" => format!("attachment; filename={name}"), "star" => format!("attachment; filename*={star}"), "both" => format!("attachment; filename=\"fallback.bin\"; filename*={star}"), "inline" => format!("inline; filename=\"{name}\""), "evil" => "attachment; filename=\"../../etc/passwd\"".into(), "dotfile" => "attachment; filename=\".hidden.bin\"".into(), _ => return None, }) } fn content_type_of(name: &str) -> &'static str { match name.rsplit('.').next().unwrap_or("") { "m3u8" => "application/vnd.apple.mpegurl", "ts" => "video/mp2t", "mpd" => "application/dash+xml", "m4s" | "mp4" => "video/mp4", _ => "application/octet-stream", } } fn route(cx: &Ctx, path: &str) -> Reply { let segs: Vec<&str> = path.trim_start_matches('/').split('/').collect(); let rest = |n: usize| format!("/{}", segs[n..].join("/")); match segs[0] { "" => Reply::text(200, "text/plain", "medlar-testserver"), "data" if segs.len() >= 3 => { let (Ok(seed), Some(len)) = (segs[1].parse::(), content::parse_len(segs[2])) else { return Reply::text(400, "text/plain", "bad data path"); }; let name = segs.get(3).copied().filter(|n| !n.is_empty()).map(pct_decode).unwrap_or(format!("data-{seed}.bin")); let mut r = Reply::file(Source::Gen { seed, len }, "application/octet-stream", format!("{seed:x}-{len:x}")); if let Some(d) = cx.q("disp").and_then(|k| disposition(k, &name)) { r = r.with("Content-Disposition", d); } r.chunked = cx.q("chunked") == Some("1"); r.no_length = cx.q("nolen") == Some("1"); r.etag = cx.q("etag") != Some("0"); r.last_modified = cx.q("lm") != Some("0"); r.weak = cx.q("weak") == Some("1"); r } "redirect" if segs.len() >= 2 => { let code = cx.q("code").and_then(|c| c.parse().ok()).unwrap_or(302); let to = if segs[1] == "loop" { "/redirect/loop".to_string() } else { let n: u32 = segs[1].parse().unwrap_or(1); let target = cx.q("to").unwrap_or("/data/1/1000"); if n <= 1 { target.to_string() } else { format!("/redirect/{}?to={}&code={code}", n - 1, pct_encode(target)) } }; Reply::text(code, "text/plain", "moved").with("Location", to) } "status" if segs.len() >= 2 => { let code = segs[1].parse().unwrap_or(500); Reply::text(code, "text/plain", format!("status {code}")) } "basic" if segs.len() >= 4 => { let want = format!("Basic {}", base64(format!("{}:{}", segs[1], segs[2]).as_bytes())); if cx.req.header("authorization").map(str::trim) == Some(want.as_str()) { route(cx, &rest(3)) } else { unauthorized(&format!("Basic realm=\"{REALM}\"")) } } "digest" if segs.len() >= 4 => { let ok = cx.req.header("authorization").is_some_and(|a| digest_ok(a, &cx.req.method, segs[1], segs[2])); if ok { route(cx, &rest(3)) } else { unauthorized(&format!("Digest realm=\"{REALM}\", nonce=\"{NONCE}\", qop=\"auth\", algorithm=MD5")) } } "cookie" if segs.len() >= 3 => { if segs[2] == "login" { return Reply::text(200, "text/plain", "ok").with("Set-Cookie", format!("session={}; Path=/", segs[1])); } let want = format!("session={}", segs[1]); let has = cx.req.header("cookie").is_some_and(|c| c.split(';').any(|p| p.trim() == want)); if has { route(cx, &rest(2)) } else { Reply::text(403, "text/plain", "login needed") } } "referrer" if segs.len() >= 3 => { if cx.req.header("referer").is_some_and(|r| r.contains(segs[1])) { route(cx, &rest(2)) } else { Reply::text(403, "text/plain", "bad referrer") } } "dir" => { if let Some(html) = content::dir_listing(path) { Reply::text(200, "text/html", html) } else if let Some(src) = content::dir_file(path) { Reply::file(src, content_type_of(path), path.to_string()) } else { Reply::text(404, "text/plain", "not found") } } "site" => match content::site_page(path) { Some((ct, src)) => Reply::file(src, ct, path.to_string()), None => Reply::text(404, "text/plain", "not found"), }, "archive.zip" => Reply::file(Source::bytes(content::make_zip()), "application/zip", "zip".into()), "archive.tar" => Reply::file(Source::bytes(content::make_tar()), "application/x-tar", "tar".into()), "sum" if segs.len() == 4 => { let (Ok(seed), Some(len)) = (segs[2].parse::(), content::parse_len(segs[3])) else { return Reply::text(400, "text/plain", "bad sum path"); }; match content::hash_source(segs[1], &Source::Gen { seed, len }) { Some(h) => Reply::text(200, "text/plain", format!("{} data-{seed}.bin\n", content::hex(&h))), None => Reply::text(404, "text/plain", "unknown algorithm"), } } "meta" if segs.len() == 2 => match segs[1] { "v4.meta4" => Reply::text(200, "application/metalink4+xml", content::metalink4(&cx.base())), "v3.metalink" => Reply::text(200, "application/metalink+xml", content::metalink3(&cx.base())), // A file whose headers point at mirrors and carry a digest (metalink in HTTP headers). "header.bin" => { let src = Source::Gen { seed: content::META_SEED, len: content::META_LEN }; let digest = base64(&content::hash_source("sha256", &src).unwrap()); Reply::file(src, "application/octet-stream", "meta".into()) .with("Link", format!("<{}/data/{}/{}/mirror.bin>; rel=duplicate; pri=1", cx.base(), content::META_SEED, content::META_LEN)) .with("Digest", format!("SHA-256={digest}")) } _ => Reply::text(404, "text/plain", "not found"), }, "media" if segs.len() == 2 && !segs[1].contains("..") => { let dir = cx.st.media.lock().unwrap().clone(); match dir.and_then(|d| std::fs::read(d.join(segs[1])).ok()) { Some(b) => Reply::file(Source::bytes(b), content_type_of(segs[1]), format!("media-{}", segs[1])), None => Reply::text(404, "text/plain", "no media (call build_media first)"), } } _ => Reply::text(404, "text/plain", "not found"), } } fn status_text(code: u16) -> &'static str { match code { 200 => "OK", 206 => "Partial Content", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 407 => "Proxy Authentication Required", 410 => "Gone", 416 => "Range Not Satisfiable", 429 => "Too Many Requests", 500 => "Internal Server Error", 503 => "Service Unavailable", _ => "Status", } } fn http_date(version: u32) -> String { const DAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; let n = version % 27; format!("{}, {:02} Jan 2024 00:00:00 GMT", DAYS[n as usize % 7], 1 + n) } /// `Err` = unsatisfiable, `Ok(None)` = ignore the header. fn parse_range(h: &str, total: u64) -> Result, ()> { let Some(spec) = h.trim().strip_prefix("bytes=") else { return Ok(None) }; if spec.contains(',') { return Ok(None); } let Some((a, b)) = spec.split_once('-') else { return Ok(None) }; match (a.trim(), b.trim()) { ("", n) => { let n: u64 = n.parse().map_err(|_| ()).or(Ok(0))?; if n == 0 || total == 0 { Err(()) } else { Ok(Some((total.saturating_sub(n), total - 1))) } } (a, b) => { let Ok(a) = a.parse::() else { return Ok(None) }; let b = if b.is_empty() { u64::MAX } else { match b.parse::() { Ok(v) => v, Err(_) => return Ok(None) } }; if b < a { Ok(None) } else if a >= total { Err(()) } else { Ok(Some((a, b.min(total - 1)))) } } } } enum Pace { Done, Abort, } async fn pace_total(st: &State, n: u64, rate: u64) { let at = { let mut next = st.pacer.lock().await; let start = (*next).max(Instant::now()); *next = start + Duration::from_secs_f64(n as f64 / rate.max(1) as f64); start }; sleep_until(at).await; } struct BodyJob<'a> { src: &'a Source, start: u64, len: u64, chunked: bool, } async fn write_body( io: &mut W, job: BodyJob<'_>, f: &Faults, st: &State, reset: &socket2::Socket, sent_out: &mut u64, ) -> io::Result { let BodyJob { src, start, len, chunked } = job; let (mut sent, mut stalled) = (0u64, false); let mut buf = vec![0u8; CHUNK]; while sent < len { if f.cut_after == Some(sent) { io.flush().await?; return Ok(Pace::Abort); } if f.reset_after == Some(sent) { io.flush().await?; let _ = reset.set_linger(Some(Duration::ZERO)); return Err(io::Error::from(io::ErrorKind::ConnectionReset)); } if f.stall_after == Some(sent) && !stalled { stalled = true; io.flush().await?; sleep(Duration::from_millis(f.stall_ms.unwrap_or(3_600_000))).await; } let mut limit = len - sent; for t in [f.cut_after, f.reset_after, f.stall_after, f.change_after].into_iter().flatten() { if t > sent { limit = limit.min(t - sent); } } let mut max_chunk = CHUNK as u64; for r in [f.throttle_conn, f.throttle_total].into_iter().flatten() { max_chunk = max_chunk.min((r / 20).max(1)); } let n = limit.min(max_chunk) as usize; let changed = f.change_after.is_some_and(|c| sent >= c); src.read(start + sent, &mut buf[..n], changed); if chunked { io.write_all(format!("{n:x}\r\n").as_bytes()).await?; } io.write_all(&buf[..n]).await?; if chunked { io.write_all(b"\r\n").await?; } io.flush().await?; sent += n as u64; *sent_out = sent; if let Some(r) = f.throttle_conn { sleep(Duration::from_secs_f64(n as f64 / r.max(1) as f64)).await; } if let Some(r) = f.throttle_total { pace_total(st, n as u64, r).await; } } if chunked { io.write_all(b"0\r\n\r\n").await?; io.flush().await?; } Ok(Pace::Done) } async fn read_head(io: &mut BufReader) -> io::Result)>> { let mut line = String::new(); if io.read_line(&mut line).await? == 0 { return Ok(None); } let mut it = line.split_whitespace(); let (m, t, v) = (it.next().unwrap_or("").to_string(), it.next().unwrap_or("/").to_string(), it.next().unwrap_or("HTTP/1.1").to_string()); let mut headers = Vec::new(); loop { line.clear(); if io.read_line(&mut line).await? == 0 || headers.len() > 200 { return Err(io::ErrorKind::UnexpectedEof.into()); } let l = line.trim_end(); if l.is_empty() { break; } if let Some((k, v)) = l.split_once(':') { headers.push((k.trim().to_string(), v.trim().to_string())); } } Ok(Some((m, t, v, headers))) } /// One connection: requests until the client or a fault closes it. pub async fn serve_conn(stream: S, st: Arc, ip: IpAddr, conn: u64, reset: socket2::Socket, scheme: &'static str) -> io::Result<()> where S: AsyncRead + AsyncWrite + Unpin, { let mut io = BufReader::new(stream); loop { let Some((method, target, version, headers)) = read_head(&mut io).await? else { return Ok(()) }; let mut req = Request { id: 0, conn, method, target, headers, status: 0, sent: 0 }; let close_req = req.header("connection").is_some_and(|c| c.eq_ignore_ascii_case("close")) || version == "HTTP/1.0"; if let Some(n) = req.header("content-length").and_then(|v| v.parse::().ok()) { let mut sink = vec![0u8; 4096]; let mut left = n.min(1 << 20); while left > 0 { let k = io.read(&mut sink[..left.min(4096) as usize]).await?; if k == 0 { return Ok(()); } left -= k as u64; } } let idx = st.log_push(&mut req); let result = respond(&mut io, &st, &req, ip, &reset, scheme).await; match result { Ok((status, sent, keep)) => { st.log_done(idx, status, sent); if !keep || close_req { return Ok(()); } } Err(e) => { st.log_done(idx, 0, 0); return Err(e); } } } } async fn respond(io: &mut BufReader, st: &State, req: &Request, ip: IpAddr, reset: &socket2::Socket, scheme: &str) -> io::Result<(u16, u64, bool)> where S: AsyncRead + AsyncWrite + Unpin, { let (path, query) = split_target(&req.target); let path = path.to_string(); let mut f = st.faults_for(&path); if let Some(q) = Faults::from_query(req.target.split_once('?').map_or("", |x| x.1)) { f = f.merged(&q); } if let Some(ms) = f.latency_ms { sleep(Duration::from_millis(ms)).await; } let (req_no, age) = st.touch(&path); let cx = Ctx { req, query, st, scheme }; let mut reply = route(&cx, &path); let mut retry_after = None; let version = f.version_after_requests.map_or(0, |k| u32::from(req_no > k)); let expired = f.expire_requests.is_some_and(|n| req_no > n) || f.expire_secs.is_some_and(|s| age >= Duration::from_secs(s)); if expired { let code = f.expire_status.unwrap_or(403); reply = Reply::text(code, "text/plain", "link expired"); } else if f.max_conns.is_some_and(|m| st.conns_of(ip) > m) { reply = Reply::text(429, "text/plain", "too many connections"); retry_after = Some(1); } else if let Some(code) = f.status.filter(|_| f.status_count.is_none_or(|n| req_no <= n)) { let total = reply.source.len(); reply = Reply::text(code, "text/plain", format!("status {code}")); if code == 416 { reply = reply.with("Content-Range", format!("bytes */{total}")); } retry_after = f.retry_after; } if let Some(r) = retry_after.or(f.retry_after.filter(|_| reply.status == 429 || reply.status == 503)) { reply = reply.with("Retry-After", r.to_string()); } let src = reply.source.versioned(version); let total = src.len(); let head_only = req.method == "HEAD"; let mut status = reply.status; let mut headers = std::mem::take(&mut reply.headers); let etag = format!("{}\"{}-v{version}\"", if reply.weak { "W/" } else { "" }, reply.id); let modified = http_date(version); let mut range = None; let ranges_on = reply.file && !f.ignore_range && !reply.chunked && !reply.no_length; if reply.file && status == 200 { if reply.etag { headers.push(("ETag".into(), etag.clone())); } if reply.last_modified { headers.push(("Last-Modified".into(), modified.clone())); } if ranges_on { headers.push(("Accept-Ranges".into(), "bytes".into())); } let not_modified = req.header("if-none-match").is_some_and(|v| v == etag); if not_modified { status = 304; } else if ranges_on && let Some(h) = req.header("range") { let if_range_ok = req.header("if-range").is_none_or(|v| v == etag || v == modified); if if_range_ok { match parse_range(h, total) { Ok(Some(r)) => range = Some(r), Ok(None) => {} Err(()) => { status = 416; headers.push(("Content-Range".into(), format!("bytes */{total}"))); } } } } } let (start, len) = match range { Some((a, b)) => { status = 206; headers.push(("Content-Range".into(), format!("bytes {a}-{b}/{total}"))); (a, b - a + 1) } None if status == 200 || status == 206 || reply.status != 200 => (0, total), None => (0, 0), }; let no_body = head_only || status == 304 || (status == 416 && reply.file); let body_len = if no_body { 0 } else { len }; if f.gzip { headers.push(("Content-Encoding".into(), "gzip".into())); } if reply.status != 304 && status != 304 { headers.push(("Content-Type".into(), reply.ctype.clone())); } let mut keep = true; let chunked = reply.chunked && !no_body; if chunked { headers.push(("Transfer-Encoding".into(), "chunked".into())); } else if reply.no_length && !head_only { keep = false; } else { let declared = (len as i64 + f.wrong_length.unwrap_or(0)).max(0); if f.wrong_length.is_some() { keep = false; } let shown = if status == 416 && reply.file || status == 304 { 0 } else { declared }; headers.push(("Content-Length".into(), shown.to_string())); } if !keep { headers.push(("Connection".into(), "close".into())); } let mut head = format!("HTTP/1.1 {status} {}\r\n", status_text(status)); for (k, v) in &headers { head.push_str(&format!("{k}: {v}\r\n")); } head.push_str("\r\n"); io.write_all(head.as_bytes()).await?; io.flush().await?; let mut sent = 0; if body_len > 0 || (chunked && !head_only) { let job = BodyJob { src: &src, start, len: body_len, chunked }; match write_body(io, job, &f, st, reset, &mut sent).await? { Pace::Done => {} Pace::Abort => keep = false, } } Ok((status, sent, keep)) }