fs-util: Add chown_and_chmod_at()
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Mon, 26 Sep 2022 08:15:03 +0000 (10:15 +0200)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Wed, 9 Nov 2022 10:14:10 +0000 (11:14 +0100)
src/basic/fs-util.c
src/basic/fs-util.h

index 6b757bd5705b182343ec357e18a4ed42feb090fe..3238ff02f779367108798dda462d2ed1f614edda 100644 (file)
@@ -195,17 +195,17 @@ int readlink_and_make_absolute(const char *p, char **r) {
         return 0;
 }
 
-int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
+int chmod_and_chown_at(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
         _cleanup_close_ int fd = -1;
 
-        assert(path);
-
-        fd = open(path, O_PATH|O_CLOEXEC|O_NOFOLLOW); /* Let's acquire an O_PATH fd, as precaution to change
-                                                       * mode/owner on the same file */
-        if (fd < 0)
-                return -errno;
+        if (path) {
+                /* Let's acquire an O_PATH fd, as precaution to change mode/owner on the same file */
+                fd = openat(dir_fd, path, O_PATH|O_CLOEXEC|O_NOFOLLOW);
+                if (fd < 0)
+                        return -errno;
+        }
 
-        return fchmod_and_chown(fd, mode, uid, gid);
+        return fchmod_and_chown(path ? fd : dir_fd, mode, uid, gid);
 }
 
 int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid) {
index c4dffc48f3bcc0b41b7f99ecc771307fad2e45e6..932d003f199356a7038d7087feac8d8031ae3d3b 100644 (file)
@@ -33,7 +33,10 @@ int readlink_malloc(const char *p, char **r);
 int readlink_value(const char *p, char **ret);
 int readlink_and_make_absolute(const char *p, char **r);
 
-int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid);
+int chmod_and_chown_at(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid);
+static inline int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
+        return chmod_and_chown_at(AT_FDCWD, path, mode, uid, gid);
+}
 int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid);
 static inline int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
         return fchmod_and_chown_with_fallback(fd, NULL, mode, uid, gid); /* no fallback */