Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 3b414c3

Browse files
committedApr 29, 2021
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.
1 parent 814a560 commit 3b414c3

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed
 

‎library/std/src/sys/unix/ext/fs.rs

+24
Original file line numberDiff line numberDiff line change
@@ -884,3 +884,27 @@ impl DirBuilderExt for fs::DirBuilder {
884884
self
885885
}
886886
}
887+
888+
/// Change the root directory of the current process to the specified path.
889+
///
890+
/// This typically requires privileges, such as root or a specific capability.
891+
///
892+
/// This does not change the current working directory; you should call
893+
/// [`std::env::set_current_dir`][`crate::env::set_current_dir`] afterwards.
894+
///
895+
/// # Examples
896+
///
897+
/// ```no_run
898+
/// use std::os::unix::fs;
899+
///
900+
/// fn main() -> std::io::Result<()> {
901+
/// fs::chroot("/sandbox")?;
902+
/// std::env::set_current_dir("/")?;
903+
/// // continue working in sandbox
904+
/// Ok(())
905+
/// }
906+
/// ```
907+
#[unstable(feature = "unix_chroot", issue = "84715")]
908+
pub fn chroot<P: AsRef<Path>>(dir: P) -> io::Result<()> {
909+
sys::fs::chroot(dir.as_ref())
910+
}

‎library/std/src/sys/unix/fs.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1328,3 +1328,9 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
13281328
})?;
13291329
Ok(bytes_copied as u64)
13301330
}
1331+
1332+
pub fn chroot(dir: &Path) -> io::Result<()> {
1333+
let dir = cstr(dir)?;
1334+
cvt(unsafe { libc::chroot(dir.as_ptr()) })?;
1335+
Ok(())
1336+
}

0 commit comments

Comments
 (0)
Please sign in to comment.