Skip to content

Commit

Permalink
Rollup merge of #84716 - joshtriplett:chroot, r=dtolnay
Browse files Browse the repository at this point in the history
Add std::os::unix::fs::chroot to change the root directory of the current process

This is a straightforward wrapper that uses the existing helpers for C
string handling and errno handling.

Having this available is convenient for UNIX utility programs written in
Rust, and avoids having to call the unsafe `libc::chroot` directly and
handle errors manually, in a program that may otherwise be entirely safe
code.
  • Loading branch information
jackh726 committed Apr 29, 2021
2 parents 7702e48 + 2fb2f0b commit ac134c3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
24 changes: 24 additions & 0 deletions library/std/src/sys/unix/ext/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -884,3 +884,27 @@ impl DirBuilderExt for fs::DirBuilder {
self
}
}

/// Change the root directory of the current process to the specified path.
///
/// This typically requires privileges, such as root or a specific capability.
///
/// This does not change the current working directory; you should call
/// [`std::env::set_current_dir`] afterwards.
///
/// # Examples
///
/// ```no_run
/// use std::os::unix::fs;
///
/// fn main() -> std::io::Result<()> {
/// fs::chroot("/sandbox")?;
/// std::env::set_current_dir("/")?;
/// // continue working in sandbox
/// Ok(())
/// }
/// ```
#[unstable(feature = "unix_chroot", issue = "84715")]
pub fn chroot<P: AsRef<Path>>(dir: P) -> io::Result<()> {
sys::fs::chroot(dir.as_ref())
}
6 changes: 6 additions & 0 deletions library/std/src/sys/unix/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1328,3 +1328,9 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
})?;
Ok(bytes_copied as u64)
}

pub fn chroot(dir: &Path) -> io::Result<()> {
let dir = cstr(dir)?;
cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
Ok(())
}

0 comments on commit ac134c3

Please sign in to comment.