diff --git a/Cargo.lock b/Cargo.lock index 49036e6..bc8b78b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,6 +59,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "autocfg" version = "1.5.1" @@ -134,12 +140,32 @@ dependencies = [ "windows-link", ] +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "const-oid" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" @@ -282,6 +308,15 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -346,6 +381,45 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + [[package]] name = "hybrid-array" version = "0.4.15" @@ -355,6 +429,64 @@ dependencies = [ "typenum", ] +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -483,12 +615,67 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -581,11 +768,18 @@ dependencies = [ "chrono", "dirs", "log", + "medlar-testserver", + "percent-encoding", "regex", + "reqwest", "rusqlite", + "rustix", + "rustls", "serde", "serde_json", + "sha2", "tempfile", + "tokio", "url", ] @@ -684,6 +878,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "option-ext" version = "0.2.0" @@ -810,6 +1010,40 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "ring" version = "0.17.14" @@ -848,6 +1082,15 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rusticata-macros" version = "4.1.0" @@ -884,6 +1127,18 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" @@ -893,6 +1148,33 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.103.17" @@ -910,6 +1192,53 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -991,6 +1320,22 @@ dependencies = [ "libc", ] +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -1057,6 +1402,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + [[package]] name = "synstructure" version = "0.13.2" @@ -1189,6 +1543,76 @@ dependencies = [ "tokio", ] +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -1240,6 +1664,25 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -1258,6 +1701,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.130" @@ -1290,6 +1744,34 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "windows-core" version = "0.62.2" diff --git a/Plans/02 Engine/S004-http-core.md b/Plans/02 Engine/S004-http-core.md index 6c1e2fd..d9a4655 100644 --- a/Plans/02 Engine/S004-http-core.md +++ b/Plans/02 Engine/S004-http-core.md @@ -12,15 +12,15 @@ Download one file over HTTP(S) in a fixed set of ranges, safely. FEATURES 1.1, 1 - testserver README or lib.rs ## Steps -- [ ] Choose and pin the HTTP client after checking its docs: HTTP/1.1 forced for segments, `Accept-Encoding: identity`, redirect control, connect and idle timeouts; record as a decision -- [ ] Probe: size, range support proven by a real 206, validators, name (Content-Disposition with RFC 5987, URL, MIME fallback), final URL -- [ ] Safe names: no path parts, control characters, leading dots, reserved or overlong names; a fuzz-style test -- [ ] Disk writer: free-space check, preallocation with fallback, positioned writes, bounded buffers, fsync policy, `.medlar` partial file, atomic rename, no silent overwrite -- [ ] Journal of finished ranges that is never ahead of the data on disk; kill -9 test at 50 random moments resumes to an identical file -- [ ] Resume check: validators plus an overlap byte comparison; a changed file stops with its own error -- [ ] Servers with no range, no length, lying length, 200 to a range request, gzip anyway: correct result or a clear error, never a corrupt file -- [ ] HTTP/2 or 3 single-stream path decided by measurement and recorded (1.14) -- [ ] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S004: …`, push +- [x] Choose and pin the HTTP client after checking its docs: HTTP/1.1 forced for segments, `Accept-Encoding: identity`, redirect control, connect and idle timeouts; record as a decision +- [x] Probe: size, range support proven by a real 206, validators, name (Content-Disposition with RFC 5987, URL, MIME fallback), final URL +- [x] Safe names: no path parts, control characters, leading dots, reserved or overlong names; a fuzz-style test +- [x] Disk writer: free-space check, preallocation with fallback, positioned writes, bounded buffers, fsync policy, `.medlar` partial file, atomic rename, no silent overwrite +- [x] Journal of finished ranges that is never ahead of the data on disk; kill -9 test at 50 random moments resumes to an identical file +- [x] Resume check: validators plus an overlap byte comparison; a changed file stops with its own error +- [x] Servers with no range, no length, lying length, 200 to a range request, gzip anyway: correct result or a clear error, never a corrupt file +- [x] HTTP/2 or 3 single-stream path decided by measurement and recorded (1.14) +- [x] `docs/PROGRESS.md` entry, tick `Plans/INDEX.md`, commit `S004: …`, push ## End criteria - `nice cargo test -j 2 -p medlar-core --test http` green, including kill tests diff --git a/Plans/INDEX.md b/Plans/INDEX.md index f1eaf49..688d0a2 100644 --- a/Plans/INDEX.md +++ b/Plans/INDEX.md @@ -12,7 +12,7 @@ Tracker: https://claude.ai/artifact/XouimfVJS6FYVKskGJ8s7H ## 02 Engine -- [ ] [S004](02%20Engine/S004-http-core.md) HTTP core with resume and crash-safe files +- [x] [S004](02%20Engine/S004-http-core.md) HTTP core with resume and crash-safe files - [ ] [S005](02%20Engine/S005-dynamic-parts.md) Dynamic parts and adaptive connections - [ ] [S006](02%20Engine/S006-manager.md) Download manager, events and snapshots - [ ] [S007](02%20Engine/S007-error-recovery.md) Error recovery diff --git a/crates/core/Cargo.toml b/crates/core/Cargo.toml index 82bde0a..94ad20a 100644 --- a/crates/core/Cargo.toml +++ b/crates/core/Cargo.toml @@ -9,11 +9,19 @@ description = "Medlar's engine, store and settings" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } dirs = "6" log = { workspace = true, features = ["std"] } +percent-encoding = "2.3.2" regex = { version = "1", default-features = false, features = ["std", "unicode-case", "unicode-perl"] } +# Pinned: D-017. +reqwest = { version = "=0.13.5", default-features = false, features = ["rustls-no-provider"] } rusqlite = { version = "0.43", features = ["bundled", "fallible_uint"] } +rustix = { version = "1.1.6", features = ["fs"] } +rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] } serde.workspace = true serde_json.workspace = true +tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "sync", "time"] } url = "2" [dev-dependencies] +medlar-testserver.workspace = true +sha2 = "0.11.1" tempfile = "3" diff --git a/crates/core/src/disk.rs b/crates/core/src/disk.rs new file mode 100644 index 0000000..997a96c --- /dev/null +++ b/crates/core/src/disk.rs @@ -0,0 +1,330 @@ +//! The file on disk while it downloads: `name.medlar`, renamed when it is whole. +//! +//! Everything here blocks, except `write_at`. + +use crate::http::name; +use rustix::fs::{CWD, FallocateFlags, RenameFlags, fallocate, fstatvfs, renameat_with}; +use rustix::io::Errno; +use std::fs::{File, OpenOptions, TryLockError}; +use std::io; +use std::os::unix::fs::{FileExt, MetadataExt}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +pub const ENDING: &str = ".medlar"; + +#[derive(Debug)] +pub enum Error { + /// Not enough free space, seen before writing. + NoSpace { need: u64, free: u64 }, + /// Another process is writing this file. + Busy, + Io(io::Error), +} + +impl From for Error { + fn from(e: io::Error) -> Error { + Error::Io(e) + } +} + +impl From for Error { + fn from(e: Errno) -> Error { + Error::Io(e.into()) + } +} + +pub type Result = std::result::Result; + +/// Locked against a second Medlar while it is open. +#[derive(Debug)] +pub struct PartialFile { + file: Arc, + path: PathBuf, +} + +impl PartialFile { + /// Starts a file in `folder`, under `name` or a numbered variant of it that is free. Returns the name it took. + pub fn create(folder: &Path, name: &str) -> Result<(PartialFile, String)> { + std::fs::create_dir_all(folder)?; + for name in variants(name) { + if exists(&folder.join(&name))? { + continue; + } + let path = partial_path(folder, &name); + let file = match OpenOptions::new().read(true).write(true).create_new(true).open(&path) { + Ok(file) => file, + // Empty and not locked: left by a kill right after it was made. Nothing is lost by taking it. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists && is_empty_file(&path) => open(&path)?, + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.into()), + }; + match lock(&file) { + Ok(()) if file.metadata()?.len() == 0 => return Ok((PartialFile { file: Arc::new(file), path }, name)), + Ok(()) | Err(Error::Busy) => continue, + Err(e) => return Err(e), + } + } + unreachable!("variants never end") + } + + /// The file of a download that was started before. None when it is gone. + pub fn reopen(folder: &Path, name: &str) -> Result> { + let path = partial_path(folder, name); + let file = match open(&path) { + Ok(file) => file, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.into()), + }; + lock(&file)?; + Ok(Some(PartialFile { file: Arc::new(file), path })) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn size(&self) -> Result { + Ok(self.file.metadata()?.len()) + } + + /// Takes the space for `size` bytes, or fails before anything is written. Filesystems that can't reserve get a sparse file. + pub fn reserve(&self, size: u64) -> Result<()> { + let meta = self.file.metadata()?; + let need = size.saturating_sub(meta.blocks() * 512); + let fs = fstatvfs(&self.file)?; + // Some network filesystems don't say. + if fs.f_blocks > 0 { + let free = fs.f_bavail.saturating_mul(fs.f_frsize); + if need > free { + return Err(Error::NoSpace { need, free }); + } + } + if size > meta.len() { + match fallocate(&self.file, FallocateFlags::empty(), 0, size) { + Ok(()) => {} + Err(Errno::NOSPC) => return Err(Errno::NOSPC.into()), + Err(_) => self.file.set_len(size)?, + } + } + Ok(()) + } + + /// Throws the contents away. + pub fn clear(&self) -> Result<()> { + Ok(self.file.set_len(0)?) + } + + /// Writes all of `buf[..n]` at `at`, off the async threads, and gives the buffer back. + pub async fn write_at(&self, buf: Vec, n: usize, at: u64) -> Result> { + let file = self.file.clone(); + blocking(move || { + file.write_all_at(&buf[..n], at)?; + Ok(buf) + }) + .await + } + + pub async fn read_at(&self, n: usize, at: u64) -> Result> { + let file = self.file.clone(); + blocking(move || { + let mut buf = vec![0; n]; + file.read_exact_at(&mut buf, at)?; + Ok(buf) + }) + .await + } + + /// Returns when everything written so far would survive a power cut. + pub fn sync(&self) -> Result<()> { + Ok(self.file.sync_data()?) + } + + /// Cuts the file to `size`, syncs it and renames it to `name`, or to a numbered variant when that name is taken by now. + /// `chosen` is called with each name before it is tried, so that a crash can't lose track of the file. + pub fn finish>( + mut self, + name: &str, + size: u64, + mut chosen: impl FnMut(&str) -> std::result::Result<(), E>, + ) -> std::result::Result { + let io = |e: io::Error| E::from(Error::Io(e)); + self.file.set_len(size).map_err(io)?; + self.file.sync_all().map_err(io)?; + let folder = self.path.parent().unwrap_or(Path::new("/")).to_path_buf(); + for variant in variants(name) { + let to = folder.join(&variant); + let from = partial_path(&folder, &variant); + if exists(&to).map_err(io)? || (from != self.path && exists(&from).map_err(io)?) { + continue; + } + // Under both names for a moment, so that it can be found whichever name a crash leaves us with. + let old = (from != self.path).then(|| std::mem::replace(&mut self.path, from)); + if let Some(old) = &old + && std::fs::hard_link(old, &self.path).is_err() + { + rename_new(old, &self.path).map_err(io)?; + } + chosen(&variant)?; + if let Some(old) = &old { + let _ = std::fs::remove_file(old); + } + match rename_new(&self.path, &to) { + Ok(()) => { + // Not every filesystem can sync a folder; the file itself is safe already. + let _ = File::open(&folder).and_then(|d| d.sync_all()); + return Ok(to); + } + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(io(e)), + } + } + unreachable!("variants never end") + } +} + +pub fn partial_path(folder: &Path, name: &str) -> PathBuf { + folder.join(format!("{name}{ENDING}")) +} + +/// Runs blocking file work off the async threads. +pub(crate) async fn blocking( + work: impl FnOnce() -> std::result::Result + Send + 'static, +) -> std::result::Result { + match tokio::task::spawn_blocking(work).await { + Ok(result) => result, + Err(e) => std::panic::resume_unwind(e.into_panic()), + } +} + +/// `a.zip`, `a (1).zip`, `a (2).zip` … +fn variants(name: &str) -> impl Iterator { + let (stem, ext) = name::split(name); + // Keep `.tar.gz` together. + let (stem, ext) = match stem.strip_suffix(".tar") { + Some(s) if ext.is_some() && !s.is_empty() => (s, &name[s.len()..]), + _ => (stem, &name[stem.len()..]), + }; + let (stem, ext) = (stem.to_string(), ext.to_string()); + (0u64..).map(move |n| if n == 0 { format!("{stem}{ext}") } else { format!("{stem} ({n}){ext}") }) +} + +/// Also true for a link that points nowhere. +fn exists(path: &Path) -> io::Result { + match path.symlink_metadata() { + Ok(_) => Ok(true), + Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false), + Err(e) => Err(e), + } +} + +fn is_empty_file(path: &Path) -> bool { + path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == 0) +} + +fn open(path: &Path) -> io::Result { + OpenOptions::new().read(true).write(true).open(path) +} + +fn lock(file: &File) -> Result<()> { + match file.try_lock() { + Err(TryLockError::WouldBlock) => Err(Error::Busy), + // Some network filesystems have no locks. + Ok(()) | Err(TryLockError::Error(_)) => Ok(()), + } +} + +/// Renames without ever replacing a file. +fn rename_new(from: &Path, to: &Path) -> io::Result<()> { + match renameat_with(CWD, from, CWD, to, RenameFlags::NOREPLACE) { + Err(Errno::INVAL | Errno::NOSYS | Errno::NOTSUP) => rename_over_placeholder(from, to), + other => Ok(other?), + } +} + +/// For filesystems without NOREPLACE: take the name with an empty file, then replace that. +fn rename_over_placeholder(from: &Path, to: &Path) -> io::Result<()> { + OpenOptions::new().write(true).create_new(true).open(to)?; + std::fs::rename(from, to) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::convert::Infallible; + + #[derive(Debug)] + struct Fail; + impl From for Fail { + fn from(_: Error) -> Fail { + Fail + } + } + impl From for Fail { + fn from(_: Infallible) -> Fail { + Fail + } + } + + fn finish(f: PartialFile, name: &str, size: u64) -> PathBuf { + f.finish(name, size, |_| Ok::<(), Fail>(())).unwrap() + } + + #[test] + fn nothing_is_overwritten() { + let dir = tempfile::tempdir().unwrap(); + let d = dir.path(); + std::fs::write(d.join("a.tar.gz"), "mine").unwrap(); + std::fs::write(d.join("a (1).tar.gz.medlar"), "half").unwrap(); + std::os::unix::fs::symlink("/nowhere", d.join("a (2).tar.gz")).unwrap(); + let (f, name) = PartialFile::create(d, "a.tar.gz").unwrap(); + assert_eq!(name, "a (3).tar.gz"); + f.reserve(10).unwrap(); + // Someone takes the name while it downloads. + std::fs::write(d.join(&name), "other").unwrap(); + assert_eq!(finish(f, &name, 10), d.join("a (3) (1).tar.gz")); + assert_eq!(std::fs::read(d.join("a.tar.gz")).unwrap(), b"mine"); + assert_eq!(std::fs::read(d.join("a (3).tar.gz")).unwrap(), b"other"); + assert!(!partial_path(d, &name).exists()); + + std::fs::write(d.join("x"), "x").unwrap(); + for rename in [rename_new, rename_over_placeholder] { + assert_eq!(rename(&d.join("x"), &d.join("a.tar.gz")).unwrap_err().kind(), io::ErrorKind::AlreadyExists); + } + rename_over_placeholder(&d.join("x"), &d.join("y")).unwrap(); + assert_eq!(std::fs::read(d.join("y")).unwrap(), b"x"); + } + + #[test] + fn one_writer_and_empty_leftovers() { + let dir = tempfile::tempdir().unwrap(); + let (first, name) = PartialFile::create(dir.path(), "f.bin").unwrap(); + let (_second, other) = PartialFile::create(dir.path(), "f.bin").unwrap(); + assert_eq!((name.as_str(), other.as_str()), ("f.bin", "f (1).bin")); + assert!(matches!(PartialFile::reopen(dir.path(), "f.bin"), Err(Error::Busy))); + drop(first); + assert!(PartialFile::reopen(dir.path(), "f.bin").unwrap().is_some()); + assert_eq!(PartialFile::create(dir.path(), "f.bin").unwrap().1, "f.bin"); + assert!(PartialFile::reopen(dir.path(), "gone").unwrap().is_none()); + } + + #[test] + fn space_is_checked_before_writing() { + let dir = tempfile::tempdir().unwrap(); + let (f, _) = PartialFile::create(dir.path(), "f").unwrap(); + assert!(matches!(f.reserve(1 << 50), Err(Error::NoSpace { need, free }) if need > free)); + assert_eq!(f.size().unwrap(), 0); + f.reserve(100_000).unwrap(); + assert_eq!(f.size().unwrap(), 100_000); + } + + #[tokio::test] + async fn a_full_disk_is_an_error() { + let file = Arc::new(open(Path::new("/dev/full")).unwrap()); + let f = PartialFile { file, path: "/dev/full".into() }; + match f.write_at(vec![0; 10], 10, 0).await { + Err(Error::Io(e)) => assert_eq!(e.kind(), io::ErrorKind::StorageFull), + other => panic!("{other:?}"), + } + } +} diff --git a/crates/core/src/http/download.rs b/crates/core/src/http/download.rs new file mode 100644 index 0000000..44197cd --- /dev/null +++ b/crates/core/src/http/download.rs @@ -0,0 +1,212 @@ +//! One file from link to disk, in a fixed set of ranges. + +use super::fetch::compare; +use super::*; +use crate::disk::{PartialFile, blocking}; +use crate::model::{Part, Task, TaskId}; +use crate::part::{self, LivePart}; +use crate::store::Store; +use std::path::PathBuf; +use std::sync::Arc; +use tokio::task::JoinSet; +use tokio::time::{MissedTickBehavior, interval}; + +#[derive(Debug, Clone)] +pub struct Options { + /// Upper bound; the task may set a lower one. + pub parts: u32, + pub min_part: u64, + /// How often finished ranges are made safe on disk and then recorded. + pub checkpoint: Duration, +} + +impl Default for Options { + fn default() -> Self { + Options { parts: 4, min_part: 1 << 20, checkpoint: Duration::from_secs(5) } + } +} + +/// Starts or continues the task and returns the finished file. Doesn't touch the task's state. +pub async fn download(client: &Client, store: &Arc, id: TaskId, source: Source, options: &Options, mut stop: Stop) -> Result { + let job = Job { store: store.clone(), id }; + let (task, parts) = job.run(move |s| Ok((s.task(id)?, s.parts(id)?))).await?; + let file = if parts.is_empty() { + None + } else { + let (folder, name) = (task.folder.clone(), task.name.clone()); + blocking(move || PartialFile::reopen(&folder, &name)).await? + }; + if !parts.is_empty() && parts.iter().all(finished) { + let size = parts.iter().map(|p| p.done).sum(); + match file { + Some(file) => return job.finish(file, size).await, + // Killed between the rename and the end. + None => { + let path = task.folder.join(&task.name); + if path.symlink_metadata().is_ok_and(|m| m.is_file() && m.len() == size) { + return Ok(path); + } + } + } + } + + let mut probe = probe(client, &source, &mut stop).await?; + let mut body = probe.body.take(); + let link = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version.clone() }; + let (file, parts) = match file { + Some(file) => resume(&job, &task, file, parts, &link, &mut stop).await?, + None => start(&job, &task, probe, options).await?, + }; + if let Some(size) = link.version.size { + let reserving = file.clone(); + blocking(move || reserving.reserve(size)).await?; + } + + let live: Vec<_> = parts.into_iter().map(LivePart::new).collect(); + let (link, (halt, halted)) = (Arc::new(link), watch::channel(false)); + let mut running = JoinSet::new(); + for part in &live { + let (link, part, file, body, halted) = (link.clone(), part.clone(), file.clone(), body.take(), halted.clone()); + running.spawn(async move { fetch(&link, &part, &file, body, halted).await }); + } + let mut tick = interval(options.checkpoint); + tick.set_missed_tick_behavior(MissedTickBehavior::Delay); + let mut failed = None; + loop { + let result = tokio::select! { + done = running.join_next() => match done { + None => break, + Some(Ok(result)) => result, + Some(Err(e)) => std::panic::resume_unwind(e.into_panic()), + }, + _ = tick.tick() => job.checkpoint(&live, &file).await, + _ = stopped(&mut stop), if failed.is_none() => Err(Error::Stopped), + }; + if let Err(e) = result { + failed.get_or_insert(e); + halt.send_replace(true); + } + } + if failed.is_none() { + // The end of a file without a length is known now. + for part in &live { + let p = part.get(); + part.set_end(p.end.unwrap_or(p.start + p.done)); + } + } + let saved = job.checkpoint(&live, &file).await; + if let Some(e) = failed { + return Err(e); + } + saved?; + let size = live.iter().map(|p| p.get().done).sum(); + let file = Arc::into_inner(file).expect("the parts have ended"); + job.finish(file, size).await +} + +fn finished(p: &Part) -> bool { + p.end == Some(p.start + p.done) +} + +async fn start(job: &Job, task: &Task, probe: Probe, options: &Options) -> Result<(Arc, Vec)> { + let parts = match probe.version.size { + Some(size) if probe.ranges => part::split(size, task.max_parts.unwrap_or(u32::MAX).min(options.parts), options.min_part), + _ => vec![Part { start: 0, end: None, done: 0 }], + }; + let wanted = safe_name(&task.name).unwrap_or(probe.name); + let (id, saved, folder) = (job.id, parts.clone(), task.folder.clone()); + let file = job + .run(move |store| { + let (file, name) = PartialFile::create(&folder, &wanted)?; + let mut task = store.task(id)?; + task.name = name; + task.size = probe.version.size; + task.etag = probe.version.etag; + task.last_modified = probe.version.last_modified; + task.mime = probe.mime; + store.save_task(task)?; + store.save_parts(id, saved)?; + Ok(file) + }) + .await?; + Ok((Arc::new(file), parts)) +} + +/// Checks that the server still has the file the parts came from. +async fn resume(job: &Job, task: &Task, file: PartialFile, mut parts: Vec, link: &Link, stop: &mut Stop) -> Result<(Arc, Vec)> { + let old = Validators { size: task.size, etag: task.etag.clone(), last_modified: task.last_modified.clone() }; + if !old.same_file(&link.version) { + return Err(Error::Changed); + } + let file = Arc::new(file); + if !link.ranges { + if parts.iter().any(|p| p.done > 0 && p.end.is_some()) { + return Err(Error::NoResume); + } + // The server never could: once more from the start. The record goes first, so that it stays behind the data. + let parts = vec![Part { start: 0, end: None, done: 0 }]; + let (id, saved, clearing) = (job.id, parts.clone(), file.clone()); + job.run(move |store| { + store.save_parts(id, saved)?; + Ok(clearing.clear()?) + }) + .await?; + return Ok((file, parts)); + } + let len = file.size()?; + for p in &mut parts { + p.end = p.end.or(link.version.size); + p.done = p.done.min(len.saturating_sub(p.start)); + if p.end.is_none_or(|end| end < p.start + p.done) { + return Err(Error::Changed); + } + } + // Parts that go on compare their own last bytes. Where none does, a finished one answers for all. + if !parts.iter().any(|p| p.done > 0 && !finished(p)) + && let Some(p) = parts.iter().find(|p| p.done > 0) + { + let n = p.done.min(OVERLAP); + compare(link, &file, p.start + p.done - n, n, stop).await?; + } + Ok((file, parts)) +} + +struct Job { + store: Arc, + id: TaskId, +} + +impl Job { + async fn run(&self, work: impl FnOnce(&Store) -> Result + Send + 'static) -> Result { + let store = self.store.clone(); + blocking(move || work(&store)).await + } + + /// Data first, then the record of it: the record never claims bytes that a power cut could take. + async fn checkpoint(&self, live: &[Arc], file: &Arc) -> Result<()> { + let parts: Vec = live.iter().map(|p| p.get()).collect(); + let (id, file) = (self.id, file.clone()); + self.run(move |store| { + if store.parts(id)? != parts { + file.sync()?; + store.save_parts(id, parts)?; + } + Ok(()) + }) + .await + } + + async fn finish(&self, file: PartialFile, size: u64) -> Result { + let id = self.id; + self.run(move |store| { + let task = store.task(id)?; + file.finish(&task.name, size, |name| { + if name != task.name || task.size != Some(size) { + store.save_task(Task { name: name.into(), size: Some(size), ..task.clone() })?; + } + Ok(()) + }) + }) + .await + } +} diff --git a/crates/core/src/http/fetch.rs b/crates/core/src/http/fetch.rs new file mode 100644 index 0000000..ee5ef63 --- /dev/null +++ b/crates/core/src/http/fetch.rs @@ -0,0 +1,170 @@ +//! One part over one connection. + +use super::probe::check_length; +use super::*; +use crate::disk::PartialFile; +use crate::part::LivePart; +use std::time::Instant; + +/// Finished bytes read again and compared when a part goes on. +pub const OVERLAP: u64 = 4096; +/// Held in memory for each part. +const BUFFER: usize = 512 * 1024; +/// A slow part writes what it has this often. +const FLUSH_EVERY: Duration = Duration::from_secs(1); + +/// The file as the probe saw it. +#[derive(Debug, Clone)] +pub struct Link { + pub client: Client, + /// At the final link. + pub source: Source, + pub ranges: bool, + pub version: Validators, +} + +/// Fills `part` until it is whole, `stop` turns true or something breaks. Whatever arrived is written before it returns, so stop +/// it instead of dropping it. Without ranges the part must be untouched; `body` is the reply to use, if there is one already. +pub async fn fetch(link: &Link, part: &LivePart, file: &PartialFile, body: Option, mut stop: Stop) -> Result<()> { + if part.finished() { + return Ok(()); + } + if *stop.borrow() { + return Err(Error::Stopped); + } + let (mut response, mut known) = if link.ranges { + range(link, part, file, &mut stop).await? + } else { + (whole(link, part, body, &mut stop).await?, vec![]) + }; + let mut buf = Vec::with_capacity(BUFFER); + let mut flushed = Instant::now(); + loop { + let chunk = tokio::select! { + biased; + _ = stopped(&mut stop) => Err(Error::Stopped), + chunk = response.chunk() => chunk.map_err(|e| broken(e, part, link)), + }; + match chunk { + Ok(Some(mut chunk)) => { + let old = chunk.split_to(chunk.len().min(known.len())); + if old != known[..old.len()] { + return Err(Error::Changed); + } + known.drain(..old.len()); + buf.extend_from_slice(&chunk); + let whole = part.remaining().is_some_and(|left| buf.len() as u64 >= left); + if whole || buf.len() >= BUFFER || flushed.elapsed() >= FLUSH_EVERY { + buf = flush(part, file, buf).await?; + flushed = Instant::now(); + } + if part.finished() { + return Ok(()); + } + } + Ok(None) => { + flush(part, file, buf).await?; + let got = part.get().done; + let expected = expected(part, link); + return if expected.is_none_or(|n| n == got) { Ok(()) } else { Err(Error::Cut { got, expected }) }; + } + Err(e) => { + flush(part, file, buf).await?; + return Err(e); + } + } + } +} + +/// Bytes the part should have in the end. +fn expected(part: &LivePart, link: &Link) -> Option { + let p = part.get(); + p.end.map(|end| end - p.start).or(link.version.size) +} + +fn broken(e: reqwest::Error, part: &LivePart, link: &Link) -> Error { + if e.is_timeout() { e.into() } else { Error::Cut { got: part.get().done, expected: expected(part, link) } } +} + +async fn flush(part: &LivePart, file: &PartialFile, buf: Vec) -> Result> { + if buf.is_empty() { + return Ok(buf); + } + let (at, n) = part.claim(buf.len() as u64); + let written = file.write_at(buf, n as usize, at).await; + part.settle(written.is_ok()); + let mut buf = written?; + buf.clear(); + Ok(buf) +} + +/// Asks for the rest of the part and checks that this is what comes. Also gives the finished bytes it must begin with. +async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec)> { + let p = part.get(); + let overlap = p.done.min(OVERLAP); + let first = p.start + p.done - overlap; + let known = file.read_at(overlap as usize, first).await?; + let response = send_range(link, first, p.end, stop).await?; + Ok((response, known)) +} + +async fn send_range(link: &Link, first: u64, end: Option, stop: &mut Stop) -> Result { + let last = end.map(|e| (e - 1).to_string()).unwrap_or_default(); + let response = link.source.get(&link.client, Some(format!("bytes={first}-{last}")), link.version.if_range().as_ref(), stop).await?; + let headers = response.headers(); + match response.status() { + StatusCode::PARTIAL_CONTENT => { + let range = ContentRange::of(headers).ok_or_else(|| Error::BadReply("no usable Content-Range".into()))?; + if !link.version.same_file(&Validators::of(headers, range.total)) { + return Err(Error::Changed); + } + if range.first != first || end.is_some_and(|e| range.last >= e) { + return Err(Error::BadReply("another range than asked for".into())); + } + check_length(headers, range)?; + check_encoding(headers, response.url())?; + Ok(response) + } + StatusCode::OK if link.version.same_file(&Validators::of(headers, content_length(headers))) => Err(Error::RangeIgnored), + StatusCode::OK => Err(Error::Changed), + StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => Err(Error::Changed), + _ => Err(status_error(&response)), + } +} + +async fn whole(link: &Link, part: &LivePart, body: Option, stop: &mut Stop) -> Result { + if part.get() != (crate::model::Part { start: 0, end: None, done: 0 }) { + return Err(Error::NoResume); + } + let response = match body { + Some(body) => body, + None => link.source.get(&link.client, None, None, stop).await?, + }; + let headers = response.headers(); + match response.status() { + StatusCode::OK => {} + s if s.is_success() => return Err(Error::BadReply(format!("status {} without a range", s.as_u16()))), + _ => return Err(status_error(&response)), + } + check_encoding(headers, response.url())?; + if !link.version.same_file(&Validators::of(headers, content_length(headers))) { + return Err(Error::Changed); + } + Ok(response) +} + +/// Compares `len` finished bytes at `at` with the server's. +pub async fn compare(link: &Link, file: &PartialFile, at: u64, len: u64, stop: &mut Stop) -> Result<()> { + let known = file.read_at(len as usize, at).await?; + let mut response = send_range(link, at, Some(at + len), stop).await?; + let mut seen = vec![]; + while seen.len() < known.len() { + let chunk = tokio::select! { + _ = stopped(stop) => return Err(Error::Stopped), + chunk = response.chunk() => chunk?, + }; + let Some(chunk) = chunk else { return Err(Error::Cut { got: seen.len() as u64, expected: Some(len) }) }; + seen.extend_from_slice(&chunk); + } + if seen == known { Ok(()) } else { Err(Error::Changed) } +} diff --git a/crates/core/src/http/mod.rs b/crates/core/src/http/mod.rs new file mode 100644 index 0000000..d38c18a --- /dev/null +++ b/crates/core/src/http/mod.rs @@ -0,0 +1,330 @@ +//! Downloading over HTTP and HTTPS. How the client is set up and why: D-017, D-018. + +mod download; +mod fetch; +pub(crate) mod name; +mod probe; + +pub use download::{Options, download}; +pub use fetch::{Link, OVERLAP, compare, fetch}; +pub use name::safe as safe_name; +pub use probe::{Probe, probe}; + +use crate::{disk, store}; +use reqwest::header::{self, HeaderMap, HeaderName, HeaderValue}; +use reqwest::{Certificate, Client, Response, StatusCode, redirect}; +use std::sync::Once; +use std::time::Duration; +use tokio::sync::watch; +use url::Url; + +/// Why a download stopped. Plain words for the user come with the error kinds (S007). +#[derive(Debug)] +pub enum Error { + /// Asked to stop. + Stopped, + /// Not a link this module can open. + Link, + /// No connection, no answer in time, or a broken one. Never holds the link. + Net(reqwest::Error), + Status { code: u16, retry_after: Option }, + /// The file on the server is not the one the parts came from. + Changed, + /// A range was asked for and the whole file came. + RangeIgnored, + /// Finished bytes are on disk and the server can't continue from them. + NoResume, + /// The server packed the file, though it was asked not to. + Encoded(String), + /// The server's own numbers contradict each other. + BadReply(String), + /// The connection ended early. + Cut { got: u64, expected: Option }, + Disk(disk::Error), + Store(store::Error), +} + +pub type Result = std::result::Result; + +impl From for Error { + fn from(e: disk::Error) -> Error { + Error::Disk(e) + } +} + +impl From for Error { + fn from(e: store::Error) -> Error { + Error::Store(e) + } +} + +impl From for Error { + fn from(e: reqwest::Error) -> Error { + Error::Net(e.without_url()) + } +} + +/// Turns true when the work should stop. +pub type Stop = watch::Receiver; + +#[derive(Debug, Clone)] +pub struct ClientOptions { + pub connect_timeout: Duration, + /// Between two pieces of data. + pub idle_timeout: Duration, + /// DER certificates to trust instead of the system's (tests). + pub only_certs: Vec>, +} + +impl Default for ClientOptions { + fn default() -> Self { + ClientOptions { connect_timeout: Duration::from_secs(20), idle_timeout: Duration::from_secs(30), only_certs: vec![] } + } +} + +pub fn client(options: &ClientOptions) -> Result { + static TLS: Once = Once::new(); + // Fails only when one is installed already, which is fine. + TLS.call_once(|| drop(rustls::crypto::ring::default_provider().install_default())); + let mut builder = Client::builder() + .user_agent(concat!("Medlar/", env!("CARGO_PKG_VERSION"))) + .http1_only() + .redirect(redirect::Policy::limited(10)) + .referer(false) + .retry(reqwest::retry::never()) + .no_proxy() + .connect_timeout(options.connect_timeout) + .read_timeout(options.idle_timeout); + if !options.only_certs.is_empty() { + let certs = options.only_certs.iter().map(|der| Certificate::from_der(der)).collect::>>()?; + builder = builder.tls_certs_only(certs); + } + Ok(builder.build()?) +} + +/// A link and the headers that go with it. +#[derive(Debug, Clone)] +pub struct Source { + pub url: Url, + pub headers: HeaderMap, +} + +impl Source { + pub fn new(url: &str) -> Result { + let url = Url::parse(url).map_err(|_| Error::Link)?; + if !matches!(url.scheme(), "http" | "https") || !url.has_host() { + return Err(Error::Link); + } + Ok(Source { url, headers: HeaderMap::new() }) + } + + /// Adds headers, skipping what isn't valid and what the engine sets itself. + pub fn with_headers(mut self, headers: &[(String, String)]) -> Source { + for (name, value) in headers { + let (Ok(name), Ok(value)) = (HeaderName::try_from(name), HeaderValue::try_from(value)) else { continue }; + if !matches!(name, header::RANGE | header::IF_RANGE | header::ACCEPT_ENCODING | header::HOST | header::CONNECTION) { + self.headers.append(name, value); + } + } + self + } + + /// The same source at the link its redirects led to. Secrets stay with the site they were given for. + pub fn at(&self, url: &Url) -> Source { + let mut headers = self.headers.clone(); + if url.origin() != self.url.origin() { + for name in [header::COOKIE, header::AUTHORIZATION, header::PROXY_AUTHORIZATION] { + headers.remove(name); + } + } + Source { url: url.clone(), headers } + } + + async fn get(&self, client: &Client, range: Option, if_range: Option<&HeaderValue>, stop: &mut Stop) -> Result { + let mut request = client.get(self.url.clone()).headers(self.headers.clone()).header(header::ACCEPT_ENCODING, "identity"); + if let Some(range) = range { + request = request.header(header::RANGE, range); + if let Some(validator) = if_range { + request = request.header(header::IF_RANGE, validator); + } + } + tokio::select! { + _ = stopped(stop) => Err(Error::Stopped), + response = request.send() => Ok(response?), + } + } +} + +/// Resolves when asked to stop, never when nobody can ask any more. +async fn stopped(stop: &mut Stop) { + if stop.wait_for(|s| *s).await.is_err() { + std::future::pending().await + } +} + +/// `bytes a-b/total`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct ContentRange { + first: u64, + last: u64, + total: Option, +} + +impl ContentRange { + fn of(headers: &HeaderMap) -> Option { + let (range, total) = split_range(headers)?; + let (first, last) = range.split_once('-')?; + let (first, last) = (first.trim().parse().ok()?, last.trim().parse().ok()?); + let total = match total { + "*" => None, + n => Some(n.parse().ok()?), + }; + (first <= last && total.is_none_or(|t| last < t)).then_some(ContentRange { first, last, total }) + } + + fn len(self) -> u64 { + self.last - self.first + 1 + } +} + +/// The total in `bytes */total`, which comes with 416. +fn unsatisfied_total(headers: &HeaderMap) -> Option { + split_range(headers).filter(|(range, _)| *range == "*")?.1.parse().ok() +} + +fn split_range(headers: &HeaderMap) -> Option<(&str, &str)> { + let value = headers.get(header::CONTENT_RANGE)?.to_str().ok()?.trim(); + let (range, total) = value.strip_prefix("bytes")?.trim().split_once('/')?; + Some((range.trim(), total.trim())) +} + +fn content_length(headers: &HeaderMap) -> Option { + headers.get(header::CONTENT_LENGTH)?.to_str().ok()?.trim().parse().ok() +} + +fn status_error(response: &Response) -> Error { + Error::Status { code: response.status().as_u16(), retry_after: retry_after(response.headers()) } +} + +fn retry_after(headers: &HeaderMap) -> Option { + let value = headers.get(header::RETRY_AFTER)?.to_str().ok()?.trim(); + if let Ok(seconds) = value.parse() { + return Some(Duration::from_secs(seconds)); + } + let at = chrono::DateTime::parse_from_rfc2822(value).ok()?; + Some((at.to_utc() - chrono::Utc::now()).to_std().unwrap_or_default()) +} + +/// Refuses a packed body. A `.gz` file announced as "gzip" is the file itself, a common server mistake. +fn check_encoding(headers: &HeaderMap, url: &Url) -> Result<()> { + let Some(value) = headers.get(header::CONTENT_ENCODING) else { return Ok(()) }; + let encoding = value.to_str().unwrap_or("?").trim().to_ascii_lowercase(); + let packed_file = || { + let path = url.path().to_ascii_lowercase(); + path.ends_with(".gz") + || path.ends_with(".tgz") + || name::mime(headers).is_some_and(|m| matches!(m.as_str(), "application/gzip" | "application/x-gzip")) + }; + match encoding.as_str() { + "" | "identity" => Ok(()), + "gzip" | "x-gzip" if packed_file() => Ok(()), + _ => Err(Error::Encoded(encoding)), + } +} + +/// What tells one version of a file from another. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Validators { + pub size: Option, + pub etag: Option, + pub last_modified: Option, +} + +impl Validators { + fn of(headers: &HeaderMap, size: Option) -> Validators { + let text = |name| headers.get(name).and_then(|v| v.to_str().ok()).map(|s| s.trim().to_string()).filter(|s| !s.is_empty()); + Validators { size, etag: text(header::ETAG), last_modified: text(header::LAST_MODIFIED) } + } + + /// False when anything both sides know differs. + pub fn same_file(&self, other: &Validators) -> bool { + fn agree(a: Option, b: Option) -> bool { + a.is_none() || b.is_none() || a == b + } + // A proxy that packs replies turns the tag into a weak one. + fn strong(tag: &Option) -> Option<&str> { + tag.as_deref().map(|t| t.strip_prefix("W/").unwrap_or(t)) + } + agree(self.size, other.size) + && agree(strong(&self.etag), strong(&other.etag)) + && agree(self.last_modified.as_ref(), other.last_modified.as_ref()) + } + + /// The value for `If-Range`, which must not be a weak tag. + fn if_range(&self) -> Option { + let strong = self.etag.as_ref().filter(|t| !t.starts_with("W/")); + HeaderValue::try_from(strong.or(self.last_modified.as_ref())?).ok() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn headers(name: HeaderName, value: &str) -> HeaderMap { + HeaderMap::from_iter([(name, HeaderValue::try_from(value).unwrap())]) + } + + #[test] + fn content_ranges() { + let of = |v| ContentRange::of(&headers(header::CONTENT_RANGE, v)); + assert_eq!(of("bytes 0-0/10"), Some(ContentRange { first: 0, last: 0, total: Some(10) })); + assert_eq!(of("bytes 5-9/*").unwrap().len(), 5); + for bad in ["bytes 5-4/10", "bytes 0-10/10", "bytes */10", "items 0-1/2", "bytes 0-1", "bytes -1-1/2", "0-1/2"] { + assert_eq!(of(bad), None, "{bad}"); + } + assert_eq!(unsatisfied_total(&headers(header::CONTENT_RANGE, "bytes */10")), Some(10)); + assert_eq!(unsatisfied_total(&headers(header::CONTENT_RANGE, "bytes 0-1/10")), None); + } + + #[test] + fn retry_after_forms() { + assert_eq!(retry_after(&headers(header::RETRY_AFTER, "7")), Some(Duration::from_secs(7))); + assert_eq!(retry_after(&headers(header::RETRY_AFTER, "Sun, 06 Nov 1994 08:49:37 GMT")), Some(Duration::ZERO)); + assert_eq!(retry_after(&headers(header::RETRY_AFTER, "soon")), None); + } + + #[test] + fn secrets_stay_with_their_site() { + let given = [("Cookie", "a=b"), ("Authorization", "Basic x"), ("Referer", "https://p/"), ("Range", "bytes=1-2"), ("Bad name", "x")]; + let given = given.map(|(k, v)| (k.to_string(), v.to_string())); + let source = Source::new("https://h/f").unwrap().with_headers(&given); + assert_eq!(source.headers.len(), 3); + assert_eq!(source.at(&Url::parse("https://h/other").unwrap()).headers.len(), 3); + for other in ["https://cdn/f", "http://h/f", "https://h:444/f"] { + let moved = source.at(&Url::parse(other).unwrap()).headers; + assert_eq!(moved.len(), 1, "{other}"); + assert!(moved.contains_key(header::REFERER)); + } + for bad in ["ftp://h/f", "file:///etc/passwd", "no link", "http:///"] { + assert!(matches!(Source::new(bad), Err(Error::Link)), "{bad}"); + } + } + + #[test] + fn versions() { + let v = |size, etag: Option<&str>, lm: Option<&str>| Validators { + size, + etag: etag.map(String::from), + last_modified: lm.map(String::from), + }; + let a = v(Some(1), Some("\"x\""), Some("d1")); + assert!(a.same_file(&v(None, Some("W/\"x\""), None))); + assert!(!a.same_file(&v(Some(2), None, None))); + assert!(!a.same_file(&v(None, Some("\"y\""), None))); + assert!(!a.same_file(&v(None, None, Some("d2")))); + assert_eq!(a.if_range().unwrap(), "\"x\""); + assert_eq!(v(None, Some("W/\"x\""), Some("d1")).if_range().unwrap(), "d1"); + assert_eq!(v(None, Some("W/\"x\""), None).if_range(), None); + } +} diff --git a/crates/core/src/http/name.rs b/crates/core/src/http/name.rs new file mode 100644 index 0000000..810a41d --- /dev/null +++ b/crates/core/src/http/name.rs @@ -0,0 +1,321 @@ +//! File names that come from servers: found, then made safe. + +use super::Source; +use percent_encoding::percent_decode_str; +use reqwest::header::{CONTENT_DISPOSITION, CONTENT_TYPE, HeaderMap}; +use url::Url; + +/// Bytes. Leaves room for ` (9999)` and the `.medlar` ending in the usual limit of 255. +const MAX: usize = 240; +/// A longer "extension" is just a name with a dot in it. +const MAX_EXT: usize = 20; + +/// Extensions of pages that send some other kind of file. +const SCRIPTS: &[&str] = &["php", "asp", "aspx", "ashx", "jsp", "cgi", "do", "action"]; + +const TYPES: &[(&str, &str)] = &[ + ("application/epub+zip", "epub"), + ("application/gzip", "gz"), + ("application/json", "json"), + ("application/msword", "doc"), + ("application/pdf", "pdf"), + ("application/rtf", "rtf"), + ("application/vnd.android.package-archive", "apk"), + ("application/vnd.debian.binary-package", "deb"), + ("application/vnd.ms-excel", "xls"), + ("application/vnd.ms-powerpoint", "ppt"), + ("application/vnd.openxmlformats-officedocument.presentationml.presentation", "pptx"), + ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xlsx"), + ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "docx"), + ("application/vnd.rar", "rar"), + ("application/x-7z-compressed", "7z"), + ("application/x-bzip2", "bz2"), + ("application/x-gzip", "gz"), + ("application/x-iso9660-image", "iso"), + ("application/x-rar-compressed", "rar"), + ("application/x-rpm", "rpm"), + ("application/x-tar", "tar"), + ("application/x-xz", "xz"), + ("application/xml", "xml"), + ("application/zip", "zip"), + ("application/zstd", "zst"), + ("audio/aac", "aac"), + ("audio/flac", "flac"), + ("audio/mp4", "m4a"), + ("audio/mpeg", "mp3"), + ("audio/ogg", "ogg"), + ("audio/opus", "opus"), + ("audio/wav", "wav"), + ("audio/x-wav", "wav"), + ("image/avif", "avif"), + ("image/gif", "gif"), + ("image/jpeg", "jpg"), + ("image/png", "png"), + ("image/svg+xml", "svg"), + ("image/webp", "webp"), + ("text/css", "css"), + ("text/csv", "csv"), + ("text/html", "html"), + ("text/plain", "txt"), + ("video/mp4", "mp4"), + ("video/mp2t", "ts"), + ("video/mpeg", "mpg"), + ("video/quicktime", "mov"), + ("video/webm", "webm"), + ("video/x-matroska", "mkv"), + ("video/x-msvideo", "avi"), +]; + +/// The name for a reply: Content-Disposition, then the final link, then the first link, then the host. Always safe. +pub(super) fn pick(source: &Source, last: &Url, headers: &HeaderMap) -> String { + if let Some(name) = headers.get(CONTENT_DISPOSITION).and_then(|v| disposition(v.as_bytes())) { + return name; + } + let ext = mime(headers).and_then(|m| extension_of(&m)); + let names: Vec = [last, &source.url].into_iter().filter_map(from_url).collect(); + let name = names.iter().find(|n| split(n).1.is_some()).or(names.first()).cloned(); + let Some(name) = name else { + let host = last.host_str().unwrap_or("file").trim_matches(['[', ']']); + return safe(&format!("{host}{}", ext.map(|e| format!(".{e}")).unwrap_or_default())).unwrap_or_else(|| "file".into()); + }; + match (split(&name), ext) { + ((stem, None), Some(ext)) => format!("{stem}.{ext}"), + ((stem, Some(old)), Some(ext)) if SCRIPTS.contains(&old.to_lowercase().as_str()) => format!("{stem}.{ext}"), + _ => name, + } +} + +/// `type/subtype` in lower case. +pub(super) fn mime(headers: &HeaderMap) -> Option { + let value = headers.get(CONTENT_TYPE)?.to_str().ok()?; + let mime = value.split(';').next()?.trim().to_ascii_lowercase(); + (!mime.is_empty()).then_some(mime) +} + +fn extension_of(mime: &str) -> Option<&'static str> { + TYPES.iter().find(|(m, _)| *m == mime).map(|(_, e)| *e) +} + +fn from_url(url: &Url) -> Option { + let last = url.path_segments()?.rfind(|s| !s.is_empty())?; + // Decoded only here, so `%2F` can't become a path: `safe` sees it. + safe(&percent_decode_str(last).decode_utf8_lossy()) +} + +/// The file name in a Content-Disposition value (RFC 6266, RFC 5987 for `filename*`, which wins). +fn disposition(value: &[u8]) -> Option { + // Not ASCII: servers send UTF-8, or Latin-1 as the old standard said. + let text = match std::str::from_utf8(value) { + Ok(s) => s.to_string(), + Err(_) => value.iter().map(|&b| b as char).collect(), + }; + let (mut plain, mut star) = (None, None); + for (key, value) in params(&text) { + match key.as_str() { + "filename" if plain.is_none() => plain = safe(&value), + "filename*" if star.is_none() => star = extended(&value).and_then(|v| safe(&v)), + _ => {} + } + } + star.or(plain) +} + +/// `; key=value` pairs, values unquoted. +fn params(text: &str) -> Vec<(String, String)> { + let mut found = vec![]; + let mut it = text.chars().peekable(); + // The type ("attachment"), which some servers leave out. + let mut key = String::new(); + while let Some(c) = it.next() { + match c { + ';' => key.clear(), + '=' => { + let mut value = String::new(); + while it.next_if(|c| c.is_whitespace()).is_some() {} + if it.next_if_eq(&'"').is_some() { + while let Some(c) = it.next() { + match c { + '"' => break, + '\\' if it.peek().is_some_and(|c| matches!(c, '"' | '\\')) => value.extend(it.next()), + c => value.push(c), + } + } + } else { + while let Some(c) = it.next_if(|c| *c != ';') { + value.push(c); + } + } + found.push((key.trim().to_ascii_lowercase(), value.trim().to_string())); + key.clear(); + } + c => key.push(c), + } + } + found +} + +/// `UTF-8'en'a%20b`. +fn extended(value: &str) -> Option { + let mut it = value.splitn(3, '\''); + let (charset, _lang, text) = (it.next()?, it.next()?, it.next()?); + let bytes: Vec = percent_decode_str(text).collect(); + match charset.to_ascii_lowercase().as_str() { + "utf-8" => String::from_utf8(bytes).ok(), + "iso-8859-1" => Some(bytes.iter().map(|&b| b as char).collect()), + _ => None, + } +} + +/// Stem and extension. +pub(crate) fn split(name: &str) -> (&str, Option<&str>) { + match name.rsplit_once('.') { + Some((stem, ext)) if !stem.is_empty() && !ext.is_empty() && ext.len() <= MAX_EXT && ext.chars().all(char::is_alphanumeric) => { + (stem, Some(ext)) + } + _ => (name, None), + } +} + +/// One name that is safe in any folder and on any drive, or None when nothing is left of it. +pub fn safe(name: &str) -> Option { + let last = name.rsplit(['/', '\\']).next().unwrap_or(""); + let clean: String = last + .chars() + .filter(|&c| !c.is_control() && !invisible(c)) + // Not allowed on FAT and NTFS drives. + .map(|c| if matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*') { '_' } else { c }) + .collect(); + let mut name = trim(&clean).to_string(); + if name.len() > MAX { + let tail = split(&name).1.map(|e| format!(".{e}")).unwrap_or_default(); + let stem = &name[..name.len() - tail.len()]; + let mut cut = MAX - tail.len(); + while !stem.is_char_boundary(cut) { + cut -= 1; + } + name = format!("{}{tail}", trim(&stem[..cut])); + } + let stem = name.split('.').next().unwrap_or("").trim_end().to_ascii_uppercase(); + if reserved(&stem) { + name.insert(0, '_'); + } + (!name.is_empty()).then_some(name) +} + +/// Leading dots hide a file; trailing dots and spaces are lost on some drives. +fn trim(s: &str) -> &str { + s.trim_start_matches(|c: char| c == '.' || c.is_whitespace()).trim_end_matches(|c: char| c == '.' || c.is_whitespace()) +} + +/// Characters that hide or reorder the rest of a name (`gpj.exe` shown as `exe.jpg`). +fn invisible(c: char) -> bool { + matches!(c, '\u{ad}' | '\u{61c}' | '\u{200b}'..='\u{200f}' | '\u{2028}'..='\u{202e}' | '\u{2060}'..='\u{206f}' | '\u{feff}' | '\u{fff9}'..='\u{fffb}') +} + +/// Device names on Windows drives. +fn reserved(stem: &str) -> bool { + matches!(stem, "CON" | "PRN" | "AUX" | "NUL") + || stem.strip_prefix("COM").or(stem.strip_prefix("LPT")).is_some_and(|n| n.len() == 1 && n.as_bytes()[0].is_ascii_digit()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::{Component, Path}; + + #[test] + fn dispositions() { + for (value, want) in [ + ("attachment; filename=\"a b.zip\"", Some("a b.zip")), + ("attachment; filename=plain.zip", Some("plain.zip")), + ("attachment; filename=two words.zip; size=3", Some("two words.zip")), + ("inline;FileName=\"x\\\"y.txt\"", Some("x_y.txt")), + ("attachment; filename=\"semi;colon=.txt\"", Some("semi;colon=.txt")), + ("attachment; filename=\"fallback.bin\"; filename*=UTF-8''na%C3%AFve%20file.bin", Some("naïve file.bin")), + ("attachment; filename*=iso-8859-1'en'%A3%20rates.txt", Some("£ rates.txt")), + ("attachment; filename*=UTF-8''..%2F..%2Fetc%2Fpasswd", Some("passwd")), + ("attachment; filename*=UTF-8''%FF; filename=ok.bin", Some("ok.bin")), + ("attachment; filename=\"C:\\\\dir\\\\a.exe\"", Some("a.exe")), + ("attachment; filename=\"..\"", None), + ("attachment; filename=\"unclosed", Some("unclosed")), + ("attachment", None), + ("", None), + ] { + assert_eq!(disposition(value.as_bytes()).as_deref(), want, "{value}"); + } + assert_eq!(disposition("filename=\"日本.zip\"".as_bytes()).as_deref(), Some("日本.zip")); + assert_eq!(disposition(b"filename=\"caf\xe9.zip\"").as_deref(), Some("café.zip")); + } + + fn picked(first: &str, last: &str, mime: &str) -> String { + let mut headers = HeaderMap::new(); + if !mime.is_empty() { + headers.insert(CONTENT_TYPE, mime.parse().unwrap()); + } + pick(&Source::new(first).unwrap(), &Url::parse(last).unwrap(), &headers) + } + + #[test] + fn names_from_links() { + let h = "https://host.example/"; + assert_eq!(picked(h, "https://host.example/a%20b.iso?x=/c.zip", "application/pdf"), "a b.iso"); + assert_eq!(picked("https://host.example/file.zip", "https://cdn.example/8f3a", "application/zip"), "file.zip"); + assert_eq!(picked(h, "https://host.example/get.php?id=1", "application/zip; x=1"), "get.zip"); + assert_eq!(picked(h, "https://host.example/movie", "video/mp4"), "movie.mp4"); + assert_eq!(picked(h, "https://host.example/dir/", "text/html"), "dir.html"); + assert_eq!(picked(h, h, "text/html; charset=utf-8"), "host.example.html"); + assert_eq!(picked(h, "https://host.example/..%2F..%2F.ssh%2Fid", ""), "id"); + assert_eq!(picked(h, "http://[::1]/", ""), "__1"); + } + + #[test] + fn safe_names() { + for (name, want) in [ + ("../../etc/passwd", Some("passwd")), + ("a\\b\\c.txt", Some("c.txt")), + (".bashrc", Some("bashrc")), + ("...", None), + ("", None), + ("dir/", None), + ("a\0b\n.txt", Some("ab.txt")), + ("photo\u{202e}gpj.exe", Some("photogpj.exe")), + ("con.txt", Some("_con.txt")), + ("COM7", Some("_COM7")), + ("COMB.txt", Some("COMB.txt")), + (" a. ", Some("a")), + ("what?.html", Some("what_.html")), + ] { + assert_eq!(safe(name).as_deref(), want, "{name:?}"); + } + let long = safe(&format!("{}.tar.gz", "é".repeat(300))).unwrap(); + assert!(long.len() <= MAX && long.ends_with("é.gz"), "{long}"); + } + + #[test] + fn no_name_gets_out_of_its_folder() { + const BITS: &[&str] = &[ + "..", ".", "/", "\\", "\0", "\n", " ", "\t", "%2f", "%00", "a", "Z", "9", "é", "日", "\u{202e}", "\u{200b}", "\u{feff}", "\u{85}", + ":", "*", "?", "\"", "<", "|", "con", "NUL", "COM1", ".gz", ".medlar", "~", "-", "$", "`", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "💾", + ]; + let mut seed = 0x9E37_79B9_7F4A_7C15_u64; + let mut next = |n: usize| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % n as u64) as usize + }; + for _ in 0..200_000 { + let len = next(30); + let raw: String = (0..len).map(|_| BITS[next(BITS.len())]).collect(); + let via_header = disposition(format!("attachment; filename=\"{raw}\"; filename*=UTF-8''{raw}").as_bytes()); + for name in [safe(&raw), via_header].into_iter().flatten() { + let parts: Vec<_> = Path::new(&name).components().collect(); + assert!(matches!(parts[..], [Component::Normal(p)] if p.to_str() == Some(&name)), "{raw:?} gave {name:?}"); + assert!(!name.starts_with('.') && !name.ends_with(['.', ' ']), "{raw:?} gave {name:?}"); + assert!(name.len() <= MAX + 1, "{raw:?} gave {name:?}"); + assert!(!name.chars().any(|c| c.is_control() || invisible(c) || c == '\\'), "{raw:?} gave {name:?}"); + assert_eq!(safe(&name).as_deref(), Some(name.as_str()), "not stable: {raw:?}"); + } + } + } +} diff --git a/crates/core/src/http/probe.rs b/crates/core/src/http/probe.rs new file mode 100644 index 0000000..f77bf3f --- /dev/null +++ b/crates/core/src/http/probe.rs @@ -0,0 +1,65 @@ +//! What a link leads to. + +use super::*; + +#[derive(Debug)] +pub struct Probe { + /// Where the redirects ended. + pub url: Url, + /// Proven by a real 206. + pub ranges: bool, + pub version: Validators, + /// Safe to use as a file name. + pub name: String, + pub mime: Option, + /// The whole file, already on its way: the server sent it instead of a range. Use it, or drop it to hang up. + pub body: Option, +} + +/// Asks for the first byte. A server without ranges answers with the file itself, which spares links that work only once. +pub async fn probe(client: &Client, source: &Source, stop: &mut Stop) -> Result { + let mut response = source.get(client, Some("bytes=0-0".into()), None, stop).await?; + let empty = response.status() == StatusCode::RANGE_NOT_SATISFIABLE && unsatisfied_total(response.headers()) == Some(0); + if response.status() == StatusCode::RANGE_NOT_SATISFIABLE && !empty { + // It can't stand ranges at all. + response = source.get(client, None, None, stop).await?; + } + let headers = response.headers(); + let (ranges, size) = match response.status() { + _ if empty => (false, Some(0)), + StatusCode::PARTIAL_CONTENT => { + let range = ContentRange::of(headers).filter(|r| r.first == 0 && r.last == 0); + let range = range.ok_or_else(|| Error::BadReply("another range than asked for".into()))?; + check_length(headers, range)?; + // Without a total the end of a part can't be checked. + (range.total.is_some(), range.total) + } + StatusCode::OK => (false, content_length(headers)), + _ => return Err(status_error(&response)), + }; + let url = response.url().clone(); + check_encoding(headers, &url)?; + let mut probe = Probe { + ranges, + version: Validators::of(headers, size), + name: name::pick(source, &url, headers), + mime: name::mime(headers), + body: None, + url, + }; + if response.status() == StatusCode::OK { + probe.body = Some(response); + } else if content_length(headers) == Some(1) { + // Read to its end, the connection can serve the first part. + let _ = tokio::time::timeout(Duration::from_secs(1), response.bytes()).await; + } + Ok(probe) +} + +/// Content-Length must fit the range, if both are there. +pub(super) fn check_length(headers: &HeaderMap, range: ContentRange) -> Result<()> { + match content_length(headers) { + Some(n) if n != range.len() => Err(Error::BadReply(format!("Content-Length {n} for a range of {}", range.len()))), + _ => Ok(()), + } +} diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index cb3e8ec..9e1bfdd 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1,7 +1,10 @@ //! Medlar's engine, limits, queues, store and settings. No UI code. +pub mod disk; +pub mod http; pub mod logging; pub mod model; +pub mod part; pub mod paths; pub mod redact; pub mod settings; diff --git a/crates/core/src/part.rs b/crates/core/src/part.rs new file mode 100644 index 0000000..695432c --- /dev/null +++ b/crates/core/src/part.rs @@ -0,0 +1,100 @@ +//! A range of a file while it is being downloaded. + +use crate::model::Part; +use std::sync::{Arc, Mutex}; + +/// Shared by the task that fills it, the journal and whoever draws it. +#[derive(Debug)] +pub struct LivePart(Mutex); + +#[derive(Debug)] +struct Inner { + part: Part, + /// Bytes now on their way to the disk. `part.done` counts only those that arrived. + claimed: u64, +} + +impl LivePart { + pub fn new(part: Part) -> Arc { + Arc::new(LivePart(Mutex::new(Inner { part, claimed: 0 }))) + } + + pub fn get(&self) -> Part { + self.0.lock().unwrap().part + } + + pub fn finished(&self) -> bool { + self.remaining() == Some(0) + } + + /// Bytes still to write. None when the end is unknown. + pub fn remaining(&self) -> Option { + let p = self.get(); + p.end.map(|end| end - p.start - p.done) + } + + /// Moves the end. Refused when it would cut bytes already written or being written. + pub fn set_end(&self, end: u64) -> bool { + let mut i = self.0.lock().unwrap(); + let ok = end >= i.part.start + i.part.done + i.claimed; + if ok { + i.part.end = Some(end); + } + ok + } + + /// Reserves the next bytes for writing: where they go, and how many of `n` still belong to this part. One writer at a time. + pub(crate) fn claim(&self, n: u64) -> (u64, u64) { + let mut i = self.0.lock().unwrap(); + let at = i.part.start + i.part.done; + i.claimed = i.part.end.map_or(n, |end| n.min(end - at)); + (at, i.claimed) + } + + /// The claimed bytes are written (or not). + pub(crate) fn settle(&self, written: bool) { + let mut i = self.0.lock().unwrap(); + if written { + i.part.done += i.claimed; + } + i.claimed = 0; + } +} + +/// `size` bytes in up to `count` ranges of about the same length, none shorter than `min` unless it is the only one. +pub fn split(size: u64, count: u32, min: u64) -> Vec { + let count = (size / min.max(1)).clamp(1, u64::from(count.max(1))); + let edge = |i: u64| (u128::from(size) * u128::from(i) / u128::from(count)) as u64; + (0..count).map(|i| Part { start: edge(i), end: Some(edge(i + 1)), done: 0 }).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn split_covers_everything_once() { + for (size, count, min) in [(0, 4, 10), (1, 4, 10), (39, 4, 10), (1000, 7, 1), (u64::MAX / 2, 32, 1 << 20), (5, 0, 0)] { + let parts = split(size, count, min); + assert!(parts.len() <= count.max(1) as usize); + assert_eq!(parts[0].start, 0); + assert_eq!(parts.last().unwrap().end, Some(size)); + assert!(parts.windows(2).all(|w| w[0].end == Some(w[1].start))); + } + assert_eq!(split(39, 4, 10).len(), 3); + } + + #[test] + fn the_end_never_cuts_written_bytes() { + let part = LivePart::new(Part { start: 100, end: Some(200), done: 10 }); + assert_eq!(part.claim(30), (110, 30)); + assert!(!part.set_end(139)); + assert!(part.set_end(140)); + part.settle(true); + assert!(part.finished()); + assert!(part.set_end(150)); + assert_eq!(part.claim(30), (140, 10)); + part.settle(false); + assert_eq!(part.remaining(), Some(10)); + } +} diff --git a/crates/core/tests/http.rs b/crates/core/tests/http.rs new file mode 100644 index 0000000..e0af35e --- /dev/null +++ b/crates/core/tests/http.rs @@ -0,0 +1,482 @@ +//! Downloads against the test server, through every fault, and killed at random moments. + +use medlar_core::disk::{self, PartialFile, partial_path}; +use medlar_core::http::*; +use medlar_core::model::{Part, Task, TaskId}; +use medlar_core::part::LivePart; +use medlar_core::store::Store; +use medlar_testserver::{Faults, TestServer, expected}; +use reqwest::Client; +use sha2::{Digest, Sha256}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime}; +use tokio::sync::watch; + +const MB: u64 = 1 << 20; + +fn sha(data: &[u8]) -> Vec { + Sha256::digest(data).to_vec() +} + +struct Bench { + server: TestServer, + dir: tempfile::TempDir, + store: Arc, + client: Client, + options: Options, +} + +impl Bench { + async fn new() -> Bench { + Bench::with(TestServer::start().await) + } + + fn with(server: TestServer) -> Bench { + let dir = tempfile::tempdir().unwrap(); + let store = Arc::new(Store::open(&dir.path().join("medlar.db")).unwrap()); + let only_certs = server.cert_der().into_iter().collect(); + let client = client(&ClientOptions { idle_timeout: Duration::from_millis(1500), only_certs, ..ClientOptions::default() }).unwrap(); + let options = Options { parts: 4, min_part: 64 * 1024, checkpoint: Duration::from_millis(20) }; + Bench { server, dir, store, client, options } + } + + fn folder(&self) -> PathBuf { + self.dir.path().join("files") + } + + fn add(&self, path: &str) -> TaskId { + self.store.add_task(Task { url: self.server.url(path), folder: self.folder(), ..Task::default() }).unwrap() + } + + async fn run_until(&self, id: TaskId, stop: Stop) -> Result { + let source = Source::new(&self.store.task(id).unwrap().url).unwrap(); + download(&self.client, &self.store, id, source, &self.options, stop).await + } + + async fn run(&self, id: TaskId) -> Result { + let (_keep, stop) = watch::channel(false); + self.run_until(id, stop).await + } + + /// Downloads a part of it: until every part has something recorded. + async fn half(&self, id: TaskId) { + let (halt, stop) = watch::channel(false); + let watching = async { + while self.store.parts(id).unwrap().iter().any(|p| p.done == 0) || self.store.parts(id).unwrap().is_empty() { + tokio::time::sleep(Duration::from_millis(5)).await; + } + halt.send_replace(true); + }; + let (result, ()) = tokio::join!(self.run_until(id, stop), watching); + assert!(matches!(result, Err(Error::Stopped)), "{result:?}"); + assert!(self.partial(id).exists()); + } + + fn partial(&self, id: TaskId) -> PathBuf { + let task = self.store.task(id).unwrap(); + partial_path(&task.folder, &task.name) + } + + fn check(&self, path: &Path, seed: u64, len: u64) { + let data = std::fs::read(path).unwrap(); + assert_eq!(data.len() as u64, len); + assert_eq!(sha(&data), sha(&expected(seed, 0, len as usize))); + let left = std::fs::read_dir(self.folder()).unwrap().filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().ends_with(disk::ENDING)); + assert_eq!(left.count(), 0, "a partial file is left"); + } + + fn sent(&self, path: &str) -> u64 { + self.server.requests_for(path).iter().map(|r| r.sent).sum() + } +} + +fn slow(per_connection: u64) -> Faults { + Faults { throttle_conn: Some(per_connection), ..Faults::default() } +} + +#[tokio::test(flavor = "multi_thread")] +async fn four_ranges_make_one_file() { + let b = Bench::new().await; + let id = b.add("/data/1/5000003/a.bin"); + let path = b.run(id).await.unwrap(); + assert_eq!(path, b.folder().join("a.bin")); + b.check(&path, 1, 5_000_003); + let requests = b.server.requests_for("/data/1/5000003/a.bin"); + assert_eq!(requests.len(), 5, "a probe and four ranges"); + for r in &requests { + assert_eq!((r.status, r.header("accept-encoding")), (206, Some("identity"))); + assert!(r.header("referer").is_none()); + } + assert!(requests[1..].iter().all(|r| r.header("if-range").is_some())); + assert_eq!(b.sent("/data/1/5000003/a.bin"), 5_000_004); + let task = b.store.task(id).unwrap(); + assert_eq!((task.size, task.downloaded, task.name.as_str()), (Some(5_000_003), 5_000_003, "a.bin")); + // Asked again after a crash that came before the state was saved. + assert_eq!(b.run(id).await.unwrap(), path); +} + +#[tokio::test(flavor = "multi_thread")] +async fn https_and_small_files() { + let b = Bench::with(TestServer::start_tls().await); + let path = b.run(b.add("/data/2/3m/tls.bin")).await.unwrap(); + b.check(&path, 2, 3 * MB); + for len in [0, 1, 2, 65_537] { + let path = b.run(b.add(&format!("/data/3/{len}/small{len}"))).await.unwrap(); + b.check(&path, 3, len); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn probe_finds_everything() { + let b = Bench::new().await; + let (_keep, mut stop) = watch::channel(false); + let mut look = async |path: &str| probe(&b.client, &Source::new(&b.server.url(path)).unwrap(), &mut stop).await; + let p = look("/redirect/3?to=/data/4/1000/end.zip").await.unwrap(); + assert!(p.url.path().ends_with("/data/4/1000/end.zip")); + assert_eq!((p.ranges, p.version.size, p.name.as_str(), p.body.is_some()), (true, Some(1000), "end.zip", false)); + assert!(p.version.etag.is_some() && p.version.last_modified.is_some() && p.mime.is_some()); + let p = look("/data/4/1000/x.bin?ignore_range=1").await.unwrap(); + assert_eq!((p.ranges, p.version.size, p.body.is_some()), (false, Some(1000), true)); + let p = look("/data/4/1000/x.bin?nolen=1").await.unwrap(); + assert_eq!((p.ranges, p.version.size), (false, None)); + assert_eq!(look("/data/4/1000/x.bin?disp=evil").await.unwrap().name, "passwd"); + assert_eq!(look("/data/4/1000/x.bin?disp=dotfile").await.unwrap().name, "hidden.bin"); + assert_ne!(look("/data/4/1000/x.bin?disp=both").await.unwrap().name, "fallback.bin"); + assert!(matches!(look("/redirect/loop").await, Err(Error::Net(e)) if e.is_redirect())); + assert!(matches!(look("/status/404").await, Err(Error::Status { code: 404, .. }))); + let busy = look("/data/4/1000/x.bin?status=429&retry_after=7").await; + assert!(matches!(busy, Err(Error::Status { code: 429, retry_after: Some(d) }) if d.as_secs() == 7)); +} + +#[tokio::test(flavor = "multi_thread")] +async fn cookies_do_not_follow_a_redirect_to_another_site() { + let (b, other) = (Bench::new().await, TestServer::start().await); + let id = b.add(&format!("/redirect/1?to={}", other.url("/data/1/300k/c.bin"))); + let source = Source::new(&b.store.task(id).unwrap().url).unwrap().with_headers(&[("Cookie".into(), "secret=1".into())]); + let (_keep, stop) = watch::channel(false); + let path = download(&b.client, &b.store, id, source, &b.options, stop).await.unwrap(); + b.check(&path, 1, 300 * 1024); + assert!(b.server.log().iter().all(|r| r.header("cookie") == Some("secret=1"))); + assert!(!other.log().is_empty() && other.log().iter().all(|r| r.header("cookie").is_none())); +} + +#[tokio::test(flavor = "multi_thread")] +async fn stop_and_continue() { + let b = Bench::new().await; + let path = "/data/5/8m/s.bin"; + b.server.set_faults(path, slow(4 * MB)); + let id = b.add(path); + b.half(id).await; + let had = b.store.task(id).unwrap().downloaded; + assert!(had > 0); + b.server.clear_all_faults(); + b.server.clear_log(); + let done = b.run(id).await.unwrap(); + b.check(&done, 5, 8 * MB); + assert!(b.sent(path) <= 8 * MB - had + 4 * OVERLAP + 1, "finished bytes were loaded again"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_broken_connection_keeps_what_came() { + for fault in [ + Faults { cut_after: Some(700_000), ..Faults::default() }, + Faults { reset_after: Some(700_000), ..Faults::default() }, + Faults { stall_after: Some(700_000), ..Faults::default() }, + ] { + let b = Bench::new().await; + let path = "/data/6/8m/f.bin"; + let id = b.add(path); + b.server.set_faults(path, fault.clone()); + let mut rounds = 0; + let done = loop { + let before = b.store.task(id).unwrap().downloaded; + match b.run(id).await { + Ok(done) => break done, + Err(Error::Cut { .. }) => {} + Err(Error::Net(e)) if e.is_timeout() && fault.stall_after.is_some() => {} + Err(e) => panic!("{e:?}"), + } + assert!(b.store.task(id).unwrap().downloaded > before, "nothing gained in round {rounds}"); + rounds += 1; + }; + assert!(rounds > 0); + b.check(&done, 6, 8 * MB); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_changed_file_stops() { + // With validators; without any, where only the bytes differ; and with a new length. + for (query, swap) in [("", "/data/7/8m/v.bin"), ("?etag=0", "/data/7/8m/v.bin"), ("?etag=0&lm=0", "/data/99/8m/v.bin"), ("", "/data/7/9m/v.bin")] { + let b = Bench::new().await; + let path = "/data/7/8m/v.bin"; + b.server.set_faults(path, slow(4 * MB)); + let id = b.add(&format!("{path}{query}")); + b.half(id).await; + b.server.set_faults(path, Faults { version_after_requests: (path == swap).then_some(0), ..Faults::default() }); + let mut task = b.store.task(id).unwrap(); + task.url = b.server.url(&format!("{swap}{query}")); + b.store.save_task(task).unwrap(); + let before = std::fs::read(b.partial(id)).unwrap(); + let result = b.run(id).await; + assert!(matches!(result, Err(Error::Changed)), "{query} {swap}: {result:?}"); + let (after, parts) = (std::fs::read(b.partial(id)).unwrap(), b.store.parts(id).unwrap()); + for p in parts { + let range = p.start as usize..(p.start + p.done) as usize; + assert!(before[range.clone()] == after[range], "finished bytes were touched"); + } + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_changed_file_is_seen_when_only_whole_parts_are_there() { + let b = Bench::new().await; + let path = "/data/8/4m/w.bin?etag=0&lm=0"; + let id = b.add(path); + b.server.set_faults("/data/8/4m/w.bin", slow(4 * MB)); + b.half(id).await; + let half = [Part { start: 0, end: Some(2 * MB), done: 2 * MB }, Part { start: 2 * MB, end: Some(4 * MB), done: 0 }]; + std::fs::write(b.partial(id), expected(8, 0, 4 * MB as usize)).unwrap(); + b.store.save_parts(id, half.to_vec()).unwrap(); + b.server.set_faults("/data/8/4m/w.bin", Faults { version_after_requests: Some(0), ..Faults::default() }); + assert!(matches!(b.run(id).await, Err(Error::Changed))); + b.server.clear_all_faults(); + let done = b.run(id).await.unwrap(); + b.check(&done, 8, 4 * MB); +} + +#[tokio::test(flavor = "multi_thread")] +async fn servers_without_ranges_or_length() { + let b = Bench::new().await; + for query in ["ignore_range=1", "nolen=1", "chunked=1", "weak=1", "etag=0&lm=0", "status=416&status_count=1", "wrong_length=0"] { + b.server.clear_log(); + let path = format!("/data/9/2m/q{}.bin", query.len()); + let done = b.run(b.add(&format!("{path}?{query}"))).await.unwrap_or_else(|e| panic!("{query}: {e:?}")); + b.check(&done, 9, 2 * MB); + if query == "ignore_range=1" { + assert_eq!(b.server.requests_for(&path).len(), 1, "the probe's reply is the download"); + } + std::fs::remove_file(done).unwrap(); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn no_ranges_starts_over() { + let b = Bench::new().await; + let path = "/data/10/4m/o.bin"; + let id = b.add(&format!("{path}?ignore_range=1")); + b.server.set_faults(path, slow(2 * MB)); + b.half(id).await; + b.server.clear_all_faults(); + let done = b.run(id).await.unwrap(); + b.check(&done, 10, 4 * MB); + + // Started without ranges, and now there are some: goes on. + let id = b.add(path); + b.server.set_faults(path, Faults { ignore_range: true, throttle_conn: Some(2 * MB), ..Faults::default() }); + b.half(id).await; + b.server.clear_all_faults(); + b.server.clear_log(); + let done = b.run(id).await.unwrap(); + assert_eq!(done, b.folder().join("o (1).bin")); + b.check(&done, 10, 4 * MB); + assert!(b.sent(path) < 4 * MB); + + // Started with ranges, and now there are none: nothing is thrown away. + let path = "/data/10/8m/r.bin"; + let id = b.add(path); + b.server.set_faults(path, slow(4 * MB)); + b.half(id).await; + b.server.set_faults(path, Faults { ignore_range: true, ..Faults::default() }); + let had = b.store.task(id).unwrap().downloaded; + assert!(matches!(b.run(id).await, Err(Error::NoResume))); + assert_eq!(b.store.task(id).unwrap().downloaded, had); + b.server.clear_all_faults(); + let done = b.run(id).await.unwrap(); + b.check(&done, 10, 8 * MB); +} + +#[tokio::test(flavor = "multi_thread")] +async fn lying_servers_get_an_error() { + let b = Bench::new().await; + let one = |query: &str| b.add(&format!("/data/11/2m/l.bin?{query}")); + for (query, what) in [ + ("wrong_length=9", "BadReply"), + ("wrong_length=-1", "BadReply"), + ("wrong_length=9&ignore_range=1", "Cut"), + ("cut_after=1000000&ignore_range=1", "Cut"), + ("cut_after=1000000&chunked=1", "Cut"), + ("gzip=1", "Encoded"), + ("gzip=1&ignore_range=1", "Encoded"), + ] { + let error = format!("{:?}", b.run(one(query)).await.expect_err(query)); + assert!(error.starts_with(what), "{query}: {error}"); + assert!(!b.folder().join("l.bin").exists()); + } + // The classic mistake: a .gz file announced as packed. + let done = b.run(b.add("/data/11/2m/l.tar.gz?gzip=1")).await.unwrap(); + assert_eq!(sha(&std::fs::read(done).unwrap()), sha(&expected(11, 0, 2 * MB as usize))); +} + +/// One part of a file whose probe promised ranges. +async fn one_part(b: &Bench, path: &str, done: u64) -> (Result<()>, Vec, Part) { + let (_keep, mut stop) = watch::channel(false); + let source = Source::new(&b.server.url(path)).unwrap(); + let p = probe(&b.client, &source, &mut stop).await.unwrap(); + let link = Link { client: b.client.clone(), source, ranges: true, version: p.version }; + let (file, name) = PartialFile::create(&b.folder(), "part").unwrap(); + std::fs::write(partial_path(&b.folder(), &name), vec![0; 200_000]).unwrap(); + let part = LivePart::new(Part { start: 100_000, end: Some(200_000), done: 0 }); + if done > 0 { + file.write_at(expected(12, 100_000, done as usize), done as usize, 100_000).await.unwrap(); + part.set_end(200_000); + } + let part = if done > 0 { LivePart::new(Part { done, ..part.get() }) } else { part }; + let result = fetch(&link, &part, &file, None, stop).await; + (result, std::fs::read(file.path()).unwrap(), part.get()) +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_whole_file_is_never_written_at_an_offset() { + let b = Bench::new().await; + let path = "/data/12/200000/p.bin"; + let (result, data, part) = one_part(&b, path, 50_000).await; + result.unwrap(); + assert_eq!((part.done, sha(&data[100_000..])), (100_000, sha(&expected(12, 100_000, 100_000)))); + assert!(data[..100_000].iter().all(|b| *b == 0)); + + for ignored in [Faults { ignore_range: true, ..Faults::default() }, Faults { version_after_requests: Some(0), ..Faults::default() }] { + let changed = ignored.version_after_requests.is_some(); + let bytes_only = format!("{path}?etag=0&lm=0"); + b.server.set_faults(path, ignored); + let (result, data, part) = one_part(&b, &bytes_only, 50_000).await; + match result { + Err(Error::Changed) if changed => {} + Err(Error::RangeIgnored) if !changed => {} + other => panic!("{other:?}"), + } + assert_eq!(part.done, 50_000); + assert!(data[..100_000].iter().chain(&data[150_000..]).all(|b| *b == 0)); + } +} + +#[tokio::test(flavor = "multi_thread")] +async fn nothing_is_overwritten() { + let b = Bench::new().await; + std::fs::create_dir_all(b.folder()).unwrap(); + std::fs::write(b.folder().join("n.bin"), "mine").unwrap(); + let path = "/data/13/2m/n.bin"; + b.server.set_faults(path, slow(4 * MB)); + let (one, two) = (b.add(path), b.add(path)); + let (one, two) = tokio::join!(b.run(one), b.run(two)); + let (one, two) = (one.unwrap(), two.unwrap()); + assert_ne!(one, two); + for done in [one, two] { + b.check(&done, 13, 2 * MB); + } + assert_eq!(std::fs::read(b.folder().join("n.bin")).unwrap(), b"mine"); +} + +#[tokio::test(flavor = "multi_thread")] +async fn a_file_larger_than_the_disk_is_refused_early() { + let b = Bench::new().await; + let id = b.add("/data/14/4000t/huge.bin"); + let result = b.run(id).await; + assert!(matches!(result, Err(Error::Disk(disk::Error::NoSpace { .. }))), "{result:?}"); + assert_eq!(std::fs::metadata(b.partial(id)).unwrap().len(), 0); + // And again, now that the task has begun. + assert!(matches!(b.run(id).await, Err(Error::Disk(disk::Error::NoSpace { .. })))); +} + +#[tokio::test(flavor = "multi_thread")] +async fn the_last_steps_survive_a_crash() { + let b = Bench::new().await; + let path = "/data/15/8m/z.bin"; + b.server.set_faults(path, slow(4 * MB)); + let id = b.add(path); + b.half(id).await; + // Everything arrived and was recorded, but the file was not renamed yet. Needs no server. + std::fs::write(b.partial(id), expected(15, 0, 8 * MB as usize)).unwrap(); + let parts = b.store.parts(id).unwrap().into_iter().map(|p| Part { done: p.end.unwrap() - p.start, ..p }).collect(); + b.store.save_parts(id, parts).unwrap(); + b.server.set_faults(path, Faults::status(404)); + let done = b.run(id).await.unwrap(); + b.check(&done, 15, 8 * MB); +} + +const CHILD: &str = "MEDLAR_HTTP_KILL_TEST"; + +/// Not a test: the process that gets killed. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "started by kills_lose_nothing"] +async fn child() { + let Ok(args) = std::env::var(CHILD) else { return }; + let (id, db) = args.split_once(' ').unwrap(); + let (id, store) = (id.parse().unwrap(), Arc::new(Store::open(Path::new(db)).unwrap())); + let options = Options { parts: 4, min_part: 64 * 1024, checkpoint: Duration::from_millis(15) }; + let source = Source::new(&store.task(id).unwrap().url).unwrap(); + let (_keep, stop) = watch::channel(false); + download(&client(&ClientOptions::default()).unwrap(), &store, id, source, &options, stop).await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn kills_lose_nothing() { + const LEN: u64 = 24 * MB; + const KILLS: u32 = 50; + let b = Bench::new().await; + let path = "/data/16/24m/k.bin"; + b.server.set_faults(path, slow(6 * MB)); + let want = expected(16, 0, LEN as usize); + let mut seed = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos() as u64 | 1; + println!("seed {seed}"); + let (mut kills, mut files, mut kept) = (0, 0, 0); + while kills < KILLS || files == 0 { + let id = b.add(path); + let mut last = 0; + loop { + let mut child = Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "child", "--ignored"]) + .env(CHILD, format!("{id} {}", b.dir.path().join("medlar.db").display())) + .stdout(Stdio::null()) + .spawn() + .unwrap(); + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + let end = Instant::now() + Duration::from_millis(10 + seed % 350); + let exit = loop { + if let Some(exit) = child.try_wait().unwrap() { + break Some(exit); + } + if kills < KILLS && Instant::now() >= end { + child.kill().unwrap(); + child.wait().unwrap(); + break None; + } + tokio::time::sleep(Duration::from_millis(1)).await; + }; + if let Some(exit) = exit { + assert!(exit.success()); + break; + } + kills += 1; + let (task, parts) = (b.store.task(id).unwrap(), b.store.parts(id).unwrap()); + assert!(task.downloaded >= last, "recorded bytes were lost"); + kept += task.downloaded - last; + last = task.downloaded; + let partial = b.partial(id); + let on_disk = std::fs::read(if partial.exists() { partial } else { b.folder().join(&task.name) }).unwrap_or_default(); + for p in parts.iter().filter(|p| p.done > 0) { + let range = p.start as usize..(p.start + p.done) as usize; + assert!(on_disk[range.clone()] == want[range], "the record is ahead of the data (seed {seed}, kill {kills})"); + } + } + let done = b.folder().join(&b.store.task(id).unwrap().name); + b.check(&done, 16, LEN); + files += 1; + } + println!("{kills} kills, {files} files, {} MB kept over kills", kept / MB); + assert!(kept > 0, "no kill came in the middle"); +} diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index e740237..814bfa9 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -18,3 +18,6 @@ - D-014 — 2026-11-24 — Work happens on the branch `claude/caveman-orchestrate-run-41d3a3`; the orchestrator fast-forwards `main` (local and `origin`) after each validated category. Sessions push only the branch. — User said yes to merging after each category. — all - D-015 — 2026-11-24 — SQLite and settings hold only keyring item names; the store refuses cookie/authorization headers and `user:password@` in links, mirrors and proxies. Callers split them off first. Tokens in a link's query stay in the link. — Secrets must not sit in plain files. — 02, 04, 05 - D-016 — 2026-11-24 — Up to three plans run at once when they do not depend on each other and their "files touched" do not overlap; waiting sessions may be prepared out of INDEX order for this. All share one target folder, so cargo queues builds by itself. Replaces the "at most two" limit in ORCHESTRATOR.md. — User asked for three at once. — all +- D-017 — 2026-11-24 — HTTP client is reqwest 0.13.5 (pinned exactly), rustls with ring and the system certificates, HTTP/1.1 only, `Accept-Encoding: identity`, no decompression, no Referer of its own, its retries off, ≤ 10 redirects, 20 s connect and 30 s idle timeout, no proxy from the environment. Segments go to the final link; cookies and logins are dropped when its origin differs. — Docs of 0.13.5 checked: `http1_only`, `redirect::Policy`, `connect_timeout`, `read_timeout` (per read), `retry::never`. — 02, 05, 06 +- D-018 — 2026-11-24 — HTTP/1.1 everywhere; no HTTP/2 or HTTP/3 (1.14), so reqwest's `http2` feature stays off. — Measured over TLS with netem, mean MB/s of HTTP/1.1 ×1, ×4, ×8 and HTTP/2 ×1: loopback 437, 950, 899, 306; 20 ms 8.7, 8.5, 8.9, 8.6; 20 ms with 0.1 % loss (15 runs) 7.6, 6.0, 7.3, 6.6; 50 ms with 0.5 % loss 1.7, 1.8, 3.2, 0.7. HTTP/2 never won. HTTP/3 was not measured: reqwest's needs an unstable build flag and another TLS stack (quinn). — 02 +- D-019 — 2026-11-24 — A stored part with `end: None` means the server had no ranges: it starts over on resume unless the server has ranges by then. A part with an end never starts over by itself (`Error::NoResume`, `Error::Changed` instead). The record of parts is written only after `fdatasync` of the data it names. — No state loses finished bytes. — 02 diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 0851acd..d1cb46e 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -22,5 +22,16 @@ Verified: `nice cargo test -j 2 -p medlar-testserver` green (44 tests, ~1 s, one - Proxies: `proxy::Proxy::start_http(auth)` / `start_socks5(auth)`; `seen()` lists kind, target, credentials, allowed; they connect only to loopback or names set with `map_host`. Not done: BLAKE3 sidecar, HTTP/2, a real gzip body, FTP/SFTP servers (their plans). +## S004 — HTTP core with resume and crash-safe files (2026-11-24) +Done: `core::http` (client, probe, names, fetch, download), `core::disk` (`PartialFile`), `core::part` (`LivePart`, `split`). Choices: D-017 to D-019. +Verified: `nice cargo test -j 2 -p medlar-core` green (47 unit, 16 http, on tmpfs and btrfs); 50 kills at random moments × 4 runs, SHA-256 equal; clippy clean for the new code. +- `http::download(client, store, id, source, options, stop)`: start or continue a task in fixed ranges, returns the finished path. It never sets the task's state. S005 replaces its scheduling; `start`/`resume`/`checkpoint`/`finish` in `download.rs` are the pieces to keep. +- `http::fetch(link, part, file, body, stop)`: one part, one connection. `stop` is a `watch` of bool; stop it, don't drop it (it writes its 512 KiB buffer first). On resume it reloads 4096 bytes and compares. `http::compare` checks any finished range (for S008). +- `LivePart`: `get()`, `remaining()`, `set_end(x)` (false if it would cut bytes written or on their way): a split is `set_end(mid)` on the old part, then a new part `mid..end`. +- `http::probe` gives size, proven ranges, validators, safe name, final link, and the live reply when there are no ranges (pass it to `fetch`, or drop it). +- `disk::PartialFile`: `create` (free name, locked), `reopen`, `reserve`, `write_at`, `read_at`, `sync`, `finish` (never replaces a file). It is `Busy` for a second process. +- `http::Error` has no user text: S007 maps it. `Error::Status` carries Retry-After for S006. Build `Source` with cookies and logins from the keyring; they are dropped on another origin. +Not done: a Content-Length smaller than the real body, on a server without ranges, can't be seen (HTTP ends the body there). A body without any length over plain HTTP can be cut unseen. The power-cut order is by construction, not tested. + ## Later -