Skip to main content

ag_agent/agent/native/
cargo_cache.rs

1//! Per-project Cargo download cache that sandboxed session commands reuse
2//! without ever reaching its files through their own paths.
3//!
4//! Agentty fills the cache outside the sandbox with a fetch that runs no
5//! model output and reads no manifest, configuration, or credentials: it
6//! parses the worktree's `Cargo.lock` as data, keeps only its crates.io
7//! packages, and runs `cargo fetch` for a synthetic workspace that pins
8//! exactly those, in a fresh directory, with a configuration-free
9//! `CARGO_HOME` and an allowlisted environment. Session commands cannot
10//! read the cache at all. The fetch records the canonical crates.io
11//! archives it was asked for and stored only after it ends. Preparing
12//! a session's sandbox then copies the recorded archives its own lockfile
13//! names into the session's `CARGO_HOME`, each verified against the
14//! lockfile's checksum, so a session that edits its copies, or runs without
15//! the sandbox, changes nothing another session uses.
16
17use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use std::fmt::Write as _;
19use std::io::{self, Read as _, Write as _};
20use std::os::fd::OwnedFd;
21use std::os::unix::ffi::OsStrExt as _;
22use std::os::unix::fs::MetadataExt as _;
23use std::path::{Path, PathBuf};
24use std::process::Stdio;
25use std::time::Duration;
26
27use rustix::fs::{self, AtFlags, FileType, Mode, OFlags};
28use sha2::{Digest as _, Sha256};
29
30use super::cargo_lockfile::{LockedPackage, Lockfile};
31use super::sandbox::CommandSandbox;
32
33/// Hexadecimal characters of the project key: the start of the SHA-256 of
34/// the project's main checkout path.
35const PROJECT_KEY_LENGTH: usize = 32;
36/// Hexadecimal characters of the toolchain variant.
37const VARIANT_LENGTH: usize = 16;
38/// Cache subdirectory that the fetch uses as `CARGO_HOME`, which sessions
39/// copy from.
40const HOME_DIRECTORY: &str = "home";
41/// Prefix of the temporary directory holding the synthetic workspace,
42/// where the fetch runs.
43const WORK_PREFIX: &str = "agentty-cargo-fetch-";
44/// Subdirectory of the work directory that the fetch uses as
45/// `CARGO_TARGET_DIR`, so that Cargo writes nothing elsewhere.
46const TARGET_DIRECTORY: &str = "target";
47/// Cache file naming the last finished fetch.
48const GENERATION_FILE: &str = "generation";
49/// First line of a generation file.
50const GENERATION_HEADER: &str = "agentty-cargo-cache 3";
51/// File of a session's `CARGO_HOME` naming the generation and lockfile it
52/// last copied.
53const SESSION_GENERATION_FILE: &str = ".agentty-cache-generation";
54/// Suffix of a session copy until its checksum is verified.
55const PARTIAL_SUFFIX: &str = ".agentty-partial";
56/// Files of a `CARGO_HOME` that Cargo reads as configuration or
57/// credentials, which the cache `CARGO_HOME` must not hold.
58const CARGO_HOME_CONFIGURATION: [&str; 4] =
59    ["config.toml", "config", "credentials.toml", "credentials"];
60/// Files above a working directory that Cargo reads as configuration, and
61/// that `rustup` reads to pick a toolchain.
62const ANCESTOR_CONFIGURATION: [&str; 4] = [
63    ".cargo/config.toml",
64    ".cargo/config",
65    "rust-toolchain.toml",
66    "rust-toolchain",
67];
68/// Deadline for one Cargo run: the version check or the fetch.
69const CARGO_TIMEOUT: Duration = Duration::from_secs(300);
70/// Registry directories of a `CARGO_HOME` holding crate archives.
71const REGISTRY_CACHE: &str = "registry/cache";
72/// Registry index directories of a `CARGO_HOME`.
73const REGISTRY_INDEX: &str = "registry/index";
74/// Index file that names a sparse registry's download location.
75const INDEX_CONFIG: &str = "config.json";
76/// Largest index configuration read.
77const MAX_INDEX_CONFIG_BYTES: u64 = 64 * 1024;
78/// Prefix of the registry directories Cargo names after crates.io.
79const CRATES_IO_DIRECTORY_PREFIX: &str = "index.crates.io-";
80/// Download location crates.io's index configuration names.
81const CRATES_IO_DOWNLOADS: &str = "https://static.crates.io/crates";
82/// Host variables the fetch receives, all others withheld: the executable
83/// search path, the home and toolchain `rustup` needs, and the proxies and
84/// certificate authorities the network may require.
85const ALLOWED_VARIABLES: [&str; 14] = [
86    "CARGO_HTTP_CAINFO",
87    "CARGO_HTTP_PROXY",
88    "HOME",
89    "HTTPS_PROXY",
90    "HTTP_PROXY",
91    "NO_PROXY",
92    "PATH",
93    "RUSTUP_HOME",
94    "RUSTUP_TOOLCHAIN",
95    "SSL_CERT_DIR",
96    "SSL_CERT_FILE",
97    "http_proxy",
98    "https_proxy",
99    "no_proxy",
100];
101
102/// The Cargo download cache of one project.
103#[derive(Clone, Debug, Eq, PartialEq)]
104pub struct TrustedCargoCache {
105    /// Directory of every project's cache, hidden from session commands.
106    cache_root: PathBuf,
107    /// This project's cache.
108    root: PathBuf,
109}
110
111impl TrustedCargoCache {
112    /// Returns the cache, under `cache_root`, of the project whose main
113    /// checkout is `main_checkout`.
114    pub fn for_project(cache_root: &Path, main_checkout: &Path) -> Self {
115        let digest = hex::encode(Sha256::digest(main_checkout.as_os_str().as_bytes()));
116
117        Self {
118            cache_root: cache_root.to_path_buf(),
119            root: cache_root.join(&digest[..PROJECT_KEY_LENGTH]),
120        }
121    }
122
123    /// Fetches the crates.io packages that `worktree`'s `Cargo.lock` pins
124    /// and the cache lacks, calling `on_fetch` first when it fetches.
125    ///
126    /// Only the lockfile is read, as data. The fetch runs the host's
127    /// `cargo` executable, which `environment`'s `PATH` resolves for a bare
128    /// name, for a synthetic workspace that pins exactly those packages, so
129    /// that no path, Git, or other registry source is reached. It reads no
130    /// Cargo configuration and no credentials at all: it runs in a fresh
131    /// directory under the first of `environment`'s `XDG_RUNTIME_DIR` and
132    /// `TMPDIR` whose every ancestor only root or the current user can
133    /// change, so that no other user can plant configuration above it (a
134    /// shared `/tmp` does not qualify); it is skipped without such a
135    /// directory, or when one of
136    /// its ancestors holds Cargo configuration or a toolchain file, with
137    /// the cache as a `CARGO_HOME` that holds neither, and with only the
138    /// allowed host variables: `PATH`, `HOME`, the `rustup` home and
139    /// toolchain, and proxies and certificate authorities. Only archives
140    /// from the canonical crates.io registry are recorded, so a host whose
141    /// network needs a crates.io mirror gets no shared cache, and its
142    /// sessions keep downloading per session. A new Cargo version fetches
143    /// again.
144    ///
145    /// # Errors
146    /// Returns an error when the cache cannot be written, Cargo fails or
147    /// times out, or the fetch left a package uncached; what was fetched
148    /// stays recorded.
149    pub async fn refresh(
150        &self,
151        cargo: &str,
152        worktree: &Path,
153        environment: &BTreeMap<String, String>,
154        on_fetch: impl FnOnce() + Send,
155    ) -> io::Result<()> {
156        let lockfile_worktree = worktree.to_path_buf();
157        let lockfile = tokio::task::spawn_blocking(move || Lockfile::read(&lockfile_worktree))
158            .await
159            .map_err(io::Error::other)?;
160        let Some(lockfile) = lockfile.filter(|lockfile| !lockfile.packages.is_empty()) else {
161            return Ok(());
162        };
163        let home = self.root.join(HOME_DIRECTORY);
164        tokio::fs::create_dir_all(&home).await?;
165        for name in CARGO_HOME_CONFIGURATION {
166            match tokio::fs::remove_file(home.join(name)).await {
167                Err(error) if error.kind() != io::ErrorKind::NotFound => return Err(error),
168                _ => {}
169            }
170        }
171        let candidates = ["XDG_RUNTIME_DIR", "TMPDIR"]
172            .iter()
173            .filter_map(|name| environment.get(*name).map(PathBuf::from))
174            .collect::<Vec<_>>();
175        let work = tokio::task::spawn_blocking(move || {
176            let Some(parent) = candidates
177                .into_iter()
178                .find(|parent| Self::is_private(parent))
179            else {
180                return io::Result::Ok(None);
181            };
182            let work = tempfile::Builder::new()
183                .prefix(WORK_PREFIX)
184                .tempdir_in(parent)?;
185
186            Ok((!Self::reads_configuration(work.path())).then_some(work))
187        })
188        .await
189        .map_err(io::Error::other)??;
190        let Some(work) = work else {
191            tracing::debug!("No private directory free of Cargo configuration; not caching");
192
193            return Ok(());
194        };
195        let fetch_environment = self.fetch_environment(environment, work.path());
196        let variant = Self::variant(cargo, work.path(), &fetch_environment).await?;
197        let previous = Generation::load(&self.root).await;
198        let covered = previous
199            .as_ref()
200            .filter(|generation| generation.variant == variant)
201            .map(|generation| generation.missing.clone());
202        if let Some(missing) = covered
203            && Self::uncached(&home, &lockfile.packages, &missing)
204                .await
205                .is_empty()
206        {
207            return Ok(());
208        }
209
210        on_fetch();
211        Self::fetch(cargo, &lockfile, work.path(), &fetch_environment).await?;
212        let missing = Self::uncached(&home, &lockfile.packages, &[]).await;
213        let scan_home = home.clone();
214        let requested = lockfile.packages.clone();
215        let mut files =
216            tokio::task::spawn_blocking(move || Generation::scan(&scan_home, &requested))
217                .await
218                .map_err(io::Error::other)?;
219        let number = previous.as_ref().map_or(0, |generation| generation.number) + 1;
220        let earlier = previous.filter(|generation| generation.variant == variant);
221        files.extend(earlier.into_iter().flat_map(|generation| generation.files));
222        files.sort();
223        files.dedup();
224        Generation {
225            files,
226            missing: missing.clone(),
227            number,
228            variant,
229        }
230        .write(&self.root)
231        .await?;
232        if !missing.is_empty() {
233            return Err(io::Error::other(format!(
234                "cargo fetch left {} packages uncached",
235                missing.len()
236            )));
237        }
238
239        Ok(())
240    }
241
242    /// Returns the directory of every project's cache, hidden from session
243    /// commands: Agentty copies what sessions need, so commands neither read
244    /// what the fetch stored nor hold Cargo's locks on it.
245    pub(crate) fn hidden_path(&self) -> &Path {
246        &self.cache_root
247    }
248
249    /// Copies into `cargo`, the open handle of a session's `CARGO_HOME`,
250    /// the recorded archives and index metadata that `worktree`'s
251    /// `Cargo.lock` names, keeping every entry the session already has.
252    ///
253    /// Each archive is copied under a temporary name, kept only when its
254    /// SHA-256 matches the lockfile's checksum, and then linked into place,
255    /// so a truncated or tampered file never appears under the name Cargo
256    /// trusts. Commands may have rewritten `cargo` on earlier turns, so
257    /// every change is made relative to handles opened without following
258    /// links: a link a command planted in place of a directory skips the
259    /// files below it. Nothing happens before a fetch finished or while the
260    /// session already copied the current generation for the same
261    /// lockfile. Failures are ignored: a missed entry is downloaded by the
262    /// session.
263    pub(crate) fn copy_into(&self, cargo: &OwnedFd, worktree: &Path) {
264        let Some(generation) = Generation::read(&self.root) else {
265            return;
266        };
267        let Some(lockfile) = Lockfile::read(worktree) else {
268            return;
269        };
270        let marker = format!("{}\n{}", generation.number, lockfile.digest);
271        if Self::session_generation(cargo).as_deref() == Some(marker.as_str()) {
272            return;
273        }
274        let home = self.root.join(HOME_DIRECTORY);
275        let recorded = generation
276            .files
277            .iter()
278            .map(String::as_str)
279            .collect::<HashSet<_>>();
280        let mut archives = HashMap::<&str, Vec<(&str, &str)>>::new();
281        let mut indexes = BTreeSet::new();
282        for file in &generation.files {
283            if file.starts_with(REGISTRY_CACHE)
284                && let Some((parent, name)) = file.rsplit_once('/')
285            {
286                archives.entry(name).or_default().push((file, parent));
287            }
288            if let Some(index) = file.strip_prefix(REGISTRY_INDEX)
289                && let Some(directory) = index.trim_start_matches('/').split('/').next()
290            {
291                indexes.insert(directory);
292            }
293        }
294        let mut wanted = indexes
295            .iter()
296            .map(|index| format!("{REGISTRY_INDEX}/{index}/{INDEX_CONFIG}"))
297            .collect::<Vec<_>>();
298        let mut directories = SessionDirectories::new(cargo);
299        for package in &lockfile.packages {
300            let name = package.archive_name();
301            for (file, parent) in archives.get(name.as_str()).into_iter().flatten() {
302                if let Some(directory) = directories.open(parent) {
303                    let _ =
304                        Self::copy_archive(&home.join(file), directory, &name, &package.checksum);
305                }
306            }
307            wanted.extend(
308                indexes
309                    .iter()
310                    .map(|index| format!("{REGISTRY_INDEX}/{index}/{}", package.index_entry())),
311            );
312        }
313        for file in wanted
314            .iter()
315            .filter(|file| recorded.contains(file.as_str()))
316        {
317            if let Some((parent, name)) = file.rsplit_once('/')
318                && let Some(directory) = directories.open(parent)
319            {
320                let _ = Self::copy_absent(&home.join(file), directory, name);
321            }
322        }
323        let _ = Self::record_session_generation(cargo, &marker);
324    }
325
326    /// Returns the host `environment` the fetch runs with: only the allowed
327    /// variables, plus the cache as `CARGO_HOME` and a target directory in
328    /// `work`.
329    fn fetch_environment(
330        &self,
331        environment: &BTreeMap<String, String>,
332        work: &Path,
333    ) -> BTreeMap<String, String> {
334        let mut fetch_environment = environment
335            .iter()
336            .filter(|(name, _)| ALLOWED_VARIABLES.contains(&name.as_str()))
337            .map(|(name, value)| (name.clone(), value.clone()))
338            .collect::<BTreeMap<_, _>>();
339        fetch_environment.insert(
340            "CARGO_HOME".to_string(),
341            self.root.join(HOME_DIRECTORY).display().to_string(),
342        );
343        fetch_environment.insert(
344            "CARGO_TARGET_DIR".to_string(),
345            work.join(TARGET_DIRECTORY).display().to_string(),
346        );
347
348        fetch_environment
349    }
350
351    /// Returns whether `directory` resolves to a path whose every ancestor
352    /// is owned by root or the current user and writable by neither its
353    /// group nor others, so that no other user can create entries above
354    /// it.
355    fn is_private(directory: &Path) -> bool {
356        let Ok(directory) = std::fs::canonicalize(directory) else {
357            return false;
358        };
359        let user = rustix::process::geteuid().as_raw();
360
361        directory.ancestors().all(|ancestor| {
362            std::fs::metadata(ancestor).is_ok_and(|metadata| {
363                (metadata.uid() == 0 || metadata.uid() == user) && metadata.mode() & 0o022 == 0
364            })
365        })
366    }
367
368    /// Returns whether `work` or one of its ancestors holds Cargo
369    /// configuration or a toolchain file, which Cargo or `rustup` would
370    /// read when run in `work`.
371    fn reads_configuration(work: &Path) -> bool {
372        work.ancestors().any(|directory| {
373            ANCESTOR_CONFIGURATION
374                .iter()
375                .any(|name| std::fs::symlink_metadata(directory.join(name)).is_ok())
376        })
377    }
378
379    /// Returns the variant that a fetch with `cargo`'s version produces:
380    /// Cargo has named its registry directories differently across
381    /// versions.
382    ///
383    /// # Errors
384    /// Returns an error when `cargo -V` cannot run, fails, or times out.
385    async fn variant(
386        cargo: &str,
387        directory: &Path,
388        environment: &BTreeMap<String, String>,
389    ) -> io::Result<String> {
390        let version = Self::run_cargo(cargo, "-V", directory, environment).await?;
391
392        Ok(hex::encode(Sha256::digest(&version))[..VARIANT_LENGTH].to_string())
393    }
394
395    /// Returns the archive names of `packages` that `home` holds in no
396    /// crates.io registry directory, except those listed as `missing`.
397    async fn uncached(home: &Path, packages: &[LockedPackage], missing: &[String]) -> Vec<String> {
398        let home = home.to_path_buf();
399        let wanted = packages
400            .iter()
401            .map(LockedPackage::archive_name)
402            .filter(|archive| !missing.contains(archive))
403            .collect::<Vec<_>>();
404
405        tokio::task::spawn_blocking(move || {
406            let registries = Generation::crates_io_directories(&home);
407            wanted
408                .into_iter()
409                .filter(|archive| {
410                    !registries.iter().any(|registry| {
411                        std::fs::symlink_metadata(
412                            home.join(REGISTRY_CACHE).join(registry).join(archive),
413                        )
414                        .is_ok_and(|metadata| metadata.is_file())
415                    })
416                })
417                .collect()
418        })
419        .await
420        .unwrap_or_default()
421    }
422
423    /// Writes the synthetic workspace for `lockfile` into `work` and runs
424    /// `cargo fetch` there.
425    ///
426    /// The synthetic lockfile may still need updating, for example where
427    /// the worktree enabled features the synthetic workspace does not, so
428    /// Cargo runs without `--locked`; the exact version pins keep every
429    /// package at its locked version, and only the synthetic lockfile
430    /// changes.
431    ///
432    /// # Errors
433    /// Returns an error when the workspace cannot be written, or Cargo
434    /// cannot start, fails, or times out.
435    async fn fetch(
436        cargo: &str,
437        lockfile: &Lockfile,
438        work: &Path,
439        environment: &BTreeMap<String, String>,
440    ) -> io::Result<()> {
441        tokio::fs::write(work.join("Cargo.toml"), lockfile.synthetic_manifest()).await?;
442        tokio::fs::write(work.join("Cargo.lock"), lockfile.synthetic_lockfile()).await?;
443        tokio::fs::write(work.join("lib.rs"), "").await?;
444
445        Self::run_cargo(cargo, "fetch", work, environment)
446            .await
447            .map(drop)
448    }
449
450    /// Runs `cargo` with the one argument `command` in `directory` with
451    /// only `environment`, no input, and its errors discarded, within the
452    /// cargo deadline, and returns its standard output.
453    ///
454    /// # Errors
455    /// Returns an error when Cargo cannot start, fails, or times out.
456    async fn run_cargo(
457        cargo: &str,
458        command: &str,
459        directory: &Path,
460        environment: &BTreeMap<String, String>,
461    ) -> io::Result<Vec<u8>> {
462        let output = tokio::process::Command::new(cargo)
463            .arg(command)
464            .current_dir(directory)
465            .env_clear()
466            .envs(environment)
467            .stdin(Stdio::null())
468            .stderr(Stdio::null())
469            .kill_on_drop(true)
470            .output();
471        let output = tokio::time::timeout(CARGO_TIMEOUT, output)
472            .await
473            .map_err(|_| io::Error::from(io::ErrorKind::TimedOut))??;
474        if !output.status.success() {
475            return Err(io::Error::other(format!(
476                "cargo {command} failed with {}",
477                output.status
478            )));
479        }
480
481        Ok(output.stdout)
482    }
483
484    /// Copies `source`, an archive of the cache, to `name` in the session
485    /// `directory` unless an entry of that name exists, keeping it only when
486    /// its SHA-256 is `checksum`.
487    ///
488    /// # Errors
489    /// Returns the filesystem error, or a mismatch, that keeps it out.
490    fn copy_archive(
491        source: &Path,
492        directory: &OwnedFd,
493        name: &str,
494        checksum: &str,
495    ) -> io::Result<()> {
496        if fs::statat(directory, name, AtFlags::SYMLINK_NOFOLLOW).is_ok() {
497            return Ok(());
498        }
499        let partial = format!(".{name}{PARTIAL_SUFFIX}");
500        let _ = fs::unlinkat(directory, partial.as_str(), AtFlags::empty());
501        let mut source = std::fs::File::open(source)?;
502        let mut destination = std::fs::File::from(fs::openat(
503            directory,
504            partial.as_str(),
505            OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
506            Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::ROTH,
507        )?);
508        let mut hasher = Sha256::new();
509        let mut buffer = vec![0; 64 * 1024];
510        loop {
511            let read = source.read(&mut buffer)?;
512            if read == 0 {
513                break;
514            }
515            hasher.update(&buffer[..read]);
516            destination.write_all(&buffer[..read])?;
517        }
518        drop(destination);
519        let verified = hex::encode(hasher.finalize()) == checksum;
520        let linked = if verified {
521            fs::linkat(
522                directory,
523                partial.as_str(),
524                directory,
525                name,
526                AtFlags::empty(),
527            )
528            .map_err(io::Error::from)
529        } else {
530            Err(io::Error::from(io::ErrorKind::InvalidData))
531        };
532        let _ = fs::unlinkat(directory, partial.as_str(), AtFlags::empty());
533
534        linked
535    }
536
537    /// Returns what the session behind `cargo` last copied.
538    fn session_generation(cargo: &OwnedFd) -> Option<String> {
539        let descriptor = fs::openat(
540            cargo,
541            SESSION_GENERATION_FILE,
542            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
543            Mode::empty(),
544        )
545        .ok()?;
546        let mut contents = String::new();
547        std::fs::File::from(descriptor)
548            .take(256)
549            .read_to_string(&mut contents)
550            .ok()?;
551
552        Some(contents)
553    }
554
555    /// Records that the session behind `cargo` copied `marker`.
556    ///
557    /// # Errors
558    /// Returns the filesystem error that keeps it from being recorded.
559    fn record_session_generation(cargo: &OwnedFd, marker: &str) -> io::Result<()> {
560        // Commands may have planted a FIFO here: never block on opening it,
561        // and write only a regular file.
562        let descriptor = fs::openat(
563            cargo,
564            SESSION_GENERATION_FILE,
565            OFlags::WRONLY | OFlags::CREATE | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
566            Mode::RUSR | Mode::WUSR,
567        )?;
568        if !FileType::from_raw_mode(fs::fstat(&descriptor)?.st_mode).is_file() {
569            return Err(io::Error::from(io::ErrorKind::InvalidInput));
570        }
571        fs::ftruncate(&descriptor, 0)?;
572
573        std::fs::File::from(descriptor).write_all(marker.as_bytes())
574    }
575
576    /// Copies `source`, a file of the cache, to `name` in `directory` unless
577    /// an entry of that name exists.
578    ///
579    /// # Errors
580    /// Returns the filesystem error that keeps it from being copied.
581    fn copy_absent(source: &Path, directory: &OwnedFd, name: &str) -> io::Result<()> {
582        let mut source = std::fs::File::open(source)?;
583        let descriptor = fs::openat(
584            directory,
585            name,
586            OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
587            Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::ROTH,
588        )?;
589        io::copy(&mut source, &mut std::fs::File::from(descriptor))?;
590
591        Ok(())
592    }
593}
594
595/// The record of one finished fetch.
596#[derive(Debug, Eq, PartialEq)]
597struct Generation {
598    /// Files of the cache `CARGO_HOME` sessions copy, relative to it.
599    files: Vec<String>,
600    /// Archive names the fetch was asked for but did not store.
601    missing: Vec<String>,
602    /// Number of finished fetches so far.
603    number: u64,
604    /// Cargo version and host configuration the fetch ran with.
605    variant: String,
606}
607
608impl Generation {
609    /// Reads the generation of the cache at `root`, or `None` before its
610    /// first finished fetch.
611    fn read(root: &Path) -> Option<Self> {
612        Self::parse(&std::fs::read_to_string(root.join(GENERATION_FILE)).ok()?)
613    }
614
615    /// Reads the generation of the cache at `root` without blocking.
616    async fn load(root: &Path) -> Option<Self> {
617        Self::parse(
618            &tokio::fs::read_to_string(root.join(GENERATION_FILE))
619                .await
620                .ok()?,
621        )
622    }
623
624    /// Parses the contents of a generation file.
625    fn parse(contents: &str) -> Option<Self> {
626        let mut lines = contents.lines();
627        if lines.next()? != GENERATION_HEADER {
628            return None;
629        }
630        let number = lines.next()?.parse().ok()?;
631        let variant = lines.next()?.to_string();
632        let mut files = Vec::new();
633        let mut missing = Vec::new();
634        for line in lines {
635            if let Some(file) = line.strip_prefix("file ")
636                && Self::is_relative_file(file)
637            {
638                files.push(file.to_string());
639            } else if let Some(archive) = line.strip_prefix("missing ") {
640                missing.push(archive.to_string());
641            }
642        }
643
644        Some(Self {
645            files,
646            missing,
647            number,
648            variant,
649        })
650    }
651
652    /// Lists the files of `home`, the cache `CARGO_HOME`, that sessions
653    /// may copy for the `requested` packages: their crate archives, their
654    /// index entries, and each index's configuration, as regular files with
655    /// plain relative paths.
656    fn scan(home: &Path, requested: &[LockedPackage]) -> Vec<String> {
657        let mut files = Vec::new();
658        for registry in Self::crates_io_directories(home) {
659            let archives = home.join(REGISTRY_CACHE).join(&registry);
660            let index = home.join(REGISTRY_INDEX).join(&registry);
661            files.push(index.join(INDEX_CONFIG));
662            for package in requested {
663                files.push(archives.join(package.archive_name()));
664                files.push(index.join(package.index_entry()));
665            }
666        }
667        files.retain(|file| {
668            std::fs::symlink_metadata(file).is_ok_and(|metadata| metadata.is_file())
669        });
670
671        let mut relative = files
672            .iter()
673            .filter_map(|file| file.strip_prefix(home).ok()?.to_str())
674            .filter(|file| Self::is_relative_file(file))
675            .map(str::to_string)
676            .collect::<Vec<_>>();
677        relative.sort();
678
679        relative
680    }
681
682    /// Returns the names of the registry directories of `home` that hold
683    /// canonical crates.io: named as Cargo names crates.io's, with an index
684    /// configuration that downloads from crates.io and requires no
685    /// authentication. Every other registry is ignored.
686    fn crates_io_directories(home: &Path) -> Vec<String> {
687        std::fs::read_dir(home.join(REGISTRY_INDEX))
688            .into_iter()
689            .flatten()
690            .flatten()
691            .filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
692            .filter_map(|entry| entry.file_name().into_string().ok())
693            .filter(|name| {
694                name.starts_with(CRATES_IO_DIRECTORY_PREFIX) && Self::is_relative_file(name)
695            })
696            .filter(|name| {
697                let config = home.join(REGISTRY_INDEX).join(name).join(INDEX_CONFIG);
698                let mut contents = Vec::new();
699                let read = std::fs::File::open(config)
700                    .and_then(|file| file.take(MAX_INDEX_CONFIG_BYTES).read_to_end(&mut contents));
701
702                read.is_ok()
703                    && serde_json::from_slice::<serde_json::Value>(&contents).is_ok_and(|config| {
704                        config.get("dl").and_then(serde_json::Value::as_str)
705                            == Some(CRATES_IO_DOWNLOADS)
706                            && config
707                                .get("auth-required")
708                                .is_none_or(|required| required == &serde_json::Value::Bool(false))
709                    })
710            })
711            .collect()
712    }
713
714    /// Returns whether `file` is a plain relative path of named components,
715    /// as the generation file can hold it.
716    fn is_relative_file(file: &str) -> bool {
717        !file.is_empty()
718            && !file.contains('\n')
719            && file
720                .split('/')
721                .all(|component| !component.is_empty() && component != "." && component != "..")
722    }
723
724    /// Writes this generation for the cache at `root` through a temporary
725    /// file of its own, replacing the old one at once, so concurrent
726    /// writers never interleave.
727    ///
728    /// # Errors
729    /// Returns the filesystem error that keeps it from being written.
730    async fn write(&self, root: &Path) -> io::Result<()> {
731        let mut contents = format!("{GENERATION_HEADER}\n{}\n{}\n", self.number, self.variant);
732        for file in &self.files {
733            let _ = writeln!(contents, "file {file}");
734        }
735        for archive in &self.missing {
736            let _ = writeln!(contents, "missing {archive}");
737        }
738        let root = root.to_path_buf();
739
740        tokio::task::spawn_blocking(move || {
741            let mut pending = tempfile::NamedTempFile::new_in(&root)?;
742            pending.write_all(contents.as_bytes())?;
743            pending
744                .persist(root.join(GENERATION_FILE))
745                .map(drop)
746                .map_err(io::Error::from)
747        })
748        .await
749        .map_err(io::Error::other)?
750    }
751}
752
753/// Directory handles inside a session's `CARGO_HOME`, opened one component
754/// at a time without following links.
755struct SessionDirectories<'a> {
756    cargo: &'a OwnedFd,
757    opened: HashMap<String, OwnedFd>,
758}
759
760impl<'a> SessionDirectories<'a> {
761    /// Starts at `cargo`, the open session `CARGO_HOME`.
762    fn new(cargo: &'a OwnedFd) -> Self {
763        Self {
764            cargo,
765            opened: HashMap::new(),
766        }
767    }
768
769    /// Returns the handle of `relative`, creating each missing component,
770    /// or `None` when a component is not a real directory.
771    fn open(&mut self, relative: &str) -> Option<&OwnedFd> {
772        let mut prefix_end = 0_usize;
773        for component in relative.split('/') {
774            let parent_prefix = &relative[..prefix_end.saturating_sub(1)];
775            prefix_end += component.len() + 1;
776            let prefix = &relative[..prefix_end - 1];
777            if self.opened.contains_key(prefix) {
778                continue;
779            }
780            let parent = if parent_prefix.is_empty() {
781                self.cargo
782            } else {
783                self.opened.get(parent_prefix)?
784            };
785            // An existing directory is fine; anything else fails the open.
786            let _ = fs::mkdirat(parent, component, Mode::RWXU);
787            let opened = fs::openat(
788                parent,
789                component,
790                CommandSandbox::directory_flags(),
791                Mode::empty(),
792            )
793            .ok()?;
794            self.opened.insert(prefix.to_string(), opened);
795        }
796
797        self.opened.get(relative)
798    }
799}
800
801#[cfg(test)]
802#[path = "cargo_cache_test.rs"]
803mod tests;