summaryrefslogtreecommitdiffstats
path: root/src/watch/digests.rs
blob: 81368503fa1620834547d90d7b93e937ec49f071 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
//! Source digest resolution (§5.3).
//!
//! `sha256sums=('SKIP')` is the hole in the integrity story. We resolve and
//! record the digest of *every* source ourselves, at detection time, regardless
//! of what the PKGBUILD declares — which turns a silent artifact swap into a
//! reviewable (or at least alertable) event.
//!
//! Cost control: only `SKIP`-declared static sources cost bandwidth. Declared
//! checksums are trusted-as-declared for identity because makepkg enforces them
//! at build time; VCS digests come free from the pin we already resolved; local
//! files are already in the mirror.

use crate::config::Config;
use crate::db::{self, *};
use crate::error::Result;
use crate::recipe::{declared_sums, is_hex_digest, SKIP};
use crate::watch::mirror::Tree;

/// Resolve the digest of every `source=()` entry.
pub fn resolve_sources(
    cfg: &Config,
    db: &Db,
    mirror: &std::path::Path,
    commit: &str,
    tree: &Tree,
    recipe: &Recipe,
    pins: &[UpstreamPin],
) -> Result<Vec<SourceDigest>> {
    let mut out = Vec::new();
    for entry in &recipe.source_entries {
        let declared = declared_sums(recipe, entry.index);
        let skip_declared = match &declared {
            Some(d) => d == SKIP || !is_hex_digest(d),
            None => true,
        };

        if entry.is_vcs() {
            // The resolved commit *is* the digest; captured during Stage B where
            // we clone anyway (§5.2), so near-free.
            let pin = pins.iter().find(|p| p.index == entry.index);
            let digest = pin
                .map(|p| p.commit.clone())
                .or_else(|| entry.commit.clone())
                .unwrap_or_default();
            out.push(SourceDigest {
                index: entry.index,
                url: entry.url.clone(),
                kind: entry.vcs.clone().unwrap_or_else(|| "vcs".into()),
                digest,
                size: 0,
                // Computed from the recipe like every other entry (m-19), not
                // hardcoded: the field answers "did the recipe give us a
                // checksum?", and for a VCS source the answer is usually yes-by-
                // absence — which is why renderers must ask `is_vcs` before
                // calling it a missing checksum.
                skip_declared: match declared_sums(recipe, entry.index) {
                    Some(d) => d == SKIP || !is_hex_digest(&d),
                    None => true,
                },
            });
            continue;
        }

        if entry.local {
            let name = entry.filename.clone().unwrap_or_default();
            let path = tree
                .blobs
                .iter()
                .find(|(p, _)| p == &name || p.ends_with(&format!("/{name}")))
                .map(|(p, _)| p.clone());
            let (digest, size) = match path {
                Some(p) => {
                    let bytes = crate::watch::mirror::read_file(mirror, commit, &p)?;
                    let d = crate::hash::hex(&bytes);
                    (d, bytes.len() as u64)
                }
                // A "local" file that is not in the tree is the recipe's bug;
                // record the absence rather than inventing a digest.
                None => (String::new(), 0),
            };
            out.push(SourceDigest {
                index: entry.index,
                url: entry.url.clone(),
                kind: "local".into(),
                digest,
                size,
                skip_declared,
            });
            continue;
        }

        // Static source.
        if !skip_declared {
            // Trusted-as-declared: makepkg verifies it at build time.
            out.push(SourceDigest {
                index: entry.index,
                url: entry.url.clone(),
                kind: "static".into(),
                digest: declared.unwrap_or_default(),
                size: 0,
                skip_declared: false,
            });
            continue;
        }

        // The paid path: download and stream-hash into the cache, which the
        // build then reuses so the bytes are paid for once.
        let (digest, size) = download_and_cache(cfg, db, &entry.url)?;
        out.push(SourceDigest {
            index: entry.index,
            url: entry.url.clone(),
            kind: "static".into(),
            digest,
            size,
            skip_declared: true,
        });
    }
    Ok(out)
}

/// Download `url`, hashing as we go, and record it in `source_cache`.
///
/// This always goes to the network. That is deliberate: the whole point of §5.3
/// is to notice that the bytes behind a `SKIP` source changed while the version
/// did not, and answering from our own cache would make that impossible. The
/// cache exists so the *build* can reuse the bytes it was reviewed against
/// ([`cached_path`]), not so detection can skip looking.
pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> {
    let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16)));
    let (digest, size) = crate::fetch::fetch_to(url, &tmp)?;
    let dest = cfg.source_cache_path(&digest);
    if !dest.exists() {
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::rename(&tmp, &dest)?;
    } else {
        let _ = std::fs::remove_file(&tmp);
    }
    let dest_s = dest.display().to_string();
    db::put_source_cache(&db.writer, url, &digest, size, &dest_s)?;
    Ok((digest, size))
}

/// The cached file holding `digest`, if we still have it. The build uses this
/// so the bytes it consumes are the bytes that were hashed at detection time.
pub fn cached_path(db: &Db, url: &str, digest: &str) -> Option<std::path::PathBuf> {
    db::source_cache_path(db, url, digest)
        .ok()
        .flatten()
        .map(std::path::PathBuf::from)
        .filter(|p| p.exists())
}