From a98e236e95719aa9c777a8cb1569a66daf0d576f Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=A9mie=20Galarneau?= Date: Mon, 2 Nov 2015 11:39:59 -0500 Subject: [PATCH] Fix: Verify directory's existence before calling mkdir MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérémie Galarneau --- src/common/utils.c | 55 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 45 insertions(+), 10 deletions(-) diff --git a/src/common/utils.c b/src/common/utils.c index ee53477de..6e7726714 100644 --- a/src/common/utils.c +++ b/src/common/utils.c @@ -30,6 +30,7 @@ #include #include #include +#include #include #include @@ -551,6 +552,44 @@ error: return fd; } +/* + * On some filesystems (e.g. nfs), mkdir will validate access rights before + * checking for the existence of the path element. This means that on a setup + * where "/home/" is a mounted NFS share, and running as an unpriviledged user, + * recursively creating a path of the form "/home/my_user/trace/" will fail with + * EACCES on mkdir("/home", ...). + * + * Performing a stat(...) on the path to check for existence allows us to + * work around this behaviour. + */ +static +int mkdir_check_exists(const char *path, mode_t mode) +{ + int ret = 0; + struct stat st; + + ret = stat(path, &st); + if (ret == 0) { + if (S_ISDIR(st.st_mode)) { + /* Directory exists, skip. */ + goto end; + } else { + /* Exists, but is not a directory. */ + errno = ENOTDIR; + ret = -1; + goto end; + } + } + + /* + * Let mkdir handle other errors as the caller expects mkdir + * semantics. + */ + ret = mkdir(path, mode); +end: + return ret; +} + /* * Create directory using the given path and mode. * @@ -562,7 +601,7 @@ int utils_mkdir(const char *path, mode_t mode, int uid, int gid) int ret; if (uid < 0 || gid < 0) { - ret = mkdir(path, mode); + ret = mkdir_check_exists(path, mode); } else { ret = run_as_mkdir(path, mode, uid, gid); } @@ -617,9 +656,9 @@ int _utils_mkdir_recursive_unsafe(const char *path, mode_t mode) ret = -1; goto error; } - ret = mkdir(tmp, mode); + ret = mkdir_check_exists(tmp, mode); if (ret < 0) { - if (errno != EEXIST) { + if (errno != EACCES) { PERROR("mkdir recursive"); ret = -errno; goto error; @@ -629,14 +668,10 @@ int _utils_mkdir_recursive_unsafe(const char *path, mode_t mode) } } - ret = mkdir(tmp, mode); + ret = mkdir_check_exists(tmp, mode); if (ret < 0) { - if (errno != EEXIST) { - PERROR("mkdir recursive last element"); - ret = -errno; - } else { - ret = 0; - } + PERROR("mkdir recursive last element"); + ret = -errno; } error: -- 2.34.1