From b8da477eaf6c775e8c82aad43a4511f7609b0b69 Mon Sep 17 00:00:00 2001 From: Yu Watanabe Date: Thu, 14 Jun 2018 11:26:29 +0900 Subject: [PATCH] fs-util: introduce fchmod_and_chown() 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 | 16 ++++++++++++++++ src/basic/fs-util.h | 1 + 2 files changed, 17 insertions(+) diff --git a/src/basic/fs-util.c b/src/basic/fs-util.c index ab6ccf7c86d..c4e2ebf9b83 100644 --- a/src/basic/fs-util.c +++ b/src/basic/fs-util.c @@ -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; diff --git a/src/basic/fs-util.h b/src/basic/fs-util.h index 4d0ed641b4f..9129d1c88ba 100644 --- a/src/basic/fs-util.h +++ b/src/basic/fs-util.h @@ -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);