]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
fs-util: Allow xopenat() to reopen existing file descriptors
authorDaan De Meyer <daan.j.demeyer@gmail.com>
Thu, 23 Mar 2023 13:30:43 +0000 (14:30 +0100)
committerDaan De Meyer <daan.j.demeyer@gmail.com>
Thu, 23 Mar 2023 16:31:55 +0000 (17:31 +0100)
src/basic/fs-util.c
src/test/test-fs-util.c

index 06bd5705f28ea0dc4b0c7e8c178f4f4a78ae366e..257c11ad715fc063926aff5a7e046ddc4fc1da9c 100644 (file)
@@ -1104,6 +1104,11 @@ int xopenat(int dir_fd, const char *path, int flags, mode_t mode) {
         assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
         assert(path);
 
+        if (isempty(path)) {
+                assert(!FLAGS_SET(flags, O_CREAT|O_EXCL));
+                return fd_reopen(dir_fd, flags);
+        }
+
         if (FLAGS_SET(flags, O_DIRECTORY|O_CREAT)) {
                 r = RET_NERRNO(mkdirat(dir_fd, path, mode));
                 if (r == -EEXIST) {
index 2ad9c5b565a38b206d7ec080bfa43fb898131f72..0f942f6dcbb4cb495b1023ace385479bbd9e0bff 100644 (file)
@@ -1223,7 +1223,7 @@ TEST(openat_report_new) {
 
 TEST(xopenat) {
         _cleanup_(rm_rf_physical_and_freep) char *t = NULL;
-        _cleanup_close_ int tfd = -EBADF, fd = -EBADF;
+        _cleanup_close_ int tfd = -EBADF, fd = -EBADF, fd2 = -EBADF;
 
         assert_se((tfd = mkdtemp_open(NULL, 0, &t)) >= 0);
 
@@ -1244,6 +1244,11 @@ TEST(xopenat) {
         assert_se((fd = xopenat(tfd, "def", O_CREAT|O_EXCL|O_CLOEXEC, 0644)) >= 0);
         assert_se(fd_verify_regular(fd) >= 0);
         fd = safe_close(fd);
+
+        /* Test that we can reopen an existing fd with xopenat() by specifying an empty path. */
+
+        assert_se((fd = xopenat(tfd, "def", O_PATH|O_CLOEXEC, 0)) >= 0);
+        assert_se((fd2 = xopenat(fd, "", O_RDWR|O_CLOEXEC, 0644)) >= 0);
 }
 
 TEST(xopenat_lock) {