S037: security fixes (busy answer over 16 connections, DASH period cap and overflow), fuzz of parsers, soak and load tests
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
c8e36dd352
commit
aad1b92d24
12 changed files with 514 additions and 6 deletions
33
crates/core/src/connector/fuzz.rs
Normal file
33
crates/core/src/connector/fuzz.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
//! Fuzz of the port's request reader and answer (S037): no panic, a web page never gets a link in.
|
||||
|
||||
use super::*;
|
||||
use crate::fuzz::run;
|
||||
|
||||
fn request(extra: &str, body: &str) -> Vec<u8> {
|
||||
format!("POST / HTTP/1.1\r\nHost: 127.0.0.1:17616\r\nContent-Type: application/json\r\n{extra}Content-Length: {}\r\n\r\n{body}", body.len()).into_bytes()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn requests() {
|
||||
let one = request("", r#"{"url":"https://h/a.zip","filename":"../.x","cookies":"k=v","headers":{"X-A":"1","Host":"evil"}}"#);
|
||||
let list = request("", r#"[{"url":"ftp://h/b"},{"url":"javascript:alert(1)"},{"url":""},{}]"#);
|
||||
let web = request("Origin: https://evil.test\r\n", r#"{"url":"https://h/a.zip"}"#);
|
||||
let ping = b"GET / HTTP/1.1\r\nHost: localhost:17616\r\n\r\n".to_vec();
|
||||
let mut inputs = vec![];
|
||||
run(&[&one, &list, &web, &ping], |b| inputs.push(b.to_vec()));
|
||||
for b in inputs {
|
||||
let Ok(Ok(req)) = tokio::time::timeout(Duration::from_secs(1), wire::read(&mut &b[..])).await else { continue };
|
||||
let (code, _, entry) = answer(&req, 17616);
|
||||
let from_web = req.header("origin").is_some() || req.header("sec-fetch-mode") == Some("cors");
|
||||
if from_web {
|
||||
assert_ne!(code, 200, "{}", String::from_utf8_lossy(&b));
|
||||
}
|
||||
if let Some((_, _, taken)) = entry {
|
||||
for link in taken {
|
||||
if let Some(name) = &link.name {
|
||||
crate::fuzz::assert_safe_name(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -257,7 +257,11 @@ async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc<Shared>, link
|
|||
tokio::select! {
|
||||
changed = want.changed() => if changed.is_err() { return } else { break },
|
||||
accepted = listener.accept() => if let Ok((stream, peer)) = accepted {
|
||||
let Ok(permit) = gate.connections.clone().try_acquire_owned() else { continue };
|
||||
let Ok(permit) = gate.connections.clone().try_acquire_owned() else {
|
||||
// Full: say so at once instead of closing without a word (S037).
|
||||
tokio::spawn(busy(stream));
|
||||
continue;
|
||||
};
|
||||
let (shared, links, gate) = (shared.clone(), links.clone(), gate.clone());
|
||||
tokio::spawn(async move {
|
||||
handle(stream, peer, port, &shared, &links, &gate).await;
|
||||
|
|
@ -284,6 +288,16 @@ async fn serve(mut want: watch::Receiver<(bool, u16)>, shared: Arc<Shared>, link
|
|||
}
|
||||
}
|
||||
|
||||
/// Answer 429 to a connection over the limit, without reading it; the client sees "busy", not a reset.
|
||||
async fn busy(mut stream: TcpStream) {
|
||||
let answer = wire::answer(Refused::Busy.status(), &serde_json::json!({ "error": Refused::Busy.code() }));
|
||||
let _ = tokio::time::timeout(Duration::from_secs(1), async {
|
||||
let _ = stream.write_all(&answer).await;
|
||||
let _ = stream.shutdown().await;
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
struct Gate {
|
||||
connections: Arc<Semaphore>,
|
||||
tokens: Mutex<(f64, Instant)>,
|
||||
|
|
@ -396,3 +410,6 @@ fn guard(request: &wire::Request, port: u16) -> Result<(), Refused> {
|
|||
_ => Err(Refused::Method),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod fuzz;
|
||||
|
|
|
|||
113
crates/core/src/fuzz.rs
Normal file
113
crates/core/src/fuzz.rs
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
//! Short fuzz runs of the parsers (S037): seeds mutated at random, no panic, and the safety rules hold.
|
||||
//! Fixed seeds of the random source, so a failure repeats; `MEDLAR_FUZZ=n` runs more rounds.
|
||||
|
||||
use crate::{batch::Batch, http::name, listing, metalink, redact};
|
||||
|
||||
pub(crate) fn rounds() -> usize {
|
||||
std::env::var("MEDLAR_FUZZ").ok().and_then(|n| n.parse().ok()).unwrap_or(2000)
|
||||
}
|
||||
|
||||
const PIECES: &[&[u8]] = &[
|
||||
b"\0", b"\r\n", b"\n", b"/", b"\\", b"..", b"%2F", b"%00", b"\"", b"'", b";", b"=", b"*", b"<", b">", b"&", b"[", b"]",
|
||||
b"{", b"}", b"-", b":", b"99999999999999999999", b"18446744073709551615", b"-1", b"0", b"\xff\xfe", b"\xe2\x80\xae",
|
||||
b"\xc3", b"UTF-8''", b"<![CDATA[", b"]]>", b"<!--", b"#EXT", b"$Number$", b"$Time$", b"PT9999999H", b"r=\"-1\"",
|
||||
];
|
||||
|
||||
/// The seed with a few random cuts, copies and inserts.
|
||||
pub(crate) fn mutate(rng: &mut fastrand::Rng, seed: &[u8]) -> Vec<u8> {
|
||||
let mut out = seed.to_vec();
|
||||
for _ in 0..rng.usize(1..8) {
|
||||
let at = rng.usize(0..=out.len());
|
||||
match rng.u8(0..5) {
|
||||
0 => out.splice(at..at, PIECES[rng.usize(0..PIECES.len())].iter().copied()).for_each(drop),
|
||||
1 => {
|
||||
let end = (at + rng.usize(0..32)).min(out.len());
|
||||
out.drain(at..end);
|
||||
}
|
||||
2 => {
|
||||
let end = (at + rng.usize(0..64)).min(out.len());
|
||||
let copy = out[at..end].to_vec();
|
||||
out.splice(at..at, copy).for_each(drop);
|
||||
}
|
||||
3 => out.insert(at, rng.u8(..)),
|
||||
_ => {
|
||||
if at < out.len() {
|
||||
out[at] = rng.u8(..);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub(crate) fn run(seeds: &[&[u8]], mut check: impl FnMut(&[u8])) {
|
||||
let mut rng = fastrand::Rng::with_seed(37);
|
||||
for seed in seeds {
|
||||
check(seed);
|
||||
}
|
||||
for _ in 0..rounds() {
|
||||
let seed = seeds[rng.usize(0..seeds.len())];
|
||||
check(&mutate(&mut rng, seed));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn assert_safe_name(n: &str) {
|
||||
assert!(!n.is_empty() && n.len() <= 255, "{n:?}");
|
||||
assert!(!n.contains(['/', '\\']) && !n.starts_with('.') && !n.chars().any(char::is_control), "{n:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names() {
|
||||
run(&[b"a.zip", b"../../etc/passwd", b"..\\..\\x.exe", b".bashrc", b"CON.txt", b"\xe2\x80\xaegpj.exe", &[b'a'; 400]], |b| {
|
||||
if let Some(n) = name::safe(&String::from_utf8_lossy(b)) {
|
||||
assert_safe_name(&n);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn metalinks() {
|
||||
const V4: &[u8] = br#"<?xml version="1.0"?><metalink xmlns="urn:ietf:params:xml:ns:metalink"><file name="a/../b.iso"><size>10</size>
|
||||
<hash type="sha-256">00</hash><url priority="1">https://h/b.iso</url><url>ftp://h/b.iso</url><pieces length="4" type="sha-1"><hash>aa</hash></pieces></file></metalink>"#;
|
||||
const V3: &[u8] = br#"<metalink version="3.0" xmlns="http://www.metalinker.org/"><files><file name="c.zip"><verification><hash type="md5">00</hash></verification>
|
||||
<resources><url type="http" preference="100">http://h/c.zip</url></resources></file></files></metalink>"#;
|
||||
run(&[V4, V3, b"<!DOCTYPE x [<!ENTITY a \"aaaa\">]><metalink>&a;&a;</metalink>"], |b| {
|
||||
let _ = metalink::parse(b);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listings() {
|
||||
const MLSD: &[u8] = b"type=file;size=10;modify=20260101120000; a.zip\r\ntype=dir;modify=20260101120000; sub\r\ntype=cdir; .\r\n";
|
||||
const UNIX: &[u8] = b"-rw-r--r-- 1 u g 1234 Jan 01 12:00 a b.zip\ndrwxr-xr-x 2 u g 4096 2025 sub\nlrwxrwxrwx 1 u g 3 Jan 1 2025 l -> ../x\n";
|
||||
const DOS: &[u8] = b"01-01-26 12:00PM <DIR> sub\r\n01-01-26 12:00PM 1234 a.zip\r\n";
|
||||
let now = chrono::Utc::now();
|
||||
run(&[MLSD, UNIX, DOS], |b| {
|
||||
let _ = listing::mlsd(b);
|
||||
let _ = listing::plain(b, now);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns() {
|
||||
run(
|
||||
&[b"https://h/[001-120].jpg", b"https://h/{a,b,c}/[a-f]/[0-100:10]", b"https://h/[2026-01-30..2026-02-02].log", b"https://h/[0-99999999999999999]/[0-9999999]"],
|
||||
|b| {
|
||||
let text = String::from_utf8_lossy(b);
|
||||
for patterns in [true, false] {
|
||||
let batch = Batch::of(&text, patterns);
|
||||
assert!(batch.links.len() <= crate::batch::MOST && batch.total >= batch.links.len() as u64);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redaction() {
|
||||
run(&[b"https://user:pass@h/a?token=secret#x", b"Cookie: k=v\nAuthorization: Basic abc"], |b| {
|
||||
let text = String::from_utf8_lossy(b);
|
||||
let _ = redact::text(&text);
|
||||
let _ = redact::url(&text);
|
||||
});
|
||||
assert!(!redact::url("https://user:hunter2@h/a?sig=hunter3").contains("hunter"));
|
||||
}
|
||||
40
crates/core/src/http/fuzz.rs
Normal file
40
crates/core/src/http/fuzz.rs
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
//! Fuzz of reply headers: names from Content-Disposition, ranges, Retry-After, encoding (S037).
|
||||
|
||||
use super::*;
|
||||
use crate::fuzz::{assert_safe_name, run};
|
||||
|
||||
fn map(name: HeaderName, value: &[u8]) -> Option<HeaderMap> {
|
||||
Some(HeaderMap::from_iter([(name, HeaderValue::from_bytes(value).ok()?)]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispositions() {
|
||||
let source = Source::new("https://h/dir/").unwrap();
|
||||
let last = source.url.clone();
|
||||
run(
|
||||
&[b"attachment; filename=\"a b.zip\"", b"attachment; filename*=UTF-8''..%2F..%2Fx.sh", b"inline; filename=\"/etc/passwd\"", b"attachment; filename*=iso-8859-1'en'%E9.txt"],
|
||||
|b| {
|
||||
let Some(headers) = map(header::CONTENT_DISPOSITION, b) else { return };
|
||||
assert_safe_name(&name::pick(&source, &last, &headers));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_and_waits() {
|
||||
run(&[b"bytes 0-0/10", b"bytes 5-9/*", b"bytes */10", b"18446744073709551615", b"Sun, 06 Nov 1994 08:49:37 GMT", b"gzip, identity"], |b| {
|
||||
if let Some(headers) = map(header::CONTENT_RANGE, b) {
|
||||
if let Some(r) = ContentRange::of(&headers) {
|
||||
assert!(r.first <= r.last && r.total.is_none_or(|t| r.last < t), "{r:?}");
|
||||
}
|
||||
let _ = unsatisfied_total(&headers);
|
||||
}
|
||||
for name in [header::RETRY_AFTER, header::CONTENT_LENGTH, header::CONTENT_ENCODING] {
|
||||
if let Some(headers) = map(name, b) {
|
||||
let _ = retry_after(&headers);
|
||||
let _ = content_length(&headers);
|
||||
let _ = check_encoding(&headers, &Url::parse("https://h/a").unwrap());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -7,6 +7,8 @@ pub(crate) mod name;
|
|||
mod parts;
|
||||
mod piece;
|
||||
mod probe;
|
||||
#[cfg(test)]
|
||||
mod fuzz;
|
||||
|
||||
pub use download::{Options, Shared, download};
|
||||
pub(crate) use download::is_page;
|
||||
|
|
|
|||
|
|
@ -48,4 +48,7 @@ mod transport;
|
|||
pub mod verify;
|
||||
pub mod ytdlp;
|
||||
|
||||
#[cfg(test)]
|
||||
mod fuzz;
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
|
|
|||
|
|
@ -342,6 +342,19 @@ fn set_aside(path: &Path) -> Option<PathBuf> {
|
|||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// S024 check 5: the size rules of "add without asking".
|
||||
#[test]
|
||||
fn auto_ok_sizes() {
|
||||
let mb = 1024 * 1024;
|
||||
let mut s = Settings { add_without_asking: true, auto_types: vec![], auto_min_mb: 10, auto_max_mb: 100, ..Settings::default() };
|
||||
let got: Vec<bool> = [Some(5 * mb), Some(50 * mb), Some(500 * mb), None].into_iter().map(|n| s.auto_ok("a.zip", n)).collect();
|
||||
assert_eq!(got, [false, true, false, true]);
|
||||
s.auto_types = vec!["zip".into()];
|
||||
assert!(s.auto_ok("A.ZIP", None) && !s.auto_ok("a.iso", None) && !s.auto_ok("zip", None));
|
||||
s.add_without_asking = false;
|
||||
assert!(!s.auto_ok("a.zip", Some(50 * mb)));
|
||||
}
|
||||
|
||||
fn file(text: &str) -> (tempfile::TempDir, PathBuf) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("settings.json");
|
||||
|
|
|
|||
|
|
@ -289,9 +289,10 @@ impl Manifest {
|
|||
return Ok(media);
|
||||
}
|
||||
media.segments.extend(r.expand(period, stretch, live.then(|| self.window(period, now)).flatten())?);
|
||||
}
|
||||
if media.segments.len() as u64 > MOST {
|
||||
return Err(odd("too many"));
|
||||
// Checked per period: many periods of MOST each would fill the memory first (S037).
|
||||
if media.segments.len() as u64 > MOST {
|
||||
return Err(odd("too many"));
|
||||
}
|
||||
}
|
||||
if !live {
|
||||
// The place in the list is what stays.
|
||||
|
|
@ -348,11 +349,17 @@ impl Rendition {
|
|||
Some((from, to)) => ((from / long).ceil().max(0.0) as u64, (to / long).floor().max(0.0) as u64),
|
||||
None => (0, (period.length.ok_or_else(|| odd("period"))? / long - 1e-6).ceil().max(0.0) as u64),
|
||||
};
|
||||
let to = end_number.map_or(to, |e| to.min((e + 1).saturating_sub(*number)));
|
||||
let to = end_number.map_or(to, |e| to.min(e.saturating_add(1).saturating_sub(*number)));
|
||||
if to.saturating_sub(from) > MOST {
|
||||
return Err(odd("too many"));
|
||||
}
|
||||
(from..to).map(|i| Ok(segment(i, i + 1, long, at(number + i, offset + i * each)?, &init))).collect()
|
||||
(from..to)
|
||||
.map(|i| {
|
||||
let n = number.checked_add(i).ok_or_else(|| odd("timeline"))?;
|
||||
let t = i.checked_mul(*each).and_then(|x| x.checked_add(*offset)).ok_or_else(|| odd("timeline"))?;
|
||||
Ok(segment(i, i + 1, long, at(n, t)?, &init))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
50
crates/core/src/stream/fuzz.rs
Normal file
50
crates/core/src/stream/fuzz.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
//! Fuzz of HLS lists and DASH manifests (S037): no panic, no endless list.
|
||||
|
||||
use crate::fuzz::run;
|
||||
use url::Url;
|
||||
|
||||
const MASTER: &[u8] = b"#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=900,RESOLUTION=1920x1080,AUDIO=\"a\"\nhigh.m3u8\n#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID=\"a\",URI=\"s.m3u8\",LANGUAGE=\"de\"\n";
|
||||
const MEDIA: &[u8] = b"#EXTM3U\n#EXT-X-TARGETDURATION:4\n#EXT-X-MEDIA-SEQUENCE:7\n#EXT-X-MAP:URI=\"i.mp4\",BYTERANGE=\"100@0\"\n#EXTINF:4.0,\na.ts\n#EXT-X-BYTERANGE:500@100\n#EXTINF:4,\nb.ts\n#EXT-X-ENDLIST\n";
|
||||
const MPD: &[u8] = br#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT9.5S"><Period>
|
||||
<AdaptationSet contentType="video" mimeType="video/mp4"><SegmentTemplate timescale="1000" duration="4000" startNumber="1" initialization="$RepresentationID$/i.mp4" media="$RepresentationID$/$Number%03d$.m4s"/>
|
||||
<Representation id="low" bandwidth="100" width="640" height="360"/></AdaptationSet>
|
||||
<AdaptationSet mimeType="audio/mp4" lang="de"><Representation id="s" bandwidth="64"><BaseURL>sound/</BaseURL>
|
||||
<SegmentTemplate timescale="10" media="$Time$.m4s"><SegmentTimeline><S t="5" d="40" r="1"/><S d="15" r="-1"/></SegmentTimeline></SegmentTemplate></Representation></AdaptationSet></Period></MPD>"#;
|
||||
|
||||
fn base() -> Url {
|
||||
Url::parse("https://h/a/m").unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hls_lists() {
|
||||
run(&[MASTER, MEDIA], |b| {
|
||||
let _ = super::hls::parse(&String::from_utf8_lossy(b), &base());
|
||||
});
|
||||
}
|
||||
|
||||
fn all_media(text: &str) {
|
||||
if let Ok(m) = super::dash::parse(text, &base()) {
|
||||
for v in m.found.videos.iter().chain(&m.found.audios) {
|
||||
if let Ok(media) = m.media(v, 1.0e9) {
|
||||
assert!(media.segments.len() <= 200_000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_manifests() {
|
||||
run(&[MPD], |b| all_media(&String::from_utf8_lossy(b)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dash_many_periods_refused() {
|
||||
// 50 periods of 150,000 numbered segments each: refused before it fills the memory.
|
||||
let period = r#"<Period duration="PT150000S"><AdaptationSet mimeType="video/mp4"><SegmentTemplate timescale="1" duration="1" media="$Number$.m4s"/><Representation id="v" bandwidth="1"/></AdaptationSet></Period>"#;
|
||||
let text = format!(r#"<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT7500000S">{}</MPD>"#, period.repeat(50));
|
||||
let m = super::dash::parse(&text, &base()).unwrap();
|
||||
assert!(m.media(&m.found.videos[0], 0.0).is_err());
|
||||
let huge = MPD.to_vec();
|
||||
let huge = String::from_utf8(huge).unwrap().replace("startNumber=\"1\"", "startNumber=\"18446744073709551615\"");
|
||||
all_media(&huge);
|
||||
}
|
||||
|
|
@ -10,6 +10,8 @@ mod join;
|
|||
mod list;
|
||||
mod record;
|
||||
mod tape;
|
||||
#[cfg(test)]
|
||||
mod fuzz;
|
||||
|
||||
pub use ffmpeg::Tools;
|
||||
pub use list::{Choice, Found, Kind, Pick, Variant};
|
||||
|
|
|
|||
|
|
@ -285,6 +285,19 @@ async fn connector_flood_15() {
|
|||
assert!(ok >= 25 && busy >= 5 && ok + busy == 40, "ok {ok} busy {busy} {codes:?}");
|
||||
}
|
||||
|
||||
/// S037: connections over the limit of 16 at once get 429 "busy", not a silent close.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn connector_over_16_connections_busy() {
|
||||
let (_c, _rx, p) = start().await;
|
||||
// 16 silent connections hold every place until the 5 s read limit.
|
||||
let held: Vec<TcpStream> = (0..16).map(|_| TcpStream::connect(("127.0.0.1", p)).unwrap()).collect();
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
let r = tokio::task::spawn_blocking(move || send(p, format!("GET / HTTP/1.1\r\nHost: 127.0.0.1:{p}\r\n\r\n").as_bytes())).await.unwrap();
|
||||
assert_eq!(code(&r), 429, "{r}");
|
||||
assert!(r.contains("busy"), "{r}");
|
||||
drop(held);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn connector_port_16_17() {
|
||||
let hold = std::net::TcpListener::bind(("127.0.0.1", 0)).unwrap();
|
||||
|
|
|
|||
215
crates/core/tests/whole.rs
Normal file
215
crates/core/tests/whole.rs
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
//! S037: the whole engine under load. All `#[ignore]`: run one by name, never at the same time as a build.
|
||||
//! - `soak`: random faults, pauses, restarts and limit changes for `MEDLAR_SOAK_SECS` (default 1200); every file checked.
|
||||
//! - `ten_thousand`: memory and times with 10,000 tasks in the list.
|
||||
//! - `loopback_speed`: one large file from the local test server, Medlar against curl.
|
||||
|
||||
use medlar_core::adapt::Timing;
|
||||
use medlar_core::host::{Caps, Hosts};
|
||||
use medlar_core::http::{ClientOptions, Options, Shared, client};
|
||||
use medlar_core::manager::*;
|
||||
use medlar_core::model::*;
|
||||
use medlar_core::segment::Rules;
|
||||
use medlar_core::settings::Limits;
|
||||
use medlar_core::store::Store;
|
||||
use medlar_testserver::{Faults, TestServer, expected};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::time::sleep;
|
||||
|
||||
fn ms(n: u64) -> Duration {
|
||||
Duration::from_millis(n)
|
||||
}
|
||||
|
||||
const LIMITS: Limits = Limits { speed: 0, max_active: 4, max_connections: 32, parts_per_download: 6, connections_per_host: 16 };
|
||||
|
||||
fn config(dir: &Path, limits: Limits) -> Config {
|
||||
let store = Arc::new(Store::open(&dir.join("medlar.db")).unwrap());
|
||||
let client = client(&ClientOptions { idle_timeout: ms(1500), ..ClientOptions::default() }).unwrap();
|
||||
let hosts = Hosts::new(Caps { burst: 1000, per_second: 1000.0, ..Caps::default() });
|
||||
let options = Options {
|
||||
rules: Rules { min: 64 * 1024, align: 4096, min_time: ms(50) },
|
||||
timing: Timing { settle: ms(200), window: ms(600), hold: ms(2000), refused: ms(3000) },
|
||||
tick: ms(25),
|
||||
stall: ms(1000),
|
||||
patience: ms(500),
|
||||
tries: 4,
|
||||
backoff: ms(20),
|
||||
max_wait: ms(2000),
|
||||
checkpoint: ms(50),
|
||||
};
|
||||
let mut config = Config::new(Shared { client, store, hosts }, limits);
|
||||
(config.options, config.bin, config.tick) = (options, Bin::at(dir.join("Trash")), ms(20));
|
||||
config
|
||||
}
|
||||
|
||||
fn rss_kb() -> u64 {
|
||||
let status = std::fs::read_to_string("/proc/self/status").unwrap();
|
||||
status.lines().find_map(|l| l.strip_prefix("VmRSS:")).and_then(|v| v.trim().trim_end_matches(" kB").trim().parse().ok()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn fault(rng: &mut fastrand::Rng) -> Faults {
|
||||
let mut f = Faults::default();
|
||||
match rng.u8(0..9) {
|
||||
0 => f.cut_after = Some(rng.u64(10_000..300_000)),
|
||||
1 => f.reset_after = Some(rng.u64(10_000..300_000)),
|
||||
2 => (f.status, f.status_count) = (Some(503), Some(2)),
|
||||
3 => (f.stall_after, f.stall_ms) = (Some(rng.u64(1000..100_000)), Some(1500)),
|
||||
4 => f.throttle_conn = Some(rng.u64(100_000..2_000_000)),
|
||||
5 => f.ignore_range = true,
|
||||
6 => f.latency_ms = Some(rng.u64(10..200)),
|
||||
7 => f.max_conns = Some(rng.usize(1..3)),
|
||||
_ => {}
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore]
|
||||
async fn soak() {
|
||||
let secs: u64 = std::env::var("MEDLAR_SOAK_SECS").ok().and_then(|s| s.parse().ok()).unwrap_or(1200);
|
||||
let seed = std::env::var("MEDLAR_SOAK_SEED").ok().and_then(|s| s.parse().ok()).unwrap_or(37);
|
||||
let mut rng = fastrand::Rng::with_seed(seed);
|
||||
let server = TestServer::start().await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let files = dir.path().join("files");
|
||||
let mut manager = Manager::open(config(dir.path(), LIMITS)).unwrap();
|
||||
let (end, mut last_restart) = (Instant::now() + Duration::from_secs(secs), Instant::now());
|
||||
let (mut checked, mut corrupt, mut unfinished, mut restarts, mut next_seed) = (0usize, vec![], vec![], 0, 1000u64);
|
||||
let mut round = 0;
|
||||
while Instant::now() < end {
|
||||
round += 1;
|
||||
let mut wanted = vec![];
|
||||
for _ in 0..6 {
|
||||
next_seed += 1;
|
||||
let len = rng.usize(16 << 10..3 << 20);
|
||||
let path = TestServer::data_path(next_seed, len as u64);
|
||||
server.set_faults(&path, fault(&mut rng));
|
||||
let task = Task { url: server.url(&path), folder: files.clone(), ..Task::default() };
|
||||
let id = manager.send(Command::Add(Box::new(task))).await.unwrap();
|
||||
wanted.push((id, next_seed, len));
|
||||
}
|
||||
// Trouble for 6 to 15 seconds.
|
||||
let trouble = Instant::now() + Duration::from_millis(rng.u64(6000..15_000));
|
||||
while Instant::now() < trouble {
|
||||
sleep(ms(rng.u64(50..400))).await;
|
||||
let (id, _, _) = wanted[rng.usize(0..wanted.len())];
|
||||
match rng.u8(0..10) {
|
||||
0..=2 => drop(manager.send(Command::Pause(id)).await),
|
||||
3..=5 => drop(manager.send(Command::Resume(id)).await),
|
||||
6 => manager.set_limits(Limits { speed: [0, 300_000, 2_000_000][rng.usize(0..3)], ..LIMITS }),
|
||||
7 => {
|
||||
let limit = [None, Some(100_000), Some(1_000_000)][rng.usize(0..3)];
|
||||
drop(manager.send(Command::Edit { id, edit: Box::new(move |t: &mut Task| t.speed_limit = limit) }).await)
|
||||
}
|
||||
8 if last_restart.elapsed() > Duration::from_secs(20) => {
|
||||
// The program ends in the middle of its work and starts again.
|
||||
drop(manager);
|
||||
manager = Manager::open(config(dir.path(), LIMITS)).unwrap();
|
||||
(last_restart, restarts) = (Instant::now(), restarts + 1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Calm: no faults, no limits, everything resumed until it is done.
|
||||
server.clear_all_faults();
|
||||
manager.set_limits(LIMITS);
|
||||
let calm = Instant::now() + Duration::from_secs(120);
|
||||
loop {
|
||||
let snapshot = manager.snapshot();
|
||||
let open: Vec<TaskId> = wanted.iter().map(|w| w.0).filter(|id| snapshot.get(*id).is_none_or(|v| v.state() != State::Done)).collect();
|
||||
if open.is_empty() || Instant::now() > calm {
|
||||
break;
|
||||
}
|
||||
for id in open {
|
||||
let state = snapshot.get(id).map(|v| v.state());
|
||||
if matches!(state, Some(State::Paused | State::Failed | State::Waiting)) {
|
||||
let _ = manager.send(Command::Edit { id, edit: Box::new(|t: &mut Task| t.speed_limit = None) }).await;
|
||||
let _ = manager.send(Command::Resume(id)).await;
|
||||
}
|
||||
}
|
||||
sleep(ms(200)).await;
|
||||
}
|
||||
let snapshot = manager.snapshot();
|
||||
for (id, seed, len) in wanted {
|
||||
let Some(v) = snapshot.get(id) else {
|
||||
unfinished.push(format!("{id}: missing"));
|
||||
continue;
|
||||
};
|
||||
if v.state() != State::Done {
|
||||
unfinished.push(format!("{id} seed {seed}: {:?} {:?}", v.state(), v.task.error));
|
||||
continue;
|
||||
}
|
||||
let path = v.task.folder.join(&v.task.name);
|
||||
let is = std::fs::read(&path).unwrap_or_default();
|
||||
checked += 1;
|
||||
if is != expected(seed, 0, len) {
|
||||
corrupt.push(format!("{id} seed {seed} len {len}: {} bytes", is.len()));
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
println!("round {round}: checked {checked}, corrupt {}, unfinished {}, restarts {restarts}, rss {} kB", corrupt.len(), unfinished.len(), rss_kb());
|
||||
}
|
||||
println!("SOAK {secs}s: {checked} files checked, {} corrupt, {} unfinished, {restarts} restarts", corrupt.len(), unfinished.len());
|
||||
println!("corrupt: {corrupt:#?}\nunfinished: {unfinished:#?}");
|
||||
assert!(corrupt.is_empty(), "corrupt files: {corrupt:#?}");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore]
|
||||
async fn ten_thousand() {
|
||||
let server = TestServer::start().await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let before = rss_kb();
|
||||
let manager = Manager::open(config(dir.path(), LIMITS)).unwrap();
|
||||
let t = Instant::now();
|
||||
for i in 0..10_000u64 {
|
||||
let task = Task {
|
||||
url: server.url(&TestServer::data_path(i, 1 << 20)),
|
||||
folder: dir.path().join("files"),
|
||||
name: format!("file {i:05} with a longish name.bin"),
|
||||
state: State::Paused,
|
||||
..Task::default()
|
||||
};
|
||||
manager.send(Command::Add(Box::new(task))).await.unwrap();
|
||||
}
|
||||
let added = t.elapsed();
|
||||
let t = Instant::now();
|
||||
let n = manager.snapshot().iter().count();
|
||||
let snap = t.elapsed();
|
||||
let full = rss_kb();
|
||||
drop(manager);
|
||||
let t = Instant::now();
|
||||
let manager = Manager::open(config(dir.path(), LIMITS)).unwrap();
|
||||
let n2 = manager.snapshot().iter().count();
|
||||
let reopen = t.elapsed();
|
||||
let db = std::fs::metadata(dir.path().join("medlar.db")).map(|m| m.len()).unwrap_or(0);
|
||||
println!("TEN_THOUSAND: added {n} in {added:?}, snapshot {snap:?}, rss {before} -> {full} kB, reopen {n2} in {reopen:?}, db {db} bytes, rss now {} kB", rss_kb());
|
||||
assert_eq!((n, n2), (10_000, 10_000));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore]
|
||||
async fn loopback_speed() {
|
||||
let len: u64 = 512 << 20;
|
||||
let server = TestServer::start().await;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = TestServer::data_path(7, len);
|
||||
let url = server.url(&path);
|
||||
let out = dir.path().join("curl.bin");
|
||||
let t = Instant::now();
|
||||
let status = tokio::process::Command::new("curl").args(["-s", "-o"]).arg(&out).arg("--").arg(&url).status().await.unwrap();
|
||||
let curl = t.elapsed();
|
||||
assert!(status.success() && std::fs::metadata(&out).unwrap().len() == len);
|
||||
std::fs::remove_file(&out).unwrap();
|
||||
let manager = Manager::open(config(dir.path(), LIMITS)).unwrap();
|
||||
let t = Instant::now();
|
||||
let id = manager.send(Command::Add(Box::new(Task { url, folder: dir.path().join("files"), ..Task::default() }))).await.unwrap();
|
||||
while manager.snapshot().get(id).is_none_or(|v| v.state() != State::Done) {
|
||||
assert!(t.elapsed() < Duration::from_secs(300), "{:?}", manager.snapshot().get(id).map(|v| (v.state(), v.task.error.clone())));
|
||||
sleep(ms(20)).await;
|
||||
}
|
||||
let medlar = t.elapsed();
|
||||
let mb = len as f64 / 1048576.0;
|
||||
println!("LOOPBACK 512 MiB: curl {curl:?} ({:.0} MiB/s), medlar {medlar:?} ({:.0} MiB/s)", mb / curl.as_secs_f64(), mb / medlar.as_secs_f64());
|
||||
}
|
||||
Loading…
Reference in a new issue