From e3d5d04774d4295d99d323cc6fb0c1462548de19 Mon Sep 17 00:00:00 2001 From: John Zaitseff Date: Mon, 1 Aug 2022 22:26:12 +1000 Subject: [PATCH] Eliminate a second TOCTOU bug in xmkdir() itself The theoretical odds of hitting this time-of-check / time-of-use bug are extremely remote. But we do want to keep Coverity Scan happy, don't we? --- src/utils.c | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/utils.c b/src/utils.c index ab51b55..cb5b72c 100644 --- a/src/utils.c +++ b/src/utils.c @@ -1223,19 +1223,21 @@ int xmkdir (const char *pathname, mode_t mode) return -1; } - // Check that pathname already exists and is a directory - if (stat(pathname, &statbuf) == 0) { - if (S_ISDIR(statbuf.st_mode)) { - return 0; - } else { - errno = ENOTDIR; - return -1; - } - } - // Try creating the directory ret = mkdir(pathname, mode); - if (ret == 0 || (errno != ENOENT && errno != ENOTDIR)) { + if (ret != 0 && errno == EEXIST) { + // Pathname exists: is it a directory? + if (stat(pathname, &statbuf) == 0) { + if (S_ISDIR(statbuf.st_mode)) { + return 0; + } else { + errno = ENOTDIR; + return -1; + } + } else { + return -1; + } + } else if (ret == 0 || (errno != ENOENT && errno != ENOTDIR)) { return ret; }