about summary refs log tree commit diff
path: root/library/std/src/sys/unix
diff options
context:
space:
mode:
authorJosh Triplett <josh@joshtriplett.org>2021-09-14 18:29:38 -0700
committerJosh Triplett <josh@joshtriplett.org>2021-09-14 19:10:05 -0700
commit4840f67fcbe02fe6428a0a29bcf329401242b739 (patch)
treef088da8a322d63cb07d60032f92387a122f5d6e1 /library/std/src/sys/unix
parentc3c0f80d6081092faff801542dd82f0e2420152b (diff)
downloadrust-4840f67fcbe02fe6428a0a29bcf329401242b739.tar.gz
rust-4840f67fcbe02fe6428a0a29bcf329401242b739.zip
Add chown functions to std::os::unix::fs to change the owner and group of files
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 unsafe functions like `libc::chown`
directly and handle errors manually, in a program that may otherwise be
entirely safe code.

In addition, these functions provide a more Rustic interface by
accepting appropriate traits and using `None` rather than `-1`.
Diffstat (limited to 'library/std/src/sys/unix')
-rw-r--r--library/std/src/sys/unix/fs.rs17
1 files changed, 17 insertions, 0 deletions
diff --git a/library/std/src/sys/unix/fs.rs b/library/std/src/sys/unix/fs.rs
index 6d7524a733a..a4fff9b2e64 100644
--- a/library/std/src/sys/unix/fs.rs
+++ b/library/std/src/sys/unix/fs.rs
@@ -1416,6 +1416,23 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
     Ok(bytes_copied as u64)
 }
 
+pub fn chown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
+    let path = cstr(path)?;
+    cvt(unsafe { libc::chown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
+    Ok(())
+}
+
+pub fn fchown(fd: c_int, uid: u32, gid: u32) -> io::Result<()> {
+    cvt(unsafe { libc::fchown(fd, uid as libc::uid_t, gid as libc::gid_t) })?;
+    Ok(())
+}
+
+pub fn lchown(path: &Path, uid: u32, gid: u32) -> io::Result<()> {
+    let path = cstr(path)?;
+    cvt(unsafe { libc::lchown(path.as_ptr(), uid as libc::uid_t, gid as libc::gid_t) })?;
+    Ok(())
+}
+
 #[cfg(not(any(target_os = "fuchsia", target_os = "vxworks")))]
 pub fn chroot(dir: &Path) -> io::Result<()> {
     let dir = cstr(dir)?;