Do not let mkpath() accept an existing non-directory

mkpath(), fmkpath(), and makepath() return success when the path exists
as a regular file, or anything else that is not a directory:

    touch /tmp/foo; mkpath("/tmp/foo", 0755);

Any path that stat() can find is taken to be done.

Check that it is a directory, otherwise fail with ENOTDIR.

Closes #26
This commit is contained in:
omrzk authored and Joachim Wiberg committed 2026-11-16 14:13:07 +01:00
1 parent 0013f4fcf4
commit eb883301b3
2 files changed
+52 -6

No files matched your search

+9 -3
View File
@@ -36,7 +36,8 @@
* @param mode A &mode_t mode to create @a dir with
*
* Directories are created with exactly @a mode, the process umask is
* not applied like it is for mkdir(2).
* not applied like it is for mkdir(2). If @a dir exists but is not a
* directory, the call fails with @c ENOTDIR.
*
* @returns POSIX OK(0) on success, otherwise -1 with @a errno set.
*/
@@ -49,8 +50,13 @@ int mkpath(const char *dir, mode_t mode)
return -1;
}
if (!stat(dir, &sb))
return 0;
if (!stat(dir, &sb)) {
if (S_ISDIR(sb.st_mode))
return 0;
errno = ENOTDIR;
return -1;
}
mkpath(dirname(strdupa(dir)), mode);
+43 -3
View File
@@ -78,6 +78,42 @@ int test_umask(void)
return 0;
}
static int notdir(int rc)
{
return rc == -1 && errno == ENOTDIR;
}
/* An existing non-directory is not a created directory */
int test_nondir(void)
{
const char *bad[] = { BASEDIR "/file", BASEDIR "/file-link", NULL };
const char *dirlink = BASEDIR "/dir-link";
int i;
if (touch(bad[0]) ||
symlink("file", bad[1]) ||
symlink("um", dirlink)) {
perror("Failed setup");
return 1;
}
for (i = 0; bad[i]; i++) {
if (!notdir(mkpath(bad[i], 0755)) ||
!notdir(fmkpath(0755, "%s", bad[i])) ||
!notdir(makepath(bad[i]))) {
fprintf(stderr, "Failed: %s accepted as a directory\n", bad[i]);
return 1;
}
}
if (mkpath(dirlink, 0755)) {
perror("Failed symlink to directory");
return 1;
}
return 0;
}
int main(void)
{
int i, ret = 0;
@@ -94,18 +130,22 @@ int main(void)
mkdir(BASEDIR, 0755);
printf("Pass 1/3: makepath() =========================\n");
printf("Pass 1/4: makepath() =========================\n");
for (i = 0; list[i] && !ret; i++)
ret |= test_makepath(list[i]);
printf("Pass 2/3: fmkpath() ==========================\n");
printf("Pass 2/4: fmkpath() ==========================\n");
for (i = 0; list[i] && !ret; i++)
ret |= test_fmkpath(list[i] + strlen(BASEDIR) + 1);
printf("Pass 3/3: mkpath() with umask ================\n");
printf("Pass 3/4: mkpath() with umask ================\n");
if (!ret)
ret |= test_umask();
printf("Pass 4/4: mkpath() on non-directories ========\n");
if (!ret)
ret |= test_nondir();
printf("Done: Cleaning up ============================\n");
system("rm -rf " BASEDIR);