Medlar/crates/core/src/adopt.rs
2026-11-25 05:50:55 -06:00

339 lines
13 KiB
Rust

//! Taking over a file that another program left unfinished.
//!
//! `look` reads what is there, `check` compares it with a link, `Command::Adopt` copies it. The file itself is never touched.
//! Browsers fill a file from the start; aria2 keeps a list of its pieces next to it. Of anything else only the start counts,
//! as far as it stands the comparison with the server.
use crate::http::{Client, Error, Link, Result, Source, Stop, same_bytes};
use crate::model::{Part, Task};
use crate::relink::{Checked, NewLink, Reason, probed, read, runs, samples, total};
use crate::{disk, http};
use std::fs::File;
use std::io::{self, ErrorKind, Read};
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Looked at in one piece for being empty.
const BLOCK: u64 = 4096;
/// Empty stretches the server is asked about.
const DOUBTS: usize = 64;
/// Endings of unfinished files, and where the name comes before them.
const ENDINGS: &[&str] = &[".part", ".crdownload", ".opdownload", ".partial", ".download", disk::ENDING];
const ARIA2: &str = ".aria2";
/// Blocks inside aria2's unfinished pieces.
const ARIA2_BLOCK: u64 = 16 * 1024;
/// More than any control file of a sensible download.
const ARIA2_MAX: u64 = 64 << 20;
#[derive(Debug, Clone, PartialEq)]
pub struct Partial {
pub path: PathBuf,
/// As far as the file's own name tells.
pub name: Option<String>,
/// What seems to be finished.
pub runs: Vec<Range<u64>>,
pub total: Option<u64>,
/// `runs` come from the other program's own list.
pub listed: bool,
}
impl Partial {
pub fn bytes(&self) -> u64 {
total(&self.runs)
}
}
/// An unfinished file and the link it can go on from. `partial.runs` holds only what stood the comparison.
#[derive(Debug, Clone)]
pub struct Found {
pub partial: Partial,
pub checked: Checked,
}
impl Found {
pub(crate) fn parts(&self) -> Vec<Part> {
parts(&self.partial.runs, self.checked.size.unwrap_or(0))
}
}
/// Blocks. Takes the file or its list.
pub fn look(path: &Path) -> io::Result<Partial> {
let text = path.to_string_lossy();
if let Some(data) = text.strip_suffix(ARIA2)
&& path.with_file_name(Path::new(data).file_name().unwrap_or_default()).is_file()
{
return look(Path::new(data));
}
let meta = path.symlink_metadata()?;
if !meta.is_file() {
return Err(ErrorKind::InvalidInput.into());
}
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
// Chrome's, before it knows the name.
let stem = ENDINGS.iter().find_map(|e| name.strip_suffix(e)).unwrap_or(&name);
let known = Some(stem).filter(|s| !s.starts_with("Unconfirmed ")).and_then(http::safe_name);
let start = std::iter::once(0..meta.len()).collect();
let mut partial = Partial { path: path.into(), name: known, runs: start, total: None, listed: false };
let mut list = path.as_os_str().to_os_string();
list.push(ARIA2);
if let Some((runs, total)) = aria2(Path::new(&list)) {
let len = meta.len();
partial.runs = runs.into_iter().map(|r| r.start.min(len)..r.end.min(len)).collect();
(partial.total, partial.listed) = (Some(total), true);
}
partial.runs.retain(|r| !r.is_empty());
Ok(partial)
}
/// The finished ranges and the size in aria2's control file, as its manual describes it ("Control file (*.aria2) format").
/// None for anything else, such as a torrent's.
fn aria2(path: &Path) -> Option<(Vec<Range<u64>>, u64)> {
let mut file = File::open(path).ok()?;
if file.metadata().ok()?.len() > ARIA2_MAX {
return None;
}
let mut bytes = vec![];
file.read_to_end(&mut bytes).ok()?;
let mut rest = &bytes[..];
let mut take = |n: usize| -> Option<&[u8]> {
let (now, later) = rest.split_at_checked(n)?;
rest = later;
Some(now)
};
let int = |b: &[u8]| b.iter().fold(0u64, |n, b| n << 8 | u64::from(*b));
let (version, _extension, hash) = (int(take(2)?), take(4)?, int(take(4)?));
if version != 1 || hash != 0 {
return None;
}
let (piece, total, _upload, field) = (int(take(4)?), int(take(8)?), take(8)?, int(take(4)?));
if piece == 0 || total == 0 || field != total.div_ceil(piece).div_ceil(8) {
return None;
}
// The first bit is the highest one.
let set = |bits: &[u8], i: u64| bits.get((i / 8) as usize).is_some_and(|b| b & (0x80 >> (i % 8)) != 0);
let bits = take(field as usize)?;
let mut done: Vec<Range<u64>> =
(0..total.div_ceil(piece)).filter(|i| set(bits, *i)).map(|i| i * piece..((i + 1) * piece).min(total)).collect();
for _ in 0..int(take(4)?) {
let (index, len, field) = (int(take(4)?), int(take(4)?), int(take(4)?));
let start = index.checked_mul(piece).filter(|s| s + len <= total)?;
let bits = take(field as usize)?;
let blocks = (0..len.div_ceil(ARIA2_BLOCK)).filter(|i| set(bits, *i));
done.extend(blocks.map(|i| start + i * ARIA2_BLOCK..start + ((i + 1) * ARIA2_BLOCK).min(len)));
}
let done: Vec<Part> = done.iter().map(|r| Part { start: r.start, end: Some(r.end), done: r.end - r.start }).collect();
Some((runs(&done), total))
}
/// Compares the file with what the link leads to. Reads only.
pub async fn check(client: &Client, partial: Partial, link: NewLink, source: Source, stop: &mut Stop) -> Result<Found> {
let task = Task { size: partial.total, name: partial.name.clone().unwrap_or_default(), url: link.url.clone(), ..Task::default() };
let (checked, opened) = probed(client, &task, link, source, partial.bytes(), stop).await?;
let mut found = Found { partial, checked };
let Some((server, _body)) = opened else { return Ok(found) };
let Some(size) = server.version.size.filter(|_| server.ranges) else {
found.checked.reason = Reason::NoRanges;
return Ok(found);
};
let Some(last) = found.partial.runs.last().map(|r| r.end) else {
found.checked.reason = Reason::Nothing;
return Ok(found);
};
if last > size {
found.checked.reason = Reason::Size { old: last, new: size };
return Ok(found);
}
let file = crate::relink::open(&found.partial.path).await?;
let mut eye = Eye { server: &server, file: &file, compared: 0, stop };
let result = if found.partial.listed { eye.listed(&found.partial.runs).await } else { eye.start(last).await };
found.checked.compared = eye.compared;
let ok = match result {
Ok(Some(runs)) => {
found.partial.runs = runs;
true
}
Ok(None) => false,
Err(Error::Changed) => {
found.checked.reason = Reason::OtherVersion;
return Ok(found);
}
Err(Error::RangeIgnored) => {
(found.checked.reason, found.checked.ranges) = (Reason::NoRanges, false);
return Ok(found);
}
Err(e) => return Err(e),
};
found.checked.here = found.partial.bytes();
found.checked.reason = match ok {
false => Reason::Bytes,
true if found.checked.compared < BLOCK => Reason::TooLittle,
true => Reason::Samples,
};
Ok(found)
}
struct Eye<'a> {
server: &'a Link,
file: &'a Arc<File>,
compared: u64,
stop: &'a mut Stop,
}
impl Eye<'_> {
async fn same(&mut self, range: Range<u64>) -> Result<bool> {
let known = read(self.file, range.clone()).await?;
self.compared += known.len() as u64;
same_bytes(self.server, &known, range.start, self.stop).await
}
/// All or nothing.
async fn listed(&mut self, runs: &[Range<u64>]) -> Result<Option<Vec<Range<u64>>>> {
for sample in samples(runs) {
if !self.same(sample).await? {
return Ok(None);
}
}
Ok(Some(runs.to_vec()))
}
/// How far the start of the file is the server's. The space may have been taken before it was filled.
async fn start(&mut self, len: u64) -> Result<Option<Vec<Range<u64>>>> {
let first = 0..len.min(BLOCK);
if !self.same(first.clone()).await? {
return Ok(None);
}
let file = self.file.clone();
let empty = disk::blocking(move || empty(&file, len)).await.map_err(disk::Error::Io)?;
let mut end = len;
for (i, hole) in empty.into_iter().enumerate() {
let ends = [hole.start..hole.start + BLOCK.min(hole.end - hole.start), hole.end.saturating_sub(BLOCK).max(hole.start)..hole.end];
if i >= DOUBTS || !self.same(ends[0].clone()).await? || !self.same(ends[1].clone()).await? {
end = hole.start;
break;
}
}
// Cut where the first of them differs, back to one that doesn't.
let mut good = first.end.min(end);
let mut looks = samples(std::slice::from_ref(&(0..end)));
looks.sort_by_key(|s| s.start);
for look in looks.into_iter().filter(|l| !l.is_empty()) {
if !self.same(look.clone()).await? {
end = good;
break;
}
good = look.end;
}
Ok((end > 0).then(|| std::iter::once(0..end).collect()))
}
}
/// Stretches of nothing but zeros, as whole blocks.
fn empty(file: &File, len: u64) -> io::Result<Vec<Range<u64>>> {
use std::os::unix::fs::FileExt;
let mut buf = vec![0; 1 << 20];
let (mut at, mut out) = (0, Vec::<Range<u64>>::new());
while at < len {
let n = (len - at).min(buf.len() as u64) as usize;
file.read_exact_at(&mut buf[..n], at)?;
for block in buf[..n].chunks(BLOCK as usize) {
let next = at + block.len() as u64;
if block.iter().all(|b| *b == 0) {
match out.last_mut() {
Some(last) if last.end == at => last.end = next,
_ => out.push(at..next),
}
}
at = next;
}
}
Ok(out)
}
/// The whole file as parts: each finished range with the gap after it.
fn parts(runs: &[Range<u64>], size: u64) -> Vec<Part> {
let mut out = vec![];
if let Some(first) = runs.first().filter(|r| r.start > 0) {
out.push(Part { start: 0, end: Some(first.start), done: 0 });
}
for (i, r) in runs.iter().enumerate() {
let end = runs.get(i + 1).map_or(size, |next| next.start);
out.push(Part { start: r.start, end: Some(end), done: r.end - r.start });
}
out
}
#[cfg(test)]
mod tests {
use super::*;
/// 10 pieces of 64 KiB, the last one short; pieces 0, 1 and 9 done, and two blocks of piece 4.
pub fn control(total: u64) -> Vec<u8> {
let mut b = vec![0, 1, 0, 0, 0, 0, 0, 0, 0, 0];
b.extend(65536u32.to_be_bytes());
b.extend(total.to_be_bytes());
b.extend(0u64.to_be_bytes());
b.extend(2u32.to_be_bytes());
b.extend([0b1100_0000, 0b0100_0000]);
b.extend(1u32.to_be_bytes());
b.extend(4u32.to_be_bytes());
b.extend(65536u32.to_be_bytes());
b.extend(1u32.to_be_bytes());
b.push(0b1010_0000);
b
}
#[test]
fn reads_the_list_of_aria2() {
let dir = tempfile::tempdir().unwrap();
let (file, list) = (dir.path().join("a.zip"), dir.path().join("a.zip.aria2"));
let total = 9 * 65536 + 100;
std::fs::write(&file, vec![1; total as usize]).unwrap();
std::fs::write(&list, control(total)).unwrap();
let found = look(&list).unwrap();
assert_eq!(found, look(&file).unwrap());
let k = 16384;
assert_eq!(found.runs, [0..8 * k, 16 * k..17 * k, 18 * k..19 * k, 36 * k..36 * k + 100]);
assert_eq!((found.total, found.listed, found.name.as_deref()), (Some(total), true, Some("a.zip")));
let parts = parts(&found.runs, total);
assert_eq!(parts.first(), Some(&Part { start: 0, end: Some(16 * k), done: 8 * k }));
assert!(parts.windows(2).all(|w| w[0].end == Some(w[1].start)) && parts.last().unwrap().end == Some(total));
// Broken ones count for nothing.
for cut in 0..control(total).len() {
std::fs::write(&list, &control(total)[..cut]).unwrap();
assert!(!look(&file).unwrap().listed, "{cut}");
}
for i in 0..control(total).len() {
let mut bad = control(total);
bad[i] ^= 0xff;
std::fs::write(&list, bad).unwrap();
let found = look(&file).unwrap();
assert!(found.runs.iter().all(|r| r.end <= total));
}
}
#[test]
fn names_of_unfinished_files() {
let dir = tempfile::tempdir().unwrap();
for (file, name) in [
("a.zip.part", Some("a.zip")),
("b.iso.crdownload", Some("b.iso")),
("Unconfirmed 1234.crdownload", None),
("c.tar.gz", Some("c.tar.gz")),
("d.bin.medlar", Some("d.bin")),
] {
let path = dir.path().join(file);
std::fs::write(&path, "xy").unwrap();
let found = look(&path).unwrap();
assert_eq!((found.name.as_deref(), &found.runs[..]), (name, std::slice::from_ref(&(0..2))), "{file}");
}
assert!(look(dir.path()).is_err() && look(&dir.path().join("none")).is_err());
}
#[test]
fn parts_begin_with_the_gap() {
let p = |start, end, done| Part { start, end: Some(end), done };
assert_eq!(parts(&[5..7, 9..10], 12), [p(0, 5, 0), p(5, 9, 2), p(9, 12, 1)]);
assert_eq!(parts(std::slice::from_ref(&(0..4)), 4), [p(0, 4, 4)]);
}
}