Skip to main content

chainguard_sandbox/workspaces/
files.rs

1//! File helpers: an atomic write over Exec, and tar archives of local directories.
2
3use std::io::{Read, Write};
4use std::path::Path;
5
6use super::Client;
7use super::exec::{ExecOptions, guest_path};
8use crate::{Error, Result};
9
10/// Decides whether to leave out a path (relative, slash-separated) and, for a directory,
11/// everything under it. The second argument is whether it is a directory.
12pub type SkipFn<'a> = &'a dyn Fn(&str, bool) -> bool;
13
14impl Client {
15    /// Atomically replaces `path` (creating parent directories) with `data`, with permission bits
16    /// `mode`. It refuses an empty path and an existing directory (exit code 21, as an
17    /// [`Error::Exit`]).
18    pub async fn write_file(&self, name: &str, path: &str, data: Vec<u8>, mode: u32) -> Result<()> {
19        if path.trim().is_empty() {
20            return Err(Error::other("workspaces: write_file needs a file path"));
21        }
22        const SCRIPT: &str = concat!(
23            r#"p=$1; if [ -d "$p" ]; then echo "$p: is a directory" >&2; cat >/dev/null; exit 21; fi; "#,
24            r#"d=$(dirname -- "$p") && mkdir -p -- "$d" && t="$d/.chainguard-sandbox-write.$$" && cat > "$t" && chmod "$2" "$t" && mv -f -- "$t" "$p" || { rm -f -- "$t"; exit 1; }"#
25        );
26        let o = ExecOptions {
27            stdin: data,
28            ..Default::default()
29        };
30        self.shell(
31            name,
32            SCRIPT,
33            o,
34            &[guest_path(path), format!("{:o}", mode & 0o777)],
35        )
36        .await?;
37        Ok(())
38    }
39}
40
41/// Writes `dir` as an uncompressed tar stream, with the rules chainctl documents for its workspace
42/// upload: symlinks travel as links; sockets, devices and FIFOs are skipped; entries are owned by
43/// root. A symlinked `dir` is resolved first. A file that changes size while it is being written is
44/// truncated or zero-padded to the size in its header, rather than aborting the tar.
45pub fn tar_dir<W: Write>(w: W, dir: &Path, skip: Option<SkipFn<'_>>) -> Result<W> {
46    let root = std::fs::canonicalize(dir).map_err(|e| Error::io(dir.display().to_string(), e))?;
47    let md = std::fs::metadata(&root).map_err(|e| Error::io(dir.display().to_string(), e))?;
48    if !md.is_dir() {
49        return Err(Error::other(format!("{}: not a directory", dir.display())));
50    }
51    let mut tw = tar::Builder::new(w);
52    tw.follow_symlinks(false);
53    walk(&mut tw, &root, "", skip)?;
54    tw.into_inner()
55        .map_err(|e| Error::io("writing the tar archive", e))
56}
57
58/// [`tar_dir`], gzip'd, in memory (the sandbox API's `upload_dir` sends it).
59pub fn tar_gz_dir(dir: &Path, skip: Option<SkipFn<'_>>) -> Result<Vec<u8>> {
60    let zw = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
61    let zw = tar_dir(zw, dir, skip)?;
62    zw.finish().map_err(|e| Error::io("gzip", e))
63}
64
65fn walk<W: Write>(
66    tw: &mut tar::Builder<W>,
67    root: &Path,
68    rel: &str,
69    skip: Option<SkipFn<'_>>,
70) -> Result<()> {
71    let dir = if rel.is_empty() {
72        root.to_path_buf()
73    } else {
74        root.join(rel)
75    };
76    let mut names: Vec<std::ffi::OsString> = std::fs::read_dir(&dir)
77        .map_err(|e| Error::io(dir.display().to_string(), e))?
78        .map(|e| e.map(|e| e.file_name()))
79        .collect::<std::io::Result<_>>()
80        .map_err(|e| Error::io(dir.display().to_string(), e))?;
81    names.sort(); // lexical order, like Go's filepath.WalkDir
82    for name in names {
83        let name = name.to_string_lossy().into_owned();
84        let r = if rel.is_empty() {
85            name.clone()
86        } else {
87            format!("{rel}/{name}")
88        };
89        let p = root.join(&r);
90        let md =
91            std::fs::symlink_metadata(&p).map_err(|e| Error::io(p.display().to_string(), e))?;
92        let ft = md.file_type();
93        if skip.is_some_and(|s| s(&r, ft.is_dir())) {
94            continue;
95        }
96        if !(ft.is_dir() || ft.is_file() || ft.is_symlink()) {
97            continue; // sockets, devices, FIFOs
98        }
99        let mut h = tar::Header::new_gnu();
100        h.set_metadata_in_mode(&md, tar::HeaderMode::Complete);
101        // Root-owned, like chainctl's upload: entries carrying the laptop's uid make git in the
102        // guest refuse /work ("dubious ownership").
103        h.set_uid(0);
104        h.set_gid(0);
105        let _ = h.set_username("");
106        let _ = h.set_groupname("");
107        let io = |e| Error::io(format!("adding {} to the tar archive", p.display()), e);
108        if ft.is_symlink() {
109            let target =
110                std::fs::read_link(&p).map_err(|e| Error::io(p.display().to_string(), e))?;
111            h.set_size(0);
112            tw.append_link(&mut h, &r, &target).map_err(io)?;
113        } else if ft.is_dir() {
114            h.set_size(0);
115            tw.append_data(&mut h, format!("{r}/"), std::io::empty())
116                .map_err(io)?;
117            walk(tw, root, &r, skip)?;
118        } else {
119            let size = md.len();
120            let f = std::fs::File::open(&p).map_err(|e| Error::io(p.display().to_string(), e))?;
121            h.set_size(size);
122            // Exactly size bytes: a file that grew is truncated, one that shrank is zero-padded.
123            let data = f.take(size).chain(std::io::repeat(0)).take(size);
124            tw.append_data(&mut h, &r, data).map_err(io)?;
125        }
126    }
127    Ok(())
128}