xget 0.1.0

xget: fast multi-connection download manager for the terminal: segmented Range downloads, queue, torrents, and curl-like requests.
use std::path::Path;
use std::time::Duration;

use reqwest::header::{ACCEPT_ENCODING, RANGE};
use reqwest::{Client, Response};

pub fn tuning_status() -> &'static str {
    #[cfg(target_os = "linux")]
    {
        if let Ok(list) =
            std::fs::read_to_string("/proc/sys/net/ipv4/tcp_available_congestion_control")
        {
            if list.split_whitespace().any(|c| c == "bbr") {
                "bbr available in the kernel (choice left to the system)"
            } else {
                "without bbr in the kernel (reno/cubic) — skip, default congestion control"
            }
        } else {
            "missing /proc (container?) — skip"
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        return "non-Linux — TCP_CONGESTION does not apply, skip";
    }
}

pub fn tcp_tuning_report() -> String {
    #[cfg(not(target_os = "linux"))]
    {
        return "TCP tuning applies to Linux only — skip on this system.".to_string();
    }
    #[cfg(target_os = "linux")]
    {
        let avail = std::fs::read_to_string("/proc/sys/net/ipv4/tcp_available_congestion_control")
            .unwrap_or_default();
        let cur = std::fs::read_to_string("/proc/sys/net/ipv4/tcp_congestion_control")
            .unwrap_or_default()
            .trim()
            .to_string();
        let rmem = std::fs::read_to_string("/proc/sys/net/core/rmem_max")
            .unwrap_or_default()
            .trim()
            .to_string();
        let wmem = std::fs::read_to_string("/proc/sys/net/core/wmem_max")
            .unwrap_or_default()
            .trim()
            .to_string();
        let has_bbr = avail.split_whitespace().any(|c| c == "bbr");
        let mut out = String::new();
        out.push_str(&format!(
            "current: congestion_control={} rmem_max={} wmem_max={}\n",
            if cur.is_empty() { "?" } else { &cur },
            if rmem.is_empty() { "?" } else { &rmem },
            if wmem.is_empty() { "?" } else { &wmem }
        ));
        out.push_str(&format!(
            "available: {}\n",
            if avail.trim().is_empty() {
                "? (missing /proc?)".to_string()
            } else {
                avail.trim().to_string()
            }
        ));
        if has_bbr && cur != "bbr" {
            out.push_str("proposal: net.ipv4.tcp_congestion_control=bbr\n");
        } else if has_bbr {
            out.push_str("bbr already active — nothing to change.\n");
        } else {
            out.push_str("missing bbr in the kernel — leave Reno/Cubic, not setting anything.\n");
        }
        out.push_str("proposal: net.core.rmem_max=16777216 net.core.wmem_max=16777216\n");
        out.push_str("applied only with explicit consent: `xget config --tcp-tuning --yes` (requires root, sysctl -w).");
        out
    }
}

pub fn apply_tcp_tuning() -> anyhow::Result<String> {
    #[cfg(not(target_os = "linux"))]
    {
        anyhow::bail!("TCP tuning on Linux only");
    }
    #[cfg(target_os = "linux")]
    {
        let avail = std::fs::read_to_string("/proc/sys/net/ipv4/tcp_available_congestion_control")
            .unwrap_or_default();
        let has_bbr = avail.split_whitespace().any(|c| c == "bbr");
        let mut applied = Vec::new();
        if has_bbr {
            let st = std::process::Command::new("sysctl")
                .args(["-w", "net.ipv4.tcp_congestion_control=bbr"])
                .output()
                .map_err(|e| anyhow::anyhow!("cannot run sysctl: {e}"))?;
            if !st.status.success() {
                let msg = String::from_utf8_lossy(&st.stderr);
                anyhow::bail!("sysctl bbr failed (root?): {msg}");
            }
            applied.push("net.ipv4.tcp_congestion_control=bbr".to_string());
        }
        for key in ["net.core.rmem_max=16777216", "net.core.wmem_max=16777216"] {
            let st = std::process::Command::new("sysctl")
                .args(["-w", key])
                .output()
                .map_err(|e| anyhow::anyhow!("cannot run sysctl: {e}"))?;
            if !st.status.success() {
                let msg = String::from_utf8_lossy(&st.stderr);
                anyhow::bail!("sysctl {key} failed (root?): {msg}");
            }
            applied.push(key.to_string());
        }
        if applied.is_empty() {
            anyhow::bail!("nothing to apply");
        }
        Ok(applied.join(", "))
    }
}

pub async fn prefetch_dns(url: &str) {
    let host = match url::Url::parse(url)
        .ok()
        .and_then(|u| u.host_str().map(str::to_owned))
    {
        Some(h) => h,
        None => return,
    };
    let _ = tokio::time::timeout(
        Duration::from_secs(3),
        tokio::net::lookup_host((host.as_str(), 80)),
    )
    .await;
}

pub async fn probe_h3(url: &str) -> bool {
    #[cfg(feature = "http3")]
    {
        let client = match Client::builder()
            .user_agent("xget/0.1 (+https://github.com/JustRoccat/xget)")
            .build()
        {
            Ok(c) => c,
            Err(_) => return false,
        };
        match tokio::time::timeout(
            Duration::from_secs(3),
            client.get(url).header(RANGE, "bytes=0-0").send(),
        )
        .await
        {
            Ok(Ok(resp)) => {
                let h3 = resp.version() == http::Version::HTTP_3;
                let _ = tokio::time::timeout(Duration::from_secs(10), resp.bytes()).await;
                h3
            }
            _ => false,
        }
    }
    #[cfg(not(feature = "http3"))]
    {
        let _ = url;
        false
    }
}

pub async fn race_range(client: &Client, urls: &[String], range: &str) -> Option<Response> {
    let retry_after = |r: &Response| -> Duration {
        r.headers()
            .get(reqwest::header::RETRY_AFTER)
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.trim().parse::<u64>().ok())
            .map(|s| Duration::from_secs(s.clamp(1, 30)))
            .unwrap_or(Duration::from_secs(2))
    };
    let one = |u: &String| {
        client
            .get(u)
            .header(RANGE, range)
            .header(ACCEPT_ENCODING, "identity")
    };
    if urls.len() <= 1 {
        for _ in 0..8 {
            let r = one(&urls[0]).send().await.ok()?;
            if r.status() == reqwest::StatusCode::PARTIAL_CONTENT {
                return Some(r);
            }
            if r.status() == reqwest::StatusCode::TOO_MANY_REQUESTS {
                tokio::time::sleep(retry_after(&r)).await;
                continue;
            }
            return None;
        }
        return None;
    }
    let futs = urls.iter().map(|u| {
        let f = async {
            let r = one(u).send().await.map_err(|_| ())?;
            if r.status() == reqwest::StatusCode::PARTIAL_CONTENT {
                Ok::<_, ()>(r)
            } else {
                Err(())
            }
        };
        Box::pin(f)
    });
    futures::future::select_ok(futs).await.ok().map(|(r, _)| r)
}

pub fn hash_range(path: &Path, start: u64, len: u64) -> Option<String> {
    crate::engine::hash_range(path, start, len)
}