summaryrefslogtreecommitdiffstats
path: root/src/fetch.rs
blob: c1c4575ed5bbb7a59e049e5c2fbe86a1bde6a1de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//! Outbound HTTP. `ureq` is blocking, which is the whole point of this stack
//! (DESIGN.md §4: "`reqwest` pulls in tokio even in blocking mode — avoid").
//!
//! `file://` is supported as a first-class scheme so the test corpus can serve
//! sources from disk with no network (§16a).

use std::io::{Read, Write};
use std::path::PathBuf;

use crate::error::{Error, Result};

pub enum Body {
    File(std::fs::File),
    Http(Box<dyn Read + Send>),
}

impl Read for Body {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            Body::File(f) => f.read(buf),
            Body::Http(r) => r.read(buf),
        }
    }
}

/// Open a URL for streaming. Never buffers the whole body: sources are hashed
/// while they are written into the cache (§5.3).
pub fn open(url: &str) -> Result<(Body, Option<u64>)> {
    if let Some(path) = url.strip_prefix("file://") {
        let p = path.trim_start_matches('/');
        let p = PathBuf::from(format!("/{p}"));
        let f = std::fs::File::open(&p).map_err(|e| Error::Http(format!("{url}: {e}")))?;
        let len = f.metadata().map(|m| m.len()).ok();
        return Ok((Body::File(f), len));
    }
    if url.starts_with("http://") || url.starts_with("https://") {
        let resp = ureq::get(url)
            .timeout(std::time::Duration::from_secs(300))
            .call()
            .map_err(|e| Error::Http(format!("{url}: {e}")))?;
        let len = resp
            .header("content-length")
            .and_then(|v| v.parse::<u64>().ok());
        return Ok((Body::Http(resp.into_reader()), len));
    }
    Err(Error::invalid(format!("unsupported url scheme: {url}")))
}

/// Fetch `url` into `dest`, returning `(sha256, size)`.
pub fn fetch_to(url: &str, dest: &std::path::Path) -> Result<(String, u64)> {
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let (body, _len) = open(url)?;
    let mut tmp = dest.as_os_str().to_os_string();
    tmp.push(".part");
    let tmp = PathBuf::from(tmp);
    let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?);
    let (digest, size) = crate::hash::digest_reader(std::io::BufReader::new(body), Some(&mut file))
        .map_err(|e| Error::Http(format!("{url}: {e}")))?;
    file.flush()?;
    // Rename into place: a half-written cache entry must never be visible.
    std::fs::rename(&tmp, dest)?;
    Ok((digest, size))
}