proxyparser 0.2.0

A cross-platform system proxy detector with strong support for complex enterprise PAC scripts
Documentation
// src/pac/downloader.rs
use crate::{log_error, log_info};
use reqwest::blocking::Client;
use std::fs;
use std::path::Path;
use std::time::Duration;
use url::Url;

pub fn download_pac(pac_url: &str) -> Result<String, Box<dyn std::error::Error>> {
    log_info!("Downloading PAC script from: {}", pac_url);

    if let Some(path) = pac_file_path(pac_url) {
        let text = fs::read_to_string(&path)?;
        log_info!("PAC script loaded from file ({} bytes)", text.len());
        return Ok(text);
    }

    let client = Client::builder().timeout(Duration::from_secs(15)).build()?;

    let response = client.get(pac_url).send()?;

    if !response.status().is_success() {
        log_error!("PAC download failed: HTTP {}", response.status());
        return Err(format!("HTTP {}", response.status()).into());
    }

    let text = response.text()?;
    log_info!("PAC script downloaded successfully ({} bytes)", text.len());
    Ok(text)
}

fn pac_file_path(pac_url: &str) -> Option<std::path::PathBuf> {
    let trimmed = pac_url.trim();
    if trimmed.is_empty() {
        return None;
    }

    if let Ok(url) = Url::parse(trimmed) {
        if url.scheme() == "file" {
            return url.to_file_path().ok();
        }
        return None;
    }

    let path = Path::new(trimmed);
    if path.is_file() {
        return Some(path.to_path_buf());
    }
    None
}

#[cfg(test)]
mod tests {
    use super::pac_file_path;
    use std::fs;

    #[test]
    fn detects_existing_local_pac_path() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("proxyparser-test-{}.pac", std::process::id()));
        fs::write(&path, "function FindProxyForURL() { return 'DIRECT'; }").unwrap();

        assert_eq!(pac_file_path(path.to_str().unwrap()), Some(path.clone()));

        let _ = fs::remove_file(path);
    }
}