Skip to content

Commit

Permalink
Add std::os::unix::fs::chroot to change the root directory of the cur…
Browse files Browse the repository at this point in the history
…rent 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
joshtriplett committed Apr 30, 2021
1 parent 814a560 commit ffb874a
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
26 changes: 26 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,29 @@ 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`][`crate::env::set_current_dir`] afterwards.
///
/// # Examples
///
/// ```no_run
/// #![feature(unix_chroot)]
/// 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")]
#[cfg(not(target_os = "fuchsia"))]
pub fn chroot<P: AsRef<Path>>(dir: P) -> io::Result<()> {
sys::fs::chroot(dir.as_ref())
}
7 changes: 7 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,10 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
})?;
Ok(bytes_copied as u64)
}

#[cfg(not(target_os = "fuchsia"))]
pub fn chroot(dir: &Path) -> io::Result<()> {
let dir = cstr(dir)?;
cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
Ok(())
}

0 comments on commit ffb874a

Please sign in to comment.