blackship 0.6.2

A FreeBSD jail manager with state machine control
//! HTTP fetching utilities for downloading FreeBSD releases
//!
//! Provides:
//! - Progress-tracked downloads
//! - SHA256 checksum verification
//! - Retry with exponential backoff

use crate::error::{Error, Result};
use crate::manifest::RetryConfig;
use chrono_machines::{Exponential, Retry};
use rand::{RngExt, rng};
use sha2::{Digest, Sha256};
use std::fs::{self, File};
use std::io::{BufReader, Read, Write};
use std::num::NonZeroU8;
use std::path::Path;
use std::thread;
use std::time::Duration;

/// Create a retry streak from `RetryConfig`.
///
/// Out-of-range values are normalised the way the old builder did: a base
/// above the cap is capped, jitter is clamped to `0.0..=1.0`, and zero
/// attempts means no retries.
pub fn backoff_from_config(config: &RetryConfig) -> Result<Retry> {
    let max = Duration::from_millis(config.max_delay_ms);
    let base = Duration::from_millis(config.base_delay_ms).min(max);
    let jitter = if config.jitter_factor.is_nan() {
        0.0
    } else {
        config.jitter_factor.clamp(0.0, 1.0)
    };
    let multiplier = config.multiplier.clamp(1.0, f64::MAX);
    let shape = Exponential::new(base, multiplier, max, jitter)
        .ok_or_else(|| Error::ConfigValidation("invalid retry backoff configuration".into()))?;
    let attempts = NonZeroU8::new(config.max_attempts).unwrap_or(NonZeroU8::MIN);
    Ok(Retry::new(shape.into(), Some(attempts)))
}

/// Whether a failed request is worth retrying.
///
/// Transport failures and 5xx are transient. Most 4xx are not: a 404 will not
/// become a 200 after five backoff sleeps, so retrying one just stalls the
/// caller for the full budget before reporting what the first response already
/// said. 408 and 429 are the retryable exceptions.
fn is_retryable(err: &ureq::Error) -> bool {
    match err {
        ureq::Error::StatusCode(408 | 429) => true,
        ureq::Error::StatusCode(code) => !(400..500).contains(code),
        _ => true,
    }
}

/// Retry an HTTP call with exponential backoff; `what` labels log and error messages.
fn retry_call<T>(
    url: &str,
    retry_config: &RetryConfig,
    what: &str,
    mut call: impl FnMut() -> std::result::Result<T, ureq::Error>,
) -> Result<T> {
    let mut backoff = backoff_from_config(retry_config)?;
    let mut rng = rng();
    let mut attempt: u8 = 0;

    loop {
        attempt += 1;
        match call() {
            Ok(v) => return Ok(v),
            Err(e) if !is_retryable(&e) => {
                return Err(Error::DownloadFailed(format!(
                    "{what} failed for {url}: {e}"
                )));
            }
            Err(e) => {
                if let Ok(delay) = backoff.failed(rng.random()) {
                    eprintln!(
                        "{what} attempt {attempt} failed, retrying in {}ms...",
                        delay.as_millis()
                    );
                    thread::sleep(delay);
                } else {
                    return Err(Error::DownloadFailed(format!(
                        "{what} failed for {url} after {attempt} attempts: {e}"
                    )));
                }
            }
        }
    }
}

/// Download a file from URL to destination with optional checksum verification
pub fn download_file(
    url: &str,
    dest: &Path,
    expected_sha256: Option<&str>,
    retry_config: &RetryConfig,
) -> Result<()> {
    // Create parent directory if needed
    if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent).map_err(|e| {
            Error::DownloadFailed(format!(
                "Failed to create directory {}: {}",
                parent.display(),
                e
            ))
        })?;
    }

    eprintln!("Downloading: {url}");

    // Make HTTP request with retry
    let response = retry_call(url, retry_config, "Download", || ureq::get(url).call())?;

    // Get content length if available
    let content_length: Option<u64> = response
        .headers()
        .get("Content-Length")
        .and_then(|v| v.to_str().ok())
        .and_then(|s| s.parse().ok());

    if let Some(len) = content_length {
        // Two-decimal display only; exact below 2^53 bytes anyway.
        #[allow(clippy::cast_precision_loss)]
        let megabytes = len as f64 / 1_048_576.0;
        eprintln!("Size: {len} bytes ({megabytes:.2} MB)");
    }

    // Unlink then O_EXCL: never write through a symlink planted at dest.
    let _ = std::fs::remove_file(dest);
    let mut file = std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(dest)
        .map_err(|e| {
            Error::DownloadFailed(format!("Failed to create file {}: {}", dest.display(), e))
        })?;

    // Download with progress
    let mut reader = response.into_body().into_reader();
    let mut hasher = Sha256::new();
    let mut buffer = vec![0u8; 65536]; // 64KB buffer, on the heap
    let mut downloaded: u64 = 0;
    let mut last_progress: u64 = 0;

    loop {
        let bytes_read = reader
            .read(&mut buffer)
            .map_err(|e| Error::DownloadFailed(format!("Read error during download: {e}")))?;

        if bytes_read == 0 {
            break;
        }

        file.write_all(&buffer[..bytes_read])
            .map_err(|e| Error::DownloadFailed(format!("Write error during download: {e}")))?;

        if expected_sha256.is_some() {
            hasher.update(&buffer[..bytes_read]);
        }

        downloaded += bytes_read as u64;

        // Print progress every 10%
        if let Some(total) = content_length
            && let Some(progress) = (downloaded * 100).checked_div(total)
            && progress >= last_progress + 10
        {
            eprintln!("Progress: {progress}% ({downloaded} / {total} bytes)");
            last_progress = progress;
        }
    }

    eprintln!("Downloaded: {downloaded} bytes");

    // Verify checksum if provided
    if let Some(expected) = expected_sha256 {
        let actual = hex::encode(hasher.finalize());
        if actual != expected {
            // Remove the corrupt file
            let _ = fs::remove_file(dest);
            return Err(Error::ChecksumMismatch {
                file: dest.display().to_string(),
                expected: expected.to_string(),
                actual,
            });
        }
        eprintln!("Checksum verified: OK");
    }

    Ok(())
}

/// Compute SHA256 hash of a file
pub fn sha256_file(path: &Path) -> Result<String> {
    let file = File::open(path)
        .map_err(|e| Error::DownloadFailed(format!("Failed to open file for checksum: {e}")))?;

    let mut reader = BufReader::new(file);
    let mut hasher = Sha256::new();
    let mut buffer = vec![0u8; 65536];

    loop {
        let bytes_read = reader
            .read(&mut buffer)
            .map_err(|e| Error::DownloadFailed(format!("Read error computing checksum: {e}")))?;

        if bytes_read == 0 {
            break;
        }

        hasher.update(&buffer[..bytes_read]);
    }

    Ok(hex::encode(hasher.finalize()))
}

/// Fetch a text file (like MANIFEST) and return its contents
pub fn fetch_text(url: &str, retry_config: &RetryConfig) -> Result<String> {
    let response = retry_call(url, retry_config, "Fetch", || ureq::get(url).call())?;

    response
        .into_body()
        .read_to_string()
        .map_err(|e| Error::DownloadFailed(format!("Failed to read response body: {e}")))
}

/// Check if a URL exists (HEAD request)
///
/// A failure that outlives the retry budget is reported as "missing": callers
/// use this to pick a mirror path, and an unreachable URL is indistinguishable
/// from an absent one for that purpose.
pub fn url_exists(url: &str, retry_config: &RetryConfig) -> bool {
    retry_call(url, retry_config, "Probe", || ureq::head(url).call()).is_ok()
}

#[cfg(test)]
mod tests;