1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::fs;
use std::io;
use std::os::unix;
use std::path::Path;
use std::path::PathBuf;
use tempfile::TempDir;
/// Represents a temporary chroot environment. This shall only contain the files
/// necessary to reproduce an execution.
pub struct TempChroot {
dir: TempDir,
}
impl TempChroot {
/// Creates a temporary directory that the tracee will chroot to. It is here
/// where we can copy files needed by the tracee.
pub fn new_in(data_dir: &Path) -> io::Result<Self> {
let dir = TempDir::new_in(data_dir)?;
Ok(Self { dir })
}
/// Returns the path to the chroot directory.
pub fn path(&self) -> &Path {
self.dir.path()
}
/// Returns a path relative to the chroot directory.
pub fn relpath(&self, path: &Path) -> PathBuf {
self.path().join(path.strip_prefix("/").unwrap_or(path))
}
/// Create symlink a file path into the chroot directory. Any intermediate
/// directory that the path has will also be created. `link` must be an
/// absolute path.
///
/// NOTE: original path must exist in chroot directory, otherwise this
/// could create a dead sym link.
pub fn symlink(&self, original: &Path, link: &Path) -> io::Result<()> {
let link = self.relpath(link);
if let Some(dir) = link.parent() {
fs::create_dir_all(dir)?;
}
unix::fs::symlink(original, link)
}
/// Creates a directory in the chroot.
pub fn create_dir_all(&self, path: &Path) -> io::Result<()> {
fs::create_dir_all(self.relpath(path))
}
/// Deletes the chroot. The `Drop` impl will also take care of this, but
/// calling this explicitly gives a chance to catch any errors.
pub fn remove(self) -> io::Result<()> {
self.dir.close()
}
}