Medlar/crates/testserver/src/content.rs
2026-11-26 14:13:53 -06:00

344 lines
12 KiB
Rust

//! Deterministic bytes by seed, and the small hand-made fixtures (zip, tar, hashes).
use std::sync::Arc;
use md5::Md5;
use sha1::Sha1;
use sha2::{Digest, Sha256, Sha512};
fn splitmix(mut x: u64) -> u64 {
x = x.wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^ (x >> 31)
}
/// Fill `buf` with the bytes of virtual file `seed` starting at offset `start`.
pub fn fill(seed: u64, start: u64, buf: &mut [u8]) {
let mut pos = start;
let mut i = 0;
while i < buf.len() {
let block = pos / 8;
let word = splitmix(seed ^ block.wrapping_mul(0xA24B_AED4_963E_E407)).to_le_bytes();
let skip = (pos % 8) as usize;
let n = (8 - skip).min(buf.len() - i);
buf[i..i + n].copy_from_slice(&word[skip..skip + n]);
i += n;
pos += n as u64;
}
}
/// The bytes a client must get for `len` bytes of file `seed` from `start`.
pub fn expected(seed: u64, start: u64, len: usize) -> Vec<u8> {
let mut v = vec![0; len];
fill(seed, start, &mut v);
v
}
/// Where the bytes of a reply come from.
#[derive(Clone)]
pub enum Source {
Gen { seed: u64, len: u64 },
Bytes(Arc<Vec<u8>>),
}
impl Source {
pub fn bytes(v: impl Into<Vec<u8>>) -> Source {
Source::Bytes(Arc::new(v.into()))
}
#[allow(clippy::len_without_is_empty)]
pub fn len(&self) -> u64 {
match self {
Source::Gen { len, .. } => *len,
Source::Bytes(b) => b.len() as u64,
}
}
/// Read at `start`; `changed` returns the "other version" of the bytes.
pub fn read(&self, start: u64, buf: &mut [u8], changed: bool) {
match self {
Source::Gen { seed, .. } => fill(if changed { !seed } else { *seed }, start, buf),
Source::Bytes(b) => {
let s = start as usize;
buf.copy_from_slice(&b[s..s + buf.len()]);
if changed {
buf.iter_mut().for_each(|x| *x ^= 0xFF);
}
}
}
}
/// Same file with another version number (another seed, so other bytes).
pub fn versioned(&self, version: u32) -> Source {
match self {
Source::Gen { seed, len } if version > 0 => Source::Gen {
seed: seed ^ u64::from(version).wrapping_mul(0x1234_5678_9ABC_DEF1),
len: *len,
},
other => other.clone(),
}
}
}
/// `12`, `4k`, `3m`, `100g`, `2t` → bytes.
pub fn parse_len(s: &str) -> Option<u64> {
let (num, mul) = match s.as_bytes().last()? {
b'k' | b'K' => (&s[..s.len() - 1], 1 << 10),
b'm' | b'M' => (&s[..s.len() - 1], 1 << 20),
b'g' | b'G' => (&s[..s.len() - 1], 1 << 30),
b't' | b'T' => (&s[..s.len() - 1], 1u64 << 40),
_ => (s, 1),
};
num.parse::<u64>().ok()?.checked_mul(mul)
}
pub fn crc32(data: &[u8]) -> u32 {
let mut crc = !0u32;
for &b in data {
crc ^= u32::from(b);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & (!(crc & 1)).wrapping_add(1));
}
}
!crc
}
pub fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
pub fn base64(data: &[u8]) -> String {
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for c in data.chunks(3) {
let n = (u32::from(c[0]) << 16)
| (u32::from(*c.get(1).unwrap_or(&0)) << 8)
| u32::from(*c.get(2).unwrap_or(&0));
for i in 0..4 {
if i <= c.len() {
out.push(T[((n >> (18 - 6 * i)) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
pub fn md5_hex(data: &[u8]) -> String {
hex(&Md5::digest(data))
}
/// Hash of a virtual file (streamed, so a big length is fine but slow).
pub fn hash_source(algo: &str, src: &Source) -> Option<Vec<u8>> {
fn run<D: Digest>(src: &Source) -> Vec<u8> {
let mut d = D::new();
let mut buf = vec![0u8; 1 << 16];
let mut pos = 0;
while pos < src.len() {
let n = buf.len().min((src.len() - pos) as usize);
src.read(pos, &mut buf[..n], false);
d.update(&buf[..n]);
pos += n as u64;
}
d.finalize().to_vec()
}
Some(match algo {
"md5" => run::<Md5>(src),
"sha1" => run::<Sha1>(src),
"sha256" => run::<Sha256>(src),
"sha512" => run::<Sha512>(src),
_ => return None,
})
}
/// Files inside the fixed ZIP and TAR: (name, seed, length).
pub const ARCHIVE_FILES: [(&str, u64, usize); 3] =
[("one.bin", 11, 3000), ("two/inner.bin", 12, 5000), ("three.bin", 13, 40000)];
/// A ZIP with stored (uncompressed) entries; the central directory is at the end.
pub fn make_zip() -> Vec<u8> {
let mut out = Vec::new();
let mut central = Vec::new();
for (name, seed, len) in ARCHIVE_FILES {
let data = expected(seed, 0, len);
let crc = crc32(&data);
let offset = out.len() as u32;
let mut common = Vec::new();
common.extend(20u16.to_le_bytes()); // version needed
common.extend(0u16.to_le_bytes()); // flags
common.extend(0u16.to_le_bytes()); // stored
common.extend(0u16.to_le_bytes()); // time
common.extend(0x5821u16.to_le_bytes()); // date
common.extend(crc.to_le_bytes());
common.extend((len as u32).to_le_bytes());
common.extend((len as u32).to_le_bytes());
common.extend((name.len() as u16).to_le_bytes());
common.extend(0u16.to_le_bytes()); // extra
out.extend(0x0403_4b50u32.to_le_bytes());
out.extend(&common);
out.extend(name.as_bytes());
out.extend(&data);
central.extend(0x0201_4b50u32.to_le_bytes());
central.extend(20u16.to_le_bytes()); // made by
central.extend(&common);
central.extend(0u16.to_le_bytes()); // comment
central.extend(0u16.to_le_bytes()); // disk
central.extend(0u16.to_le_bytes()); // internal attrs
central.extend(0u32.to_le_bytes()); // external attrs
central.extend(offset.to_le_bytes());
central.extend(name.as_bytes());
}
let cd_offset = out.len() as u32;
out.extend(&central);
out.extend(0x0605_4b50u32.to_le_bytes());
out.extend([0u8; 4]); // disk numbers
out.extend((ARCHIVE_FILES.len() as u16).to_le_bytes());
out.extend((ARCHIVE_FILES.len() as u16).to_le_bytes());
out.extend((central.len() as u32).to_le_bytes());
out.extend(cd_offset.to_le_bytes());
out.extend(0u16.to_le_bytes());
out
}
/// A ustar TAR with the same files.
pub fn make_tar() -> Vec<u8> {
let mut out = Vec::new();
for (name, seed, len) in ARCHIVE_FILES {
let mut h = [0u8; 512];
h[..name.len()].copy_from_slice(name.as_bytes());
h[100..107].copy_from_slice(b"0000644");
h[108..115].copy_from_slice(b"0000000");
h[116..123].copy_from_slice(b"0000000");
h[124..135].copy_from_slice(format!("{len:011o}").as_bytes());
h[136..147].copy_from_slice(b"14000000000");
h[156] = b'0';
h[257..263].copy_from_slice(b"ustar\0");
h[263..265].copy_from_slice(b"00");
h[148..156].fill(b' ');
let sum: u32 = h.iter().map(|&b| u32::from(b)).sum();
h[148..155].copy_from_slice(format!("{sum:06o}\0").as_bytes());
out.extend(h);
out.extend(expected(seed, 0, len));
out.resize(out.len().div_ceil(512) * 512, 0);
}
out.extend([0u8; 1024]);
out
}
/// The open directory tree: (dir, entries). A trailing `/` marks a sub directory.
pub fn dir_entries(path: &str) -> Option<Vec<(&'static str, u64)>> {
match path {
"/dir/" => Some(vec![
("a.bin", 10_000),
("b.bin", 20_000),
("notes.txt", 12),
("sub/", 0),
("pack.zip", make_zip().len() as u64),
("pack.tar", make_tar().len() as u64),
]),
"/dir/sub/" => Some(vec![("deep.bin", 5_000), ("../", 0)]),
_ => None,
}
}
/// A file of the open directory tree.
pub fn dir_file(path: &str) -> Option<Source> {
Some(match path {
"/dir/a.bin" => Source::Gen { seed: 1, len: 10_000 },
"/dir/b.bin" => Source::Gen { seed: 2, len: 20_000 },
"/dir/notes.txt" => Source::bytes("hello notes\n"),
"/dir/sub/deep.bin" => Source::Gen { seed: 3, len: 5_000 },
"/dir/pack.zip" => Source::bytes(make_zip()),
"/dir/pack.tar" => Source::bytes(make_tar()),
_ => return None,
})
}
pub fn dir_listing(path: &str) -> Option<String> {
let entries = dir_entries(path)?;
let mut html = format!("<html><head><title>Index of {path}</title></head><body><h1>Index of {path}</h1><pre>\n");
for (name, size) in entries {
if name.ends_with('/') {
html.push_str(&format!("<a href=\"{name}\">{name}</a>\n"));
} else {
html.push_str(&format!("<a href=\"{name}\">{name}</a> {size}\n"));
}
}
html.push_str("</pre></body></html>\n");
Some(html)
}
/// The small site: (content type, body).
pub fn site_page(path: &str) -> Option<(&'static str, Source)> {
let html = |s: &str| Some(("text/html", Source::bytes(s)));
match path {
"/site/" | "/site/index.html" => html(
"<html><body><a href=\"page1.html\">one</a> <a href=\"a/page2.html\">two</a> \
<a href=\"/site/a/b/page3.html\">three</a> <a href=\"http://elsewhere.invalid/x.html\">out</a> \
<img src=\"img/logo.bin\"><link rel=\"stylesheet\" href=\"style.css\"></body></html>",
),
"/site/page1.html" => html("<html><body><a href=\"index.html\">home</a> <a href=\"a/page2.html\">two</a></body></html>"),
"/site/a/page2.html" => html("<html><body><a href=\"../index.html\">home</a> <a href=\"b/page3.html\">three</a></body></html>"),
"/site/a/b/page3.html" => html("<html><body><a href=\"../../index.html\">home</a> <a href=\"../../files/big.bin\">big</a></body></html>"),
"/site/style.css" => Some(("text/css", Source::bytes("body{color:#123}"))),
"/site/img/logo.bin" => Some(("application/octet-stream", Source::Gen { seed: 21, len: 2_000 })),
"/site/files/big.bin" => Some(("application/octet-stream", Source::Gen { seed: 22, len: 50_000 })),
_ => None,
}
}
/// The fixed file the metalink fixtures describe.
pub const META_SEED: u64 = 5;
pub const META_LEN: u64 = 50_000;
pub fn metalink4(base: &str) -> String {
let src = Source::Gen { seed: META_SEED, len: META_LEN };
let sha = hex(&hash_source("sha256", &src).unwrap());
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<metalink xmlns=\"urn:ietf:params:xml:ns:metalink\">\n\
<file name=\"meta.bin\"><size>{META_LEN}</size><hash type=\"sha-256\">{sha}</hash>\n\
<url priority=\"1\">{base}/data/{META_SEED}/{META_LEN}</url>\n\
<url priority=\"2\">{base}/data/{META_SEED}/{META_LEN}/mirror.bin</url></file></metalink>\n"
)
}
pub fn metalink3(base: &str) -> String {
let src = Source::Gen { seed: META_SEED, len: META_LEN };
let md5 = hex(&hash_source("md5", &src).unwrap());
let sha = hex(&hash_source("sha1", &src).unwrap());
format!(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<metalink version=\"3.0\" xmlns=\"http://www.metalinker.org/\"><files>\n\
<file name=\"meta.bin\"><size>{META_LEN}</size><verification><hash type=\"md5\">{md5}</hash><hash type=\"sha1\">{sha}</hash></verification>\n\
<resources><url type=\"http\" preference=\"100\">{base}/data/{META_SEED}/{META_LEN}</url>\n\
<url type=\"http\" preference=\"50\">{base}/data/{META_SEED}/{META_LEN}/mirror.bin</url></resources></file></files></metalink>\n"
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranges_match_whole() {
let whole = expected(7, 0, 1000);
assert_eq!(expected(7, 13, 100), whole[13..113]);
assert_eq!(expected(7, 999, 1), whole[999..]);
assert_ne!(expected(8, 0, 64), whole[..64]);
}
#[test]
fn lengths() {
assert_eq!(parse_len("100g"), Some(100 << 30));
assert_eq!(parse_len("12"), Some(12));
assert_eq!(parse_len("x"), None);
}
#[test]
fn known_values() {
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
assert_eq!(base64(b"Aladdin:open sesame"), "QWxhZGRpbjpvcGVuIHNlc2FtZQ==");
assert_eq!(md5_hex(b""), "d41d8cd98f00b204e9800998ecf8427e");
}
}