use std::collections::HashMap;
use std::io::SeekFrom;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow, bail};
use indicatif::{MultiProgress, ProgressBar};
use reqwest::header::{ACCEPT_RANGES, CONTENT_LENGTH, CONTENT_RANGE, RANGE};
use reqwest::{Client, StatusCode};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncSeekExt, AsyncWriteExt};
use crate::config::{DEFAULT_CONNECTIONS, format_bytes, format_duration_precise, format_speed};
use crate::engine::{self, Limiter, backoff};
use crate::fafo;
const MIN_SEGMENTED_BYTES: u64 = 256 * 1024;
const CHUNK_PAUSE_CHECK_EVERY: u64 = 32;
const ADAPTIVE_START: usize = 4;
const ADAPTIVE_MAX: usize = 32;
const THROTTLE_PROBE_BYTES: u64 = 512 * 1024;
const THROTTLE_PROBE_TIMEOUT: Duration = Duration::from_secs(8);
const WRITE_COALESCE_BYTES: usize = 1024 * 1024;
const MIN_SPLIT_REMAINING: u64 = 256 * 1024;
#[derive(Debug, Clone)]
pub struct DownloadOptions {
pub connections: usize,
pub speed_limit_bps: Option<u64>,
pub retries: u32,
pub mirrors: Vec<String>,
pub allow_h3: bool,
pub auto_mirror: bool,
pub proxy: Option<String>,
}
impl Default for DownloadOptions {
fn default() -> Self {
Self {
connections: DEFAULT_CONNECTIONS,
speed_limit_bps: None,
retries: 5,
mirrors: Vec::new(),
allow_h3: false,
auto_mirror: true,
proxy: None,
}
}
}
#[derive(Debug, Clone)]
pub struct Summary {
pub total_bytes: u64,
pub elapsed_secs: f64,
pub avg_bps: f64,
#[allow(dead_code)]
pub mirrors: Vec<String>,
}
pub fn part_path(out: &Path) -> PathBuf {
let mut s = out.as_os_str().to_owned();
s.push(".part");
PathBuf::from(s)
}
pub fn meta_path(out: &Path) -> PathBuf {
let mut s = out.as_os_str().to_owned();
s.push(".xget.json");
PathBuf::from(s)
}
pub fn pause_sentinel(out: &Path) -> PathBuf {
let mut s = out.as_os_str().to_owned();
s.push(".part.pause");
PathBuf::from(s)
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct SegState {
start: u64,
end: u64,
done: u64,
#[serde(default)]
hash: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Sidecar {
url: String,
total: Option<u64>,
segments: Vec<SegState>,
}
fn save_sidecar(meta: &Path, url: &str, total: Option<u64>, segs: &[SegState]) {
let sc = Sidecar {
url: url.to_string(),
total,
segments: segs.to_vec(),
};
engine::save_json(meta, &sc);
}
pub fn read_progress(out: &Path, url: &str) -> (Option<u64>, u64) {
let meta = meta_path(out);
if let Ok(raw) = std::fs::read_to_string(&meta)
&& let Ok(sc) = serde_json::from_str::<Sidecar>(&raw)
&& sc.url == url
{
let done = sc.segments.iter().map(|s| s.done).sum();
return (sc.total, done);
}
let part = part_path(out);
if part.exists() {
return (None, std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0));
}
if out.exists() {
let len = std::fs::metadata(out).map(|m| m.len()).unwrap_or(0);
return (Some(len), len);
}
(None, 0)
}
fn load_sidecar(meta: &Path, url: &str, total: Option<u64>, _n: usize) -> Option<Vec<SegState>> {
let raw = std::fs::read_to_string(meta).ok()?;
let sc: Sidecar = serde_json::from_str(&raw).ok()?;
if sc.url != url || sc.total != total || sc.segments.is_empty() {
return None;
}
Some(sc.segments)
}
pub fn filename_from_url(url: &str) -> String {
if let Ok(parsed) = url::Url::parse(url) {
if let Some(q) = parsed.query() {
for (k, v) in url::form_urlencoded::parse(q.as_bytes()) {
if (k == "file" || k == "name" || k == "filename") && !v.is_empty() {
return sanitize_filename(&v);
}
}
}
if let Some(seg) = parsed
.path_segments()
.and_then(|mut s| s.rfind(|p| !p.is_empty()))
{
let decoded = urlencoding_decode(seg);
if !decoded.is_empty() {
return sanitize_filename(&decoded);
}
}
}
let tail = url.split(['?', '#']).next().unwrap_or(url);
let tail = tail.trim_end_matches('/').rsplit('/').next().unwrap_or("");
if tail.is_empty() {
"download.bin".to_string()
} else {
sanitize_filename(tail)
}
}
fn urlencoding_decode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%'
&& i + 2 < bytes.len()
&& let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2]))
{
out.push((h * 16 + l) as char);
i += 3;
continue;
}
out.push(bytes[i] as char);
i += 1;
}
out
}
fn hex(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
fn sanitize_filename(name: &str) -> String {
let n: String = name
.chars()
.map(|c| {
if matches!(c, '/' | '\\' | '\0') {
'_'
} else {
c
}
})
.collect();
let n = n.trim();
if n.is_empty() || n == "." || n == ".." {
"download.bin".to_string()
} else {
n.to_string()
}
}
pub fn resolve_output(
url: &str,
output_opt: Option<PathBuf>,
download_dir: &Path,
) -> Result<PathBuf> {
if let Some(o) = output_opt {
if o.as_os_str().is_empty() {
bail!("empty output path");
}
let looks_like_dir = o.as_path().exists() && o.as_path().is_dir();
if looks_like_dir {
return Ok(o.join(filename_from_url(url)));
}
return Ok(o);
}
Ok(download_dir.join(filename_from_url(url)))
}
fn make_client_with(proxy: Option<&str>) -> Result<Client> {
let mut b = Client::builder()
.user_agent("xget/0.1 (+https://github.com/JustRoccat/xget)")
.pool_max_idle_per_host(ADAPTIVE_MAX)
.pool_idle_timeout(Duration::from_secs(90))
.tcp_keepalive(Duration::from_secs(20))
.tcp_nodelay(true)
.connect_timeout(Duration::from_secs(15));
if let Some(p) = proxy {
b = b.proxy(reqwest::Proxy::all(p).with_context(|| format!("bad proxy URL: {p}"))?);
}
b.build().context("cannot create HTTP client")
}
fn make_client() -> Result<Client> { make_client_with(None) }
fn parse_total_from_content_range(v: &str) -> Option<u64> {
v.rsplit('/').next()?.trim().parse::<u64>().ok()
}
fn pause_requested(out: &Path) -> bool {
pause_sentinel(out).exists()
}
pub async fn run_download(url: &str, out_path: &Path, opts: &DownloadOptions) -> Result<Summary> {
let started = Instant::now();
let _ = std::fs::remove_file(pause_sentinel(out_path));
let _ = fafo::tuning_status();
let client = make_client_with(opts.proxy.as_deref())?;
fafo::prefetch_dns(url).await;
let (total, ranges, _h3_won) = probe(&client, url, opts.allow_h3).await;
let mut explicit = filter_mirrors(&client, &opts.mirrors, total).await;
let mut auto = Vec::new();
if opts.auto_mirror {
let cands = auto_candidates(url);
let fresh: Vec<String> = cands
.into_iter()
.filter(|c| c != url && !explicit.contains(c) && !opts.mirrors.contains(c))
.collect();
auto = rank_and_filter(&client, &fresh, total).await;
explicit = rank_and_filter(&client, &explicit, total).await;
}
let mut mirrors = explicit;
mirrors.extend(auto.iter().cloned());
if let Some(t) = total {
let out_len = std::fs::metadata(out_path).map(|m| m.len()).ok();
if is_delta_complete(out_len, part_path(out_path).exists(), Some(t)) {
return Ok(Summary {
total_bytes: t,
elapsed_secs: started.elapsed().as_secs_f64(),
avg_bps: t as f64 / started.elapsed().as_secs_f64().max(0.001),
mirrors: mirrors.clone(),
});
}
}
let n = opts.connections.clamp(1, ADAPTIVE_MAX);
if ranges && total.is_some_and(|t| t >= MIN_SEGMENTED_BYTES) && n > 1 {
let total = total.unwrap();
if total >= 8 * THROTTLE_PROBE_BYTES {
let throttled = throttle_probe(&client, url, total).await;
if !throttled {
eprintln!(" mode: single-stream (no per-connection throttle detected)");
let total_written =
single_stream(&client, url, &mirrors, out_path, Some(total), ranges, opts)
.await?;
let secs = started.elapsed().as_secs_f64();
return Ok(Summary {
total_bytes: total_written,
elapsed_secs: secs,
avg_bps: total_written as f64 / started.elapsed().as_secs_f64().max(0.001),
mirrors,
});
}
eprintln!(" mode: segmented x{n} (per-connection throttle detected)");
}
let effective = opts.clone();
segmented(&client, url, &mirrors, out_path, total, n, &effective).await?;
let secs = started.elapsed().as_secs_f64();
return Ok(Summary {
total_bytes: total,
elapsed_secs: secs,
avg_bps: total as f64 / started.elapsed().as_secs_f64().max(0.001),
mirrors,
});
}
let total_written =
single_stream(&client, url, &mirrors, out_path, total, ranges, opts).await?;
Ok(Summary {
total_bytes: total_written,
elapsed_secs: started.elapsed().as_secs_f64(),
avg_bps: total_written as f64 / started.elapsed().as_secs_f64().max(0.001),
mirrors,
})
}
impl Summary {
pub fn report(&self) -> String {
format!(
"Completed: {} in {} (avg. {})",
format_bytes(self.total_bytes),
format_duration_precise(self.elapsed_secs),
format_speed(self.avg_bps)
)
}
}
async fn throttle_probe(client: &Client, url: &str, total: u64) -> bool {
let n = THROTTLE_PROBE_BYTES.min(total / 4).max(256 * 1024);
let _ = timed_range(client, url, 0, 256 * 1024).await;
let bps_one = timed_range(client, url, 0, n).await;
let (a, b) = tokio::join!(
timed_range(client, url, 0, n / 2),
timed_range(client, url, n / 2, n - n / 2),
);
let (Some(b1), Some(ba), Some(bb)) = (bps_one, a, b) else {
return true;
};
(ba + bb) > b1 * 1.5
}
async fn timed_range(client: &Client, url: &str, start: u64, len: u64) -> Option<f64> {
let range = format!("bytes={start}-{}", start + len - 1);
let t0 = Instant::now();
let resp = tokio::time::timeout(
THROTTLE_PROBE_TIMEOUT,
client
.get(url)
.header(RANGE, range)
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send(),
)
.await
.ok()?
.ok()?;
if resp.status() != StatusCode::PARTIAL_CONTENT {
return None;
}
let mut got = 0u64;
let mut resp = resp;
loop {
let chunk = tokio::time::timeout(THROTTLE_PROBE_TIMEOUT, resp.chunk())
.await
.ok()?
.ok()?;
let Some(bytes) = chunk else { break };
got += bytes.len() as u64;
if got >= len {
break;
}
}
if got == 0 {
return None;
}
Some(got as f64 / t0.elapsed().as_secs_f64().max(0.001))
}
async fn probe(client: &Client, url: &str, allow_h3: bool) -> (Option<u64>, bool, bool) {
let head_fut = async {
match tokio::time::timeout(
Duration::from_secs(15),
client
.head(url)
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send(),
)
.await
{
Ok(Ok(resp)) if resp.status().is_success() => {
let total = resp
.headers()
.get(CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok());
let ranges = resp
.headers()
.get(ACCEPT_RANGES)
.and_then(|v| v.to_str().ok())
.is_some_and(|ar| ar.trim().eq_ignore_ascii_case("bytes"));
(total, ranges)
}
_ => (None, false),
}
};
let range_fut = async {
match tokio::time::timeout(
Duration::from_secs(15),
client
.get(url)
.header(RANGE, "bytes=0-0")
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send(),
)
.await
{
Ok(Ok(resp)) => {
if resp.status() == StatusCode::PARTIAL_CONTENT {
let mut total = resp
.headers()
.get(CONTENT_RANGE)
.and_then(|v| v.to_str().ok())
.and_then(parse_total_from_content_range);
if total.is_none() {
total = resp
.headers()
.get(CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok())
.map(|l| l + 1);
}
let _ = tokio::time::timeout(Duration::from_secs(15), resp.bytes()).await;
(total, true)
} else if resp.status().is_success() {
let total = resp
.headers()
.get(CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|s| s.trim().parse::<u64>().ok());
(total, false)
} else {
(None, false)
}
}
_ => (None, false),
}
};
let ((h_total, h_ranges), (r_total, r_ranges), h3_won) = if allow_h3 {
let (hr, rr, h3) = tokio::join!(head_fut, range_fut, fafo::probe_h3(url));
(hr, rr, h3)
} else {
let (hr, rr) = tokio::join!(head_fut, range_fut);
(hr, rr, false)
};
(h_total.or(r_total), h_ranges || r_ranges, h3_won)
}
async fn filter_mirrors(client: &Client, mirrors: &[String], total: Option<u64>) -> Vec<String> {
if mirrors.is_empty() {
return Vec::new();
}
let checks = mirrors
.iter()
.map(|m| async move { timed_mirror_check(client, m, total).await.map(|(u, _)| u) });
futures::future::join_all(checks)
.await
.into_iter()
.flatten()
.collect()
}
async fn timed_mirror_check(
client: &Client,
m: &str,
total: Option<u64>,
) -> Option<(String, std::time::Duration)> {
let t0 = Instant::now();
let r = tokio::time::timeout(
Duration::from_secs(10),
client
.get(m)
.header(RANGE, "bytes=0-0")
.header(reqwest::header::ACCEPT_ENCODING, "identity")
.send(),
)
.await
.ok()?
.ok()?;
if r.status() != StatusCode::PARTIAL_CONTENT {
return None;
}
let mt = r
.headers()
.get(CONTENT_RANGE)
.and_then(|v| v.to_str().ok())
.and_then(parse_total_from_content_range);
let _ = tokio::time::timeout(Duration::from_secs(15), r.bytes()).await;
let dt = t0.elapsed();
match (total, mt) {
(Some(t), Some(x)) if t == x => Some((m.to_owned(), dt)),
(None, _) => Some((m.to_owned(), dt)),
_ => None,
}
}
async fn rank_and_filter(client: &Client, mirrors: &[String], total: Option<u64>) -> Vec<String> {
if mirrors.is_empty() {
return Vec::new();
}
let checks = mirrors.iter().map(|m| timed_mirror_check(client, m, total));
let mut timed: Vec<(String, std::time::Duration)> = futures::future::join_all(checks)
.await
.into_iter()
.flatten()
.collect();
timed.sort_by_key(|(_, dt)| *dt);
timed.into_iter().map(|(u, _)| u).collect()
}
pub fn auto_candidates(url: &str) -> Vec<String> {
let mut out = Vec::new();
let parsed = match url::Url::parse(url) {
Ok(u) => u,
Err(_) => return out,
};
let host = parsed.host_str().unwrap_or("").to_ascii_lowercase();
let path = if parsed.path().is_empty() {
"/"
} else {
parsed.path()
};
let query = parsed.query().map(|q| format!("?{q}")).unwrap_or_default();
let full_path = format!("{path}{query}");
let swap_host = |new_host: &str| format!("{}://{}{}", parsed.scheme(), new_host, full_path);
match host.as_str() {
"releases.ubuntu.com" => {
for h in [
"ftp.icm.edu.pl/pub/Linux/ubuntu-releases",
"mirroronet.pl/pub/mirror/ubuntu-releases",
"mirrors.edge.kernel.org/ubuntu-releases",
] {
let p = full_path.trim_start_matches('/');
out.push(format!(
"{}://{}/{}",
parsed.scheme(),
h.split('/').next().unwrap_or(h),
format!("{}/{}", h.split_once('/').map(|(_, r)| r).unwrap_or(""), p)
.trim_start_matches('/')
));
}
}
"cdn.kernel.org" | "download.kernel.org" => {
for h in ["mirrors.kernel.org", "mirrors.edge.kernel.org"] {
out.push(swap_host(h));
}
}
"deb.debian.org" => {
for h in ["ftp.pl.debian.org", "ftp.debian.org"] {
out.push(swap_host(h));
}
}
"github.com" if full_path.contains("/releases/download/") => {
out.push(format!("https://mirror.ghproxy.com/{url}"));
}
_ => {}
}
if (host == "127.0.0.1" || host == "localhost")
&& let Some(port) = parsed.port()
{
for p in [port + 1, port + 2] {
let mut u = parsed.clone();
let _ = u.set_port(Some(p));
out.push(u.to_string());
}
}
if let Ok(extra) = std::env::var("XGET_AUTO_MIRRORS") {
for e in extra.split(',').map(str::trim).filter(|s| !s.is_empty()) {
if !out.contains(&e.to_string()) {
out.push(e.to_string());
}
}
}
out.retain(|c| c != url);
out
}
#[allow(clippy::too_many_arguments)]
async fn segmented(
client: &Client,
url: &str,
mirrors: &[String],
out_path: &Path,
total: u64,
n: usize,
opts: &DownloadOptions,
) -> Result<()> {
let part = part_path(out_path);
let meta = meta_path(out_path);
if let Some(parent) = out_path.parent()
&& !parent.as_os_str().is_empty()
{
tokio::fs::create_dir_all(parent)
.await
.with_context(|| format!("cannot create directory {}", parent.display()))?;
}
let mut ceiling = n.clamp(1, ADAPTIVE_MAX);
let start_n = ceiling;
let base = total / start_n as u64;
let mut rem = total % start_n as u64;
let mut ranges: Vec<(u64, u64)> = Vec::with_capacity(ceiling);
let mut cur = 0u64;
for _ in 0..start_n {
let mut len = base;
if rem > 0 {
len += 1;
rem -= 1;
}
ranges.push((cur, cur + len));
cur += len;
}
let pre_have = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
{
let f = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(false)
.open(&part)
.with_context(|| format!("cannot create {}", part.display()))?;
f.set_len(total)
.with_context(|| format!("cannot preallocate {}", part.display()))?;
let md = f.metadata()?;
if md.len() != total {
f.set_len(total)?;
}
}
let mut segs: Vec<SegState> = ranges
.iter()
.map(|(s, e)| SegState {
start: *s,
end: *e,
done: 0,
hash: None,
})
.collect();
if part.exists() {
if let Some(saved) = load_sidecar(&meta, url, Some(total), n) {
if saved.len() == segs.len()
&& saved
.iter()
.zip(segs.iter())
.all(|(a, b)| a.start == b.start && a.end == b.end)
{
for (dst, src) in segs.iter_mut().zip(saved.iter()) {
let max = dst.end.saturating_sub(dst.start);
dst.done = src.done.min(max);
}
} else {
let kept: Vec<SegState> = saved
.into_iter()
.map(|s| {
let (mut a, mut b) = (s.start, s.end);
if b < a {
std::mem::swap(&mut a, &mut b);
}
let max = b.saturating_sub(a);
SegState {
start: a,
end: b,
done: s.done.min(max),
hash: s.hash.filter(|_| s.done >= max),
}
})
.filter(|s| s.end > s.start)
.collect();
if !kept.is_empty() {
segs = kept;
for s in segs.iter_mut() {
let len = s.end.saturating_sub(s.start);
if s.done >= len
&& len > 0
&& s.hash.as_ref().is_some_and(|h| {
fafo::hash_range(&part, s.start, len).as_ref() != Some(h)
})
{
s.done = 0;
s.hash = None;
}
}
}
}
} else if pre_have > 0 && pre_have < total {
for s in segs.iter_mut() {
if pre_have <= s.start {
break;
}
s.done = pre_have.min(s.end).saturating_sub(s.start);
}
}
}
save_sidecar(&meta, url, Some(total), &segs);
let already: u64 = segs.iter().map(|s| s.done).sum();
if already >= total {
finalize(&part, &meta, out_path).await?;
return Ok(());
}
let mp = MultiProgress::new();
let total_bar = mp.add(ProgressBar::new(total));
total_bar.set_style(engine::total_style());
total_bar.set_message(engine::short_name(out_path));
total_bar.set_position(already);
let shared: Arc<std::sync::Mutex<Vec<SegState>>> = Arc::new(std::sync::Mutex::new(segs));
let errors: Arc<AtomicU64> = Arc::new(AtomicU64::new(0));
let limiter: Option<Arc<Limiter>> = opts.speed_limit_bps.map(|b| Arc::new(Limiter::new(b)));
let flush_shared = shared.clone();
let flush_meta = meta.clone();
let flush_url = url.to_string();
let flush_stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let flush_stop_w = flush_stop.clone();
let flush_handle = tokio::spawn(async move {
let mut iv = tokio::time::interval(Duration::from_secs(1));
loop {
iv.tick().await;
if flush_stop_w.load(std::sync::atomic::Ordering::Relaxed) {
break;
}
let snapshot: Vec<SegState> = flush_shared.lock().unwrap().clone();
save_sidecar(&flush_meta, &flush_url, Some(total), &snapshot);
}
});
let sources: Vec<String> = std::iter::once(url.to_owned())
.chain(mirrors.iter().cloned())
.collect();
let mut bar_of: HashMap<usize, ProgressBar> = HashMap::new();
let mut handles = Vec::with_capacity(ceiling);
{
let segs0 = shared.lock().unwrap().clone();
for (i, s) in segs0.iter().enumerate() {
let seg_len = s.end.saturating_sub(s.start);
if s.done >= seg_len {
continue;
}
let bar = mp.add(ProgressBar::new(seg_len));
bar.set_style(engine::seg_style());
bar.set_message(format!("#{i}"));
bar.set_position(s.done);
bar_of.insert(i, bar.clone());
handles.push(tokio::spawn(fetch_segment(
client.clone(),
sources.clone(),
part.clone(),
i,
shared.clone(),
bar,
total_bar.clone(),
limiter.clone(),
opts.retries,
errors.clone(),
out_path.to_path_buf(),
)));
if i == 0 {
tokio::task::yield_now().await;
} else {
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
}
{
let mut best_bps = 0.0f64;
let mut prev_done = already;
let mut prev_t = Instant::now();
let mut stalls = 0u32;
let mut last_err = errors.load(Ordering::Relaxed);
let mut rounds = 0u32;
let mut ticks = 0u32;
loop {
tokio::time::sleep(Duration::from_millis(100)).await;
if handles.iter().all(|h| h.is_finished()) {
break;
}
if pause_requested(out_path) {
break;
}
ticks += 1;
if !ticks.is_multiple_of(5) {
continue;
}
rounds += 1;
let (cur_done, unfinished, _biggest) = {
let segs = shared.lock().unwrap();
let mut done = 0u64;
let mut unfin = 0usize;
let mut big: Option<(usize, u64)> = None;
for (i, s) in segs.iter().enumerate() {
done += s.done;
let len = s.end.saturating_sub(s.start);
if s.done < len {
unfin += 1;
let left = len - s.done;
if big.map(|(_, b)| left > b).unwrap_or(true) {
big = Some((i, left));
}
}
}
(done, unfin, big)
};
if cur_done >= total || unfinished == 0 {
break;
}
if rounds > 120 {
break;
}
let dt = prev_t.elapsed().as_secs_f64().max(0.001);
let win_bps = cur_done.saturating_sub(prev_done) as f64 / dt;
prev_done = cur_done;
prev_t = Instant::now();
let cur_err = errors.load(Ordering::Relaxed);
if cur_err > last_err {
last_err = cur_err;
ceiling = unfinished
.saturating_sub(1)
.max(ADAPTIVE_START.min(ceiling));
stalls += 1;
if stalls >= 3 {
break;
}
continue;
}
if best_bps == 0.0 || win_bps > best_bps * 1.05 {
if win_bps > best_bps {
best_bps = win_bps;
}
stalls = 0;
let target = (unfinished * 2).max(unfinished + 1).min(ceiling);
for _ in 0..ADAPTIVE_MAX {
let (unfin_now, cand) = {
let segs = shared.lock().unwrap();
let mut unfin = 0usize;
let mut big: Option<(usize, u64)> = None;
for (i, s) in segs.iter().enumerate() {
let len = s.end.saturating_sub(s.start);
if s.done < len {
unfin += 1;
let left = len - s.done;
if left >= MIN_SPLIT_REMAINING
&& big.map(|(_, b)| left > b).unwrap_or(true)
{
big = Some((i, left));
}
}
}
(unfin, big)
};
if unfin_now >= target {
break;
}
let Some((bi, _)) = cand else {
break;
};
let split = {
let mut segs = shared.lock().unwrap();
if bi >= segs.len() {
None
} else {
let pos = segs[bi].start + segs[bi].done;
let old_end = segs[bi].end;
if old_end.saturating_sub(pos) < MIN_SPLIT_REMAINING {
None
} else {
let mid = pos + (old_end - pos) / 2;
segs[bi].end = mid;
let new_idx = segs.len();
segs.push(SegState {
start: mid,
end: old_end,
done: 0,
hash: None,
});
Some((new_idx, mid - segs[bi].start, old_end - mid))
}
}
};
if let Some((new_idx, old_len, new_len)) = split {
if let Some(b) = bar_of.get(&bi) {
b.set_length(old_len);
}
let bar = mp.add(ProgressBar::new(new_len));
bar.set_style(engine::seg_style());
bar.set_message(format!("#{new_idx}"));
bar.set_position(0);
bar_of.insert(new_idx, bar.clone());
handles.push(tokio::spawn(fetch_segment(
client.clone(),
sources.clone(),
part.clone(),
new_idx,
shared.clone(),
bar,
total_bar.clone(),
limiter.clone(),
opts.retries,
errors.clone(),
out_path.to_path_buf(),
)));
} else {
break;
}
}
} else {
stalls += 1;
if stalls >= 2 {
break;
}
}
}
}
let wait_all = async {
let mut first_err: Option<anyhow::Error> = None;
for h in handles {
match h.await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
if first_err.is_none() {
first_err = Some(e);
}
}
Err(e) => {
if first_err.is_none() {
first_err = Some(anyhow!("segment task aborted: {e}"));
}
}
}
}
match first_err {
Some(e) => Err(e),
None => Ok(()),
}
};
let res = tokio::select! {
r = wait_all => r,
_ = tokio::signal::ctrl_c() => {
Err(anyhow!("interrupted (Ctrl-C) — download can be resumed with `resume`"))
}
};
flush_stop.store(true, std::sync::atomic::Ordering::Relaxed);
flush_handle.abort();
{
let snapshot: Vec<SegState> = shared.lock().unwrap().clone();
save_sidecar(&meta, url, Some(total), &snapshot);
}
match res {
Ok(()) => {
if pause_requested(out_path) {
total_bar.abandon_with_message("paused");
bail!("__XGET_PAUSED__");
}
let got: u64 = shared.lock().unwrap().iter().map(|s| s.done).sum();
if got < total {
total_bar.abandon_with_message("incomplete");
bail!(
"only {} of {} downloaded — can be resumed with `resume`",
format_bytes(got),
format_bytes(total)
);
}
total_bar.finish_with_message("done");
finalize(&part, &meta, out_path).await?;
mp.clear().ok();
Ok(())
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
total_bar.abandon_with_message("paused");
} else {
total_bar.abandon_with_message("error");
}
mp.clear().ok();
Err(e)
}
}
}
#[allow(clippy::too_many_arguments)]
async fn fetch_segment(
client: Client,
sources: Vec<String>,
part: PathBuf,
idx: usize,
shared: Arc<std::sync::Mutex<Vec<SegState>>>,
bar: ProgressBar,
total_bar: ProgressBar,
limiter: Option<Arc<Limiter>>,
retries: u32,
errors: Arc<AtomicU64>,
out_path: PathBuf,
) -> Result<()> {
let mut buf: Vec<u8> = Vec::with_capacity(WRITE_COALESCE_BYTES);
let mut attempt: u32 = 0;
loop {
if pause_requested(&out_path) {
bail!("__XGET_PAUSED__");
}
let (start, end, done) = {
let segs = shared.lock().unwrap();
match segs.get(idx) {
Some(s) => (s.start, s.end, s.done),
None => bail!("seg #{idx}: segment state missing"),
}
};
let from = start + done;
if from >= end {
bar.finish_with_message(format!("#{idx} ok"));
return Ok(());
}
let range = format!("bytes={from}-{}", end - 1);
let resp = match tokio::time::timeout(
Duration::from_secs(30),
fafo::race_range(&client, &sources, &range),
)
.await
{
Ok(Some(r)) => r,
Ok(None) => {
errors.fetch_add(1, Ordering::Relaxed);
attempt += 1;
if attempt > retries {
bar.abandon_with_message(format!("#{idx} error"));
return Err(anyhow!("seg #{idx}: all sources rejected Range"));
}
backoff(attempt).await;
continue;
}
Err(_) => {
errors.fetch_add(1, Ordering::Relaxed);
attempt += 1;
if attempt > retries {
bar.abandon_with_message(format!("#{idx} error"));
return Err(anyhow!("seg #{idx}: connection timeout (30 s)"));
}
backoff(attempt).await;
continue;
}
};
let mut file = tokio::fs::OpenOptions::new()
.write(true)
.read(true)
.open(&part)
.await
.with_context(|| format!("seg #{idx}: cannot open working file"))?;
file.seek(SeekFrom::Start(from))
.await
.with_context(|| format!("seg #{idx}: seek error"))?;
let mut resp = resp;
let mut chunks_since_check = 0u64;
let mut last_pause_check = Instant::now();
let mut done = done;
let mut ok = true;
let mut fatal: Option<anyhow::Error> = None;
loop {
let chunk = match tokio::time::timeout(Duration::from_secs(60), resp.chunk()).await {
Ok(Ok(c)) => c,
Ok(Err(e)) => {
ok = false;
fatal = Some(anyhow!("seg #{idx}: read error: {e}"));
break;
}
Err(_) => {
ok = false;
fatal = Some(anyhow!("seg #{idx}: read timeout (60 s without data)"));
break;
}
};
let Some(mut bytes) = chunk else { break };
if bytes.is_empty() {
continue;
}
let cur_end = shared
.lock()
.unwrap()
.get(idx)
.map(|s| s.end)
.unwrap_or(end);
let have = start + done + buf.len() as u64;
if have >= cur_end {
break;
}
let remaining = cur_end - have;
if bytes.len() as u64 > remaining {
bytes.truncate(remaining as usize);
}
if let Some(lim) = &limiter {
lim.consume(bytes.len() as u64).await;
}
buf.extend_from_slice(&bytes);
if buf.len() >= WRITE_COALESCE_BYTES {
if let Err(e) = file.write_all(&buf).await {
ok = false;
fatal = Some(anyhow!("seg #{idx}: write error: {e}"));
break;
}
done += buf.len() as u64;
bar.inc(buf.len() as u64);
total_bar.inc(buf.len() as u64);
{
let mut g = shared.lock().unwrap();
if let Some(s) = g.get_mut(idx) {
s.done = done;
}
}
buf.clear();
}
chunks_since_check += 1;
if chunks_since_check >= CHUNK_PAUSE_CHECK_EVERY
|| last_pause_check.elapsed() >= Duration::from_millis(300)
{
chunks_since_check = 0;
last_pause_check = Instant::now();
if pause_requested(&out_path) {
fatal = Some(anyhow!("__XGET_PAUSED__"));
ok = false;
break;
}
}
if start + done + buf.len() as u64 >= cur_end {
break;
}
}
if !buf.is_empty() && ok {
if let Err(e) = file.write_all(&buf).await {
ok = false;
fatal = Some(anyhow!("seg #{idx}: write error: {e}"));
} else {
done += buf.len() as u64;
bar.inc(buf.len() as u64);
total_bar.inc(buf.len() as u64);
{
let mut g = shared.lock().unwrap();
if let Some(s) = g.get_mut(idx) {
s.done = done;
}
}
buf.clear();
}
} else if !ok {
buf.clear();
}
if ok {
let cur_end = shared
.lock()
.unwrap()
.get(idx)
.map(|s| s.end)
.unwrap_or(end);
if start + done >= cur_end {
bar.finish_with_message(format!("#{idx} ok"));
return Ok(());
}
errors.fetch_add(1, Ordering::Relaxed);
attempt += 1;
if attempt > retries {
bar.abandon_with_message(format!("#{idx} error"));
return Err(anyhow!(
"seg #{idx}: server cut the stream ({} of {})",
format_bytes(done),
format_bytes(cur_end.saturating_sub(start))
));
}
backoff(attempt).await;
continue;
}
let e = fatal.unwrap();
if e.to_string() == "__XGET_PAUSED__" {
return Err(e);
}
errors.fetch_add(1, Ordering::Relaxed);
attempt += 1;
if attempt > retries {
bar.abandon_with_message(format!("#{idx} error"));
return Err(e.context(format!("seg #{idx}: retries exhausted ({retries})")));
}
backoff(attempt).await;
}
}
#[allow(dead_code)]
fn stamp_hash(shared: &Arc<std::sync::Mutex<Vec<SegState>>>, part: &Path, idx: usize) {
let (start, len, missing) = {
let g = shared.lock().unwrap();
match g.get(idx) {
Some(s) => (s.start, s.end.saturating_sub(s.start), s.hash.is_none()),
None => return,
}
};
if !missing || len == 0 {
return;
}
let h = fafo::hash_range(part, start, len);
if let Some(s) = shared.lock().unwrap().get_mut(idx) {
s.hash = h;
}
}
pub fn is_delta_complete(out_len: Option<u64>, part_exists: bool, total: Option<u64>) -> bool {
match (out_len, total) {
(Some(len), Some(t)) => t > 0 && len == t && !part_exists,
_ => false,
}
}
pub fn use_compression(ranges_supported: bool) -> bool {
!ranges_supported
}
async fn finalize(part: &Path, meta: &Path, out_path: &Path) -> Result<()> {
let _ = std::fs::remove_file(pause_sentinel(out_path));
if out_path.exists() {
tokio::fs::remove_file(out_path).await.ok();
}
tokio::fs::rename(part, out_path)
.await
.with_context(|| format!("cannot move {} -> {}", part.display(), out_path.display()))?;
let _ = std::fs::remove_file(meta);
Ok(())
}
async fn single_stream(
client: &Client,
url: &str,
mirrors: &[String],
out_path: &Path,
total: Option<u64>,
ranges: bool,
opts: &DownloadOptions,
) -> Result<u64> {
let part = part_path(out_path);
let meta = meta_path(out_path);
if let Some(parent) = out_path.parent()
&& !parent.as_os_str().is_empty()
{
tokio::fs::create_dir_all(parent)
.await
.with_context(|| format!("cannot create directory {}", parent.display()))?;
}
let mut resume_from: u64 = 0;
if part.exists() {
resume_from = std::fs::metadata(&part).map(|m| m.len()).unwrap_or(0);
if let Some(t) = total
&& resume_from >= t
&& t > 0
{
finalize(&part, &meta, out_path).await?;
return Ok(t);
}
}
let mp = MultiProgress::new();
let bar = match total {
Some(t) if t > 0 => {
let b = mp.add(ProgressBar::new(t));
b.set_style(engine::total_style());
b
}
_ => {
let b = mp.add(ProgressBar::new_spinner());
b.set_style(engine::spinner_style());
b.enable_steady_tick(Duration::from_millis(120));
b
}
};
bar.set_message(engine::short_name(out_path));
bar.set_position(resume_from.min(bar.length().unwrap_or(resume_from)));
let limiter: Option<Arc<Limiter>> = opts.speed_limit_bps.map(|b| Arc::new(Limiter::new(b)));
let allow_compression = use_compression(ranges);
let sources: Vec<&str> = std::iter::once(url)
.chain(mirrors.iter().map(String::as_str))
.collect();
let mut attempt = 0u32;
loop {
if pause_requested(out_path) {
bar.abandon_with_message("paused");
mp.clear().ok();
bail!("__XGET_PAUSED__");
}
let src = sources[(attempt as usize) % sources.len()];
let mut req = client.get(src);
if allow_compression {
req = req.header(reqwest::header::ACCEPT_ENCODING, "zstd, gzip, br, deflate");
} else {
req = req.header(reqwest::header::ACCEPT_ENCODING, "identity");
}
let req = if resume_from > 0 {
req.header(RANGE, format!("bytes={resume_from}-"))
} else {
req
};
let resp = match req.send().await {
Ok(r) => r,
Err(e) => {
attempt += 1;
if attempt > opts.retries {
bar.abandon_with_message("error");
mp.clear().ok();
return Err(anyhow!("connection error: {e}"));
}
backoff(attempt).await;
continue;
}
};
let code = resp.status();
let append = resume_from > 0 && code == StatusCode::PARTIAL_CONTENT;
if resume_from > 0 && code == StatusCode::OK {
resume_from = 0;
bar.set_position(0);
} else if !code.is_success() && code != StatusCode::PARTIAL_CONTENT {
attempt += 1;
if attempt > opts.retries {
bar.abandon_with_message("error");
mp.clear().ok();
bail!("server responded {code}");
}
backoff(attempt).await;
continue;
}
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(!append)
.open(&part)
.await
.with_context(|| format!("cannot open {}", part.display()))?;
if append {
file.seek(SeekFrom::Start(resume_from)).await?;
}
let mut written = resume_from;
let mut resp = resp;
let mut buf: Vec<u8> = Vec::with_capacity(WRITE_COALESCE_BYTES);
let run = async {
loop {
tokio::select! {
_ = tokio::signal::ctrl_c() => {
bail!("interrupted (Ctrl-C) — download can be resumed with `resume`");
}
chunk = resp.chunk() => {
let chunk = chunk.with_context(|| "response read error")?;
let Some(bytes) = chunk else { break };
if bytes.is_empty() { continue; }
if let Some(lim) = &limiter {
lim.consume(bytes.len() as u64).await;
}
buf.extend_from_slice(&bytes);
if buf.len() >= WRITE_COALESCE_BYTES {
file.write_all(&buf).await.with_context(|| "file write error")?;
written += buf.len() as u64;
bar.inc(buf.len() as u64);
buf.clear();
}
if pause_requested(out_path) {
bail!("__XGET_PAUSED__");
}
}
}
}
if !buf.is_empty() {
file.write_all(&buf)
.await
.with_context(|| "file write error")?;
written += buf.len() as u64;
bar.inc(buf.len() as u64);
buf.clear();
}
Ok::<(), anyhow::Error>(())
};
match run.await {
Ok(()) => {
if let Some(t) = total
&& append
&& written < t
{
resume_from = written;
attempt += 1;
if attempt > opts.retries {
bar.abandon_with_message("incomplete");
mp.clear().ok();
bail!(
"server dropped the connection ({} of {})",
format_bytes(written),
format_bytes(t)
);
}
backoff(attempt).await;
continue;
}
file.flush().await.ok();
drop(file);
bar.finish_with_message("done");
finalize(&part, &meta, out_path).await?;
mp.clear().ok();
return Ok(written);
}
Err(e) => {
if e.to_string() == "__XGET_PAUSED__" {
bar.abandon_with_message("paused");
mp.clear().ok();
return Err(e);
}
attempt += 1;
if attempt > opts.retries {
bar.abandon_with_message("error");
mp.clear().ok();
return Err(e);
}
resume_from = written;
backoff(attempt).await;
}
}
}
}
#[cfg(test)]
mod fafo_tests {
use super::*;
#[test]
fn hash_range_matches_blake3() {
let dir = std::env::temp_dir().join("xget-fafo-test");
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("blob.bin");
let data: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
std::fs::write(&p, &data).unwrap();
let want = blake3::hash(&data[1000..200_000]).to_hex().to_string();
assert_eq!(fafo::hash_range(&p, 1000, 199_000), Some(want));
assert_eq!(fafo::hash_range(&p.join("missing"), 0, 10), None);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn tuning_probe_never_panics() {
let _ = fafo::tuning_status();
let rep = fafo::tcp_tuning_report();
assert!(!rep.is_empty());
}
#[test]
fn delta_skip_only_on_matching_size_without_part() {
assert!(is_delta_complete(Some(100), false, Some(100)));
assert!(!is_delta_complete(Some(100), true, Some(100)));
assert!(!is_delta_complete(Some(99), false, Some(100)));
assert!(!is_delta_complete(Some(100), false, None));
assert!(!is_delta_complete(None, false, Some(100)));
assert!(!is_delta_complete(Some(0), false, Some(0)));
}
#[test]
fn sidecar_roundtrip_keeps_hashes_for_resume() {
let dir = std::env::temp_dir().join("xget-sidecar-test");
std::fs::create_dir_all(&dir).unwrap();
let meta = dir.join("f.xget.json");
let segs = vec![
SegState {
start: 0,
end: 100,
done: 100,
hash: Some("abc".into()),
},
SegState {
start: 100,
end: 200,
done: 40,
hash: None,
},
];
save_sidecar(&meta, "http://x/f", Some(200), &segs);
let back = load_sidecar(&meta, "http://x/f", Some(200), 2).unwrap();
assert_eq!(back.len(), 2);
assert_eq!(back[0].done, 100);
assert_eq!(back[0].hash.as_deref(), Some("abc"));
assert!(load_sidecar(&meta, "http://x/other", Some(200), 2).is_none());
assert!(load_sidecar(&meta, "http://x/f", Some(999), 2).is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn resume_verifies_completed_segment_hash() {
let dir = std::env::temp_dir().join("xget-resume-test");
std::fs::create_dir_all(&dir).unwrap();
let p = dir.join("part");
let data: Vec<u8> = (0..10_000u32).map(|i| (i % 251) as u8).collect();
std::fs::write(&p, &data).unwrap();
let good = fafo::hash_range(&p, 0, 10_000).unwrap();
assert_eq!(good, blake3::hash(&data).to_hex().to_string());
let mut bad = data.clone();
bad[5000] ^= 0xff;
assert_ne!(blake3::hash(&bad).to_hex().to_string(), good);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn auto_mirror_rules_cover_known_hosts() {
let u = auto_candidates("https://releases.ubuntu.com/22.04/ubuntu-22.04-desktop-amd64.iso");
assert!(!u.is_empty(), "ubuntu must have candidates");
let k = auto_candidates("https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-6.9.tar.xz");
assert!(k.iter().any(|c| c.contains("mirrors.kernel.org")));
let g = auto_candidates("https://github.com/o/r/releases/download/v1/f.bin");
assert!(g.iter().any(|c| c.contains("ghproxy")));
assert!(auto_candidates("https://example.com/f.bin").is_empty());
}
#[test]
fn auto_mirror_loopback_heuristic_for_bench() {
let u = auto_candidates("http://127.0.0.1:8911/big.bin");
assert!(u.iter().any(|c| c.contains(":8912")));
assert!(!u.iter().any(|c| c == "http://127.0.0.1:8911/big.bin"));
}
#[test]
fn compression_only_without_range() {
assert!(use_compression(false));
assert!(!use_compression(true));
}
}