fs-util: introduce fchmod_and_chown()
authorYu Watanabe <watanabe.yu+github@gmail.com>
Thu, 14 Jun 2018 02:26:29 +0000 (11:26 +0900)
committerYu Watanabe <watanabe.yu+github@gmail.com>
Thu, 14 Jun 2018 02:47:57 +0000 (11:47 +0900)
The new function fchmod_and_chown() is almost same as chmod_and_chown()
except it takes file descriptor instead of file path.

src/basic/fs-util.c
src/basic/fs-util.h

index ab6ccf7..c4e2ebf 100644 (file)
@@ -230,6 +230,22 @@ int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
         return 0;
 }
 
+int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
+        /* Under the assumption that we are running privileged we
+         * first change the access mode and only then hand out
+         * ownership to avoid a window where access is too open. */
+
+        if (mode != MODE_INVALID)
+                if (fchmod(fd, mode) < 0)
+                        return -errno;
+
+        if (uid != UID_INVALID || gid != GID_INVALID)
+                if (fchown(fd, uid, gid) < 0)
+                        return -errno;
+
+        return 0;
+}
+
 int fchmod_umask(int fd, mode_t m) {
         mode_t u;
         int r;
index 4d0ed64..9129d1c 100644 (file)
@@ -31,6 +31,7 @@ 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 fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid);
 
 int fchmod_umask(int fd, mode_t mode);
 int fchmod_opath(int fd, mode_t m);