Skip to main content

airlock/
files.rs

1//! Files placed into a container as one archive, and files read back out of it.
2
3use std::io::Read as _;
4
5use bollard::{
6    body_full,
7    query_parameters::{DownloadFromContainerOptionsBuilder, UploadToContainerOptionsBuilder},
8};
9use bytes::Bytes;
10use futures::TryStreamExt as _;
11use saluki_error::{generic_error, ErrorContext as _, GenericError};
12use tokio::time::Instant;
13
14use crate::{container::Container, removal::bounded};
15
16/// A set of files to place into a container in one request.
17pub struct Archive {
18    builder: tar::Builder<Vec<u8>>,
19}
20
21impl Archive {
22    /// Creates an empty archive.
23    pub fn new() -> Self {
24        Self {
25            builder: tar::Builder::new(Vec::new()),
26        }
27    }
28
29    /// Adds a file with the given permission bits.
30    ///
31    /// `path` is relative to the root the archive is placed at, uses `/` as its separator, and may name directories
32    /// that do not exist yet.
33    ///
34    /// # Errors
35    ///
36    /// Returns an error if `path` is absolute or contains `..`.
37    pub fn add_file(&mut self, path: &str, contents: &[u8], mode: u32) -> Result<(), GenericError> {
38        let mut header = tar::Header::new_gnu();
39        header.set_size(contents.len() as u64);
40        header.set_mode(mode);
41        header.set_entry_type(tar::EntryType::Regular);
42        self.builder
43            .append_data(&mut header, path, contents)
44            .with_error_context(|| format!("Failed to add '{}' to an archive.", path))
45    }
46
47    /// Adds a directory with the given permission bits, so the directory has them even if no file of the archive lies
48    /// in it.
49    ///
50    /// `path` is relative to the root the archive is placed at, as in [`Self::add_file`].
51    ///
52    /// # Errors
53    ///
54    /// Returns an error if `path` is absolute or contains `..`.
55    pub fn add_dir(&mut self, path: &str, mode: u32) -> Result<(), GenericError> {
56        let mut header = tar::Header::new_gnu();
57        header.set_size(0);
58        header.set_mode(mode);
59        header.set_entry_type(tar::EntryType::Directory);
60        self.builder
61            .append_data(&mut header, path, std::io::empty())
62            .with_error_context(|| format!("Failed to add '{}' to an archive.", path))
63    }
64}
65
66impl Default for Archive {
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72impl Container {
73    /// Places every file of `archive` under `root`, such as `/`, in the container's filesystem.
74    ///
75    /// This works whether or not the container is running, so files can be placed between create and start. A file
76    /// whose path lies on a volume the container mounts is written to that volume.
77    ///
78    /// # Errors
79    ///
80    /// Returns an error if the archive cannot be finished, if Docker refuses to extract it, or if `deadline` passes
81    /// first.
82    pub async fn place(&self, root: &str, archive: Archive, deadline: Instant) -> Result<(), GenericError> {
83        let tar = archive
84            .builder
85            .into_inner()
86            .error_context("Failed to finish an archive.")?;
87        let options = UploadToContainerOptionsBuilder::default().path(root).build();
88        let upload = self
89            .docker
90            .upload_to_container(&self.name, Some(options), body_full(Bytes::from(tar)));
91        bounded(Some(deadline), upload).await.map_err(|e| {
92            generic_error!(
93                "Failed to place files under '{}' in container '{}': {}",
94                root,
95                &self.name,
96                e
97            )
98        })
99    }
100
101    /// Reads the file at `path` in the container's filesystem, or returns `None` if nothing is there.
102    ///
103    /// # Errors
104    ///
105    /// Returns an error if the container does not exist, if Docker cannot copy the path out, if the path is not a
106    /// regular file, or if `deadline` passes first.
107    pub async fn read_file(&self, path: &str, deadline: Instant) -> Result<Option<Vec<u8>>, GenericError> {
108        let options = DownloadFromContainerOptionsBuilder::default().path(path).build();
109        let download = self
110            .docker
111            .download_from_container(&self.name, Some(options))
112            .map_ok(|chunk| chunk.to_vec())
113            .try_concat();
114        let tar = match bounded(Some(deadline), download).await {
115            Ok(tar) => tar,
116            // Docker answers 404 both for a missing path and for a missing container.
117            Err(e) if e.is_not_found() => {
118                return match bounded(Some(deadline), self.docker.inspect_container(&self.name, None)).await {
119                    Ok(_) => Ok(None),
120                    Err(e) => Err(generic_error!(
121                        "Failed to read '{}': container '{}' cannot be inspected: {}",
122                        path,
123                        &self.name,
124                        e
125                    )),
126                }
127            }
128            Err(e) => {
129                return Err(generic_error!(
130                    "Failed to copy '{}' out of container '{}': {}",
131                    path,
132                    &self.name,
133                    e
134                ))
135            }
136        };
137
138        let mut archive = tar::Archive::new(tar.as_slice());
139        let mut entries = archive
140            .entries()
141            .with_error_context(|| format!("Failed to read the archive of '{}'.", path))?;
142        let mut entry = entries
143            .next()
144            .ok_or_else(|| generic_error!("Docker returned an empty archive for '{}'.", path))?
145            .with_error_context(|| format!("Failed to read the archive of '{}'.", path))?;
146        if entry.header().entry_type() != tar::EntryType::Regular {
147            return Err(generic_error!(
148                "'{}' in container '{}' is not a regular file.",
149                path,
150                &self.name
151            ));
152        }
153        let mut contents = Vec::new();
154        entry
155            .read_to_end(&mut contents)
156            .with_error_context(|| format!("Failed to read '{}' from its archive.", path))?;
157        Ok(Some(contents))
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164
165    #[test]
166    fn archive_refuses_paths_outside_its_root() {
167        let mut archive = Archive::new();
168
169        assert!(archive.add_file("/etc/passwd", b"", 0o644).is_err());
170        assert!(archive.add_file("data/../../etc/passwd", b"", 0o644).is_err());
171        assert!(archive.add_dir("/tmp", 0o777).is_err());
172        archive.add_file("data/greeting", b"hello", 0o644).unwrap();
173    }
174}