Fix copyfile() not preserving source mode with restrictive umask

copyfile() passes the source mode to open(2), which applies the umask,
so a 0644 file copied with umask 0027 ends up 0640.

Apply the source mode with fchmod() after creating the destination.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
This commit is contained in:
Joachim Wiberg
2026-09-13 18:53:40 +02:00
parent e874608b76
commit b69d8a6013
3 changed files with 34 additions and 1 deletions
+2
View File
@@ -8,6 +8,8 @@ All notable changes to the project are documented in this file.
--------------
### Fixes
- Fix `copyfile()` not preserving the source file mode when the process
umask is more restrictive
- Fix `mkpath()`, and `fmkpath()`, not applying the given mode when the
process umask is more restrictive, e.g., requesting 0755 with umask
0027 silently created a 0750 directory
+8
View File
@@ -208,12 +208,20 @@ ssize_t copyfile(const char *src, const char *dst, int len, int opt)
goto exit;
}
/* open(2) applies umask, we want the source file mode */
if (fchmod(out, st.st_mode & 07777)) {
saved_errno = errno;
size = -1;
goto close_exit;
}
size = do_copy(in, out, num, buffer, BUFSIZ);
if (size < 0)
saved_errno = errno;
else if (keep_mtim)
set_mtime(in, out);
close_exit:
close(out);
close(in);
+24 -1
View File
@@ -123,9 +123,32 @@ static int _copyfile()
return rc;
}
/* copyfile() must preserve source mode, even with a restrictive umask */
static int _mode(void)
{
const char *src = "/tmp/libite-mode-src", *dst = "/tmp/libite-mode-dst";
struct stat st;
mode_t old;
int rc = 1;
if (touch(src) || chmod(src, 0644))
return test(1, "copyfile() mode, prepare %s", src);
old = umask(0077);
if (copyfile(src, dst, 0, 0) >= 0 && !stat(dst, &st))
rc = (st.st_mode & 07777) != 0644;
umask(old);
erase(src);
erase(dst);
return test(rc, "copyfile() preserves mode 0644 with umask 0077");
}
int main(void)
{
return _fcopyfile() ||
_copyfile() ||
_sz();
_sz() ||
_mode();
}