418 lines
17 KiB
Rust
418 lines
17 KiB
Rust
//! One part over one connection.
|
|
|
|
use super::probe::check_length;
|
|
use super::*;
|
|
use crate::disk::PartialFile;
|
|
use crate::limit::Flow;
|
|
use crate::part::LivePart;
|
|
use bytes::Bytes;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::Instant;
|
|
|
|
/// Finished bytes read again and compared when a part goes on.
|
|
pub const OVERLAP: u64 = 4096;
|
|
/// Finished bytes compared with a reply of another version of the same size, and on a farm when a part goes on.
|
|
pub const SAMPLE: u64 = 64 * 1024;
|
|
/// Replies asked for until one of the known version and one of another can be compared.
|
|
const PROOF_TRIES: u32 = 12;
|
|
/// 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,
|
|
/// The first version seen, kept for display and as the one the bytes on disk are of.
|
|
pub version: Validators,
|
|
/// Shared by clones.
|
|
pub farm: Arc<Farm>,
|
|
}
|
|
|
|
/// Servers behind one link that differ in dates and tags. Each other version counts once its bytes were shown to be the same.
|
|
#[derive(Debug, Default)]
|
|
pub struct Farm {
|
|
/// Known to be one from before.
|
|
stored: bool,
|
|
proven: Mutex<Vec<Validators>>,
|
|
/// Bytes of the known version at an offset, that other versions are compared with.
|
|
sample: Mutex<Option<(u64, Vec<u8>)>>,
|
|
}
|
|
|
|
impl Farm {
|
|
pub fn is(&self) -> bool {
|
|
self.stored || !self.proven.lock().unwrap().is_empty()
|
|
}
|
|
}
|
|
|
|
impl Link {
|
|
pub fn new(client: Client, source: Source, ranges: bool, version: Validators, farm: bool) -> Link {
|
|
Link { client, source, ranges, version, farm: Arc::new(Farm { stored: farm, ..Farm::default() }) }
|
|
}
|
|
|
|
pub fn farm(&self) -> bool {
|
|
self.farm.is()
|
|
}
|
|
|
|
/// Finished bytes at `at`, of the version the bytes here are of.
|
|
pub(super) fn known_sample(&self, at: u64, data: Vec<u8>) {
|
|
self.farm.sample.lock().unwrap().get_or_insert((at, data));
|
|
}
|
|
|
|
/// Of a farm's other server maybe, to be told by the bytes. Only over HTTP: other links have no farms.
|
|
pub(super) fn maybe_same(&self, version: &Validators) -> bool {
|
|
self.source.web() && self.version.maybe_same(version)
|
|
}
|
|
|
|
/// Of the version the bytes here are of, or of one shown to have the same bytes.
|
|
fn sure(&self, version: &Validators) -> bool {
|
|
self.version.same_file(version) || self.farm.proven.lock().unwrap().iter().any(|p| p == version)
|
|
}
|
|
|
|
/// `version` has the same bytes as the known one.
|
|
fn proven(&self, version: Validators) {
|
|
let mut proven = self.farm.proven.lock().unwrap();
|
|
if !proven.contains(&version) {
|
|
log::info!("{}: another server has the same bytes ({:?}, {:?})", self.source.url, version.etag, version.last_modified);
|
|
proven.push(version);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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<Response>, stop: Stop) -> Result<()> {
|
|
fetch_within(link, part, file, body, &Flow::free(), stop).await
|
|
}
|
|
|
|
/// The same within limits of speed.
|
|
pub(super) async fn fetch_within(
|
|
link: &Link,
|
|
part: &LivePart,
|
|
file: &PartialFile,
|
|
body: Option<Response>,
|
|
flow: &Flow,
|
|
mut stop: Stop,
|
|
) -> Result<()> {
|
|
if part.finished() {
|
|
return Ok(());
|
|
}
|
|
if *stop.borrow() {
|
|
return Err(Error::Stopped);
|
|
}
|
|
let (mut response, mut known, mut unsure) = if link.ranges {
|
|
range(link, part, file, &mut stop).await?
|
|
} else {
|
|
(whole(link, part, body, &mut stop).await?, vec![], None)
|
|
};
|
|
part.begin();
|
|
let mut buf = Vec::with_capacity(BUFFER);
|
|
let mut flushed = Instant::now();
|
|
// What came while the limits held the bytes before it.
|
|
let mut ahead = None;
|
|
loop {
|
|
let chunk = match ahead.take() {
|
|
Some(Err(_)) if *stop.borrow() => Err(Error::Stopped),
|
|
Some(chunk) => chunk,
|
|
None => tokio::select! {
|
|
biased;
|
|
_ = stopped(&mut stop) => Err(Error::Stopped),
|
|
chunk = next(&mut response, part, link) => chunk,
|
|
},
|
|
};
|
|
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());
|
|
// Another version's reply had the bytes that are here: its server differs in dates only.
|
|
if known.is_empty()
|
|
&& let Some(version) = unsure.take()
|
|
{
|
|
link.proven(version);
|
|
}
|
|
// Piece by piece, as fast as the limits have it. One chunk is read ahead, so that the sender has room again before
|
|
// all is used up.
|
|
let mut rest = &chunk[..];
|
|
while !rest.is_empty() {
|
|
let take = flow.take(rest.len() as u64);
|
|
tokio::pin!(take);
|
|
let n = loop {
|
|
tokio::select! {
|
|
biased;
|
|
_ = stopped(&mut stop) => break None,
|
|
n = &mut take => break Some(n as usize),
|
|
chunk = next(&mut response, part, link), if ahead.is_none() => ahead = Some(chunk),
|
|
}
|
|
};
|
|
// It is here already, so a stop doesn't throw it away.
|
|
let (piece, later) = rest.split_at(n.unwrap_or(rest.len()));
|
|
rest = later;
|
|
buf.extend_from_slice(piece);
|
|
part.arrive(piece.len() as u64);
|
|
let whole = part.remaining().is_some_and(|left| buf.len() as u64 >= left);
|
|
if whole || n.is_none() || 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<u64> {
|
|
let p = part.get();
|
|
p.end.map(|end| end - p.start).or(link.version.size)
|
|
}
|
|
|
|
async fn next(response: &mut Response, part: &LivePart, link: &Link) -> Result<Option<Bytes>> {
|
|
let cut = |e: reqwest::Error| if e.is_timeout() { e.into() } else { Error::Cut { got: part.get().done, expected: expected(part, link) } };
|
|
link.client.wait(async { response.chunk().await.map_err(cut) }).await
|
|
}
|
|
|
|
async fn flush(part: &LivePart, file: &PartialFile, buf: Vec<u8>) -> Result<Vec<u8>> {
|
|
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, and
|
|
/// whether the reply is of another version of the same size, which these bytes have to confirm.
|
|
async fn range(link: &Link, part: &LivePart, file: &PartialFile, stop: &mut Stop) -> Result<(Response, Vec<u8>, Option<Validators>)> {
|
|
let p = part.get();
|
|
let mut overlap = p.done.min(if link.farm() { SAMPLE } else { OVERLAP });
|
|
loop {
|
|
let first = p.start + p.done - overlap;
|
|
if p.done == 0 {
|
|
return Ok((sure_range(link, first, p.end, stop).await?, vec![], None));
|
|
}
|
|
let (response, unsure) = send_range(link, first, p.end, stop).await?;
|
|
// Enough of the bytes here to tell another version from the same file on another server.
|
|
if unsure.is_some() && overlap < p.done.min(SAMPLE) {
|
|
overlap = p.done.min(SAMPLE);
|
|
continue;
|
|
}
|
|
let known = file.read_at(overlap as usize, first).await?;
|
|
return Ok((response, known, unsure));
|
|
}
|
|
}
|
|
|
|
/// A range from the known version, or from another one shown to have the same bytes.
|
|
async fn sure_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<Response> {
|
|
for _ in 0..PROOF_TRIES {
|
|
let (response, unsure) = send_range(link, first, end, stop).await?;
|
|
let Some(version) = unsure else { return Ok(response) };
|
|
drop(response);
|
|
// Only replies of the same size are unsure, so the size is known.
|
|
let until = end.or(link.version.size).unwrap_or(first);
|
|
prove(link, &version, first, (until - first).min(SAMPLE), stop).await?;
|
|
}
|
|
Err(Error::Changed)
|
|
}
|
|
|
|
/// Asks for `len` bytes at `at` until a sure reply and one of another version can be compared, and so until `version` is
|
|
/// sure. The same bytes make a version sure; other bytes, or no sure reply at all, mean the file changed.
|
|
async fn prove(link: &Link, version: &Validators, at: u64, len: u64, stop: &mut Stop) -> Result<()> {
|
|
let mut other = None;
|
|
for _ in 0..PROOF_TRIES {
|
|
// Maybe by another part meanwhile.
|
|
if link.sure(version) {
|
|
return Ok(());
|
|
}
|
|
// The known sample's place, once there is one.
|
|
let (at, len) = link.farm.sample.lock().unwrap().as_ref().map_or((at, len), |(at, d)| (*at, d.len() as u64));
|
|
let (response, unsure) = send_range(link, at, Some(at + len), stop).await?;
|
|
let data = all(&link.client, response, len, stop).await?;
|
|
if data.len() as u64 != len {
|
|
return Err(Error::Cut { got: data.len() as u64, expected: Some(len) });
|
|
}
|
|
match unsure {
|
|
Some(version) => other = Some((version, at, data)),
|
|
None => link.known_sample(at, data),
|
|
}
|
|
let sample = link.farm.sample.lock().unwrap().clone();
|
|
if let (Some((at, known)), Some((version, other_at, data))) = (sample, &other)
|
|
&& at == *other_at
|
|
&& known.len() == data.len()
|
|
{
|
|
if known != *data {
|
|
return Err(Error::Changed);
|
|
}
|
|
link.proven(version.clone());
|
|
return Ok(());
|
|
}
|
|
}
|
|
Err(Error::Changed)
|
|
}
|
|
|
|
/// A reply to a range, and its version when that is another one of the same size: maybe the same file from another server
|
|
/// of a farm, which only its bytes can tell.
|
|
async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop) -> Result<(Response, Option<Validators>)> {
|
|
let last = end.map(|e| (e - 1).to_string()).unwrap_or_default();
|
|
// Servers of a farm with other dates answer a date in If-Range with the whole file.
|
|
let mut if_range = if link.farm() { None } else { link.version.if_range() };
|
|
loop {
|
|
let response = link.source.get(&link.client, Some(format!("bytes={first}-{last}")), 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()))?;
|
|
let version = Validators::of(headers, range.total);
|
|
let unsure = !link.sure(&version);
|
|
if unsure && !link.maybe_same(&version) {
|
|
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())?;
|
|
return Ok((response, unsure.then_some(version)));
|
|
}
|
|
StatusCode::OK => {
|
|
let version = Validators::of(headers, content_length(headers));
|
|
if link.version.same_file(&version) {
|
|
return Err(Error::RangeIgnored);
|
|
}
|
|
if link.maybe_same(&version) && if_range.take().is_some() {
|
|
continue;
|
|
}
|
|
if link.farm() && link.maybe_same(&version) {
|
|
return Err(Error::RangeIgnored);
|
|
}
|
|
return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed });
|
|
}
|
|
StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => {
|
|
return Err(Error::Changed);
|
|
}
|
|
_ => return Err(status_error(&response)),
|
|
}
|
|
}
|
|
}
|
|
|
|
fn comes_as_page(link: &Link, headers: &HeaderMap) -> bool {
|
|
name::from_url(&link.source.url).is_some_and(|n| page_instead(name::mime(headers).as_deref(), &n))
|
|
}
|
|
|
|
async fn whole(link: &Link, part: &LivePart, body: Option<Response>, stop: &mut Stop) -> Result<Response> {
|
|
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(if comes_as_page(link, headers) { Error::Page } else { 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?;
|
|
if same_bytes(link, &known, at, stop).await? { Ok(()) } else { Err(Error::Changed) }
|
|
}
|
|
|
|
/// Whether the server has `known` at `at`.
|
|
pub async fn same_bytes(link: &Link, known: &[u8], at: u64, stop: &mut Stop) -> Result<bool> {
|
|
let len = known.len() as u64;
|
|
let (response, unsure) = send_range(link, at, Some(at + len), stop).await?;
|
|
let same = same_body(&link.client, response, known, stop).await?;
|
|
if same && len > 0
|
|
&& let Some(version) = unsure
|
|
{
|
|
link.proven(version);
|
|
}
|
|
Ok(same)
|
|
}
|
|
|
|
/// `len` bytes at `at`.
|
|
pub(crate) async fn bytes_at(link: &Link, at: u64, len: u64, stop: &mut Stop) -> Result<Vec<u8>> {
|
|
let response = sure_range(link, at, Some(at + len), stop).await?;
|
|
let data = all(&link.client, response, len, stop).await?;
|
|
if data.len() as u64 == len { Ok(data) } else { Err(Error::Cut { got: data.len() as u64, expected: Some(len) }) }
|
|
}
|
|
|
|
/// A whole file of at most `max` bytes that is no web page.
|
|
pub(crate) async fn small(client: &Client, source: &Source, max: u64, stop: &mut Stop) -> Result<Vec<u8>> {
|
|
let response = source.get(client, None, None, stop).await?;
|
|
let headers = response.headers();
|
|
if response.status() != StatusCode::OK {
|
|
return Err(status_error(&response));
|
|
}
|
|
if page(name::mime(headers).as_deref()) {
|
|
return Err(Error::Page);
|
|
}
|
|
check_encoding(headers, response.url())?;
|
|
all(client, response, max, stop).await
|
|
}
|
|
|
|
async fn all(client: &Client, mut response: Response, max: u64, stop: &mut Stop) -> Result<Vec<u8>> {
|
|
let mut data = vec![];
|
|
loop {
|
|
let chunk = tokio::select! {
|
|
_ = stopped(stop) => return Err(Error::Stopped),
|
|
chunk = client.wait(response.chunk()) => chunk?,
|
|
};
|
|
let Some(chunk) = chunk else { return Ok(data) };
|
|
if data.len() as u64 + chunk.len() as u64 > max {
|
|
return Err(Error::BadReply("more than there should be".into()));
|
|
}
|
|
data.extend_from_slice(&chunk);
|
|
}
|
|
}
|
|
|
|
/// Whether the body begins with `known`.
|
|
pub(crate) async fn same_body(client: &Client, mut response: Response, known: &[u8], stop: &mut Stop) -> Result<bool> {
|
|
let mut rest = known;
|
|
while !rest.is_empty() {
|
|
let chunk = tokio::select! {
|
|
_ = stopped(stop) => return Err(Error::Stopped),
|
|
chunk = client.wait(response.chunk()) => chunk?,
|
|
};
|
|
let Some(chunk) = chunk else {
|
|
return Err(Error::Cut { got: (known.len() - rest.len()) as u64, expected: Some(known.len() as u64) });
|
|
};
|
|
let (now, later) = rest.split_at(chunk.len().min(rest.len()));
|
|
if !chunk.starts_with(now) {
|
|
return Ok(false);
|
|
}
|
|
rest = later;
|
|
}
|
|
Ok(true)
|
|
}
|