chainguard_sandbox/workspaces/
files.rs1use std::io::{Read, Write};
4use std::path::Path;
5
6use super::Client;
7use super::exec::{ExecOptions, guest_path};
8use crate::{Error, Result};
9
10pub type SkipFn<'a> = &'a dyn Fn(&str, bool) -> bool;
13
14impl Client {
15 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
41pub 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
58pub 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(); 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; }
99 let mut h = tar::Header::new_gnu();
100 h.set_metadata_in_mode(&md, tar::HeaderMode::Complete);
101 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 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}