diff options
| author | bors <bors@rust-lang.org> | 2021-04-30 12:19:37 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2021-04-30 12:19:37 +0000 |
| commit | 7506228e2e688517ae142fc385f13b30c4ce07f1 (patch) | |
| tree | 879f2baa5c33cfdf975885b1949df21db5e1b444 /library/std/src/sys | |
| parent | 49920bc581743d6edb9f82fbff4cbafebc212619 (diff) | |
| parent | ffb874ac90947c6ffa87af0e80b362bf84442d76 (diff) | |
| download | rust-7506228e2e688517ae142fc385f13b30c4ce07f1.tar.gz rust-7506228e2e688517ae142fc385f13b30c4ce07f1.zip | |
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.
Diffstat (limited to 'library/std/src/sys')
| -rw-r--r-- | library/std/src/sys/unix/ext/fs.rs | 26 | ||||
| -rw-r--r-- | library/std/src/sys/unix/fs.rs | 7 |
2 files changed, 33 insertions, 0 deletions
diff --git a/library/std/src/sys/unix/ext/fs.rs b/library/std/src/sys/unix/ext/fs.rs index 9a982a4acd9..9cf51be2836 100644 --- a/library/std/src/sys/unix/ext/fs.rs +++ b/library/std/src/sys/unix/ext/fs.rs @@ -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()) +} diff --git a/library/std/src/sys/unix/fs.rs b/library/std/src/sys/unix/fs.rs index 16a7f727696..45bae25a0c3 100644 --- a/library/std/src/sys/unix/fs.rs +++ b/library/std/src/sys/unix/fs.rs @@ -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(()) +} |
