mirror of
https://github.com/rust-lang/rust.git
synced 2025-02-06 20:13:42 +00:00
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.
This commit is contained in:
commit
7506228e2e
@ -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())
|
||||
}
|
||||
|
@ -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(())
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user