Medlar/crates/core/src/http/probe.rs
2026-11-25 13:55:19 -06:00

69 lines
2.7 KiB
Rust

//! What a link leads to.
use super::*;
use crate::metalink::{self, Hints};
#[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<String>,
/// Checksum and mirrors the headers tell of.
pub hints: Hints,
/// 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<Response>,
}
/// 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<Probe> {
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),
hints: metalink::hints(headers, &url),
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(()),
}
}