1use 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
16pub struct Archive {
18 builder: tar::Builder<Vec<u8>>,
19}
20
21impl Archive {
22 pub fn new() -> Self {
24 Self {
25 builder: tar::Builder::new(Vec::new()),
26 }
27 }
28
29 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 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 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 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 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}