Skip to content

Commit 7506228

Browse files
committed
Auto merge of #84716 - joshtriplett:chroot, r=dtolnay
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.
2 parents 49920bc + ffb874a commit 7506228

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

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

+26
Original file line numberDiff line numberDiff line change
@@ -884,3 +884,29 @@ 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+
/// #![feature(unix_chroot)]
899+
/// use std::os::unix::fs;
900+
///
901+
/// fn main() -> std::io::Result<()> {
902+
/// fs::chroot("/sandbox")?;
903+
/// std::env::set_current_dir("/")?;
904+
/// // continue working in sandbox
905+
/// Ok(())
906+
/// }
907+
/// ```
908+
#[unstable(feature = "unix_chroot", issue = "84715")]
909+
#[cfg(not(target_os = "fuchsia"))]
910+
pub fn chroot<P: AsRef<Path>>(dir: P) -> io::Result<()> {
911+
sys::fs::chroot(dir.as_ref())
912+
}

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

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

0 commit comments

Comments
 (0)