From fc9deee642e554e6bdd39617375df76546c26891 Mon Sep 17 00:00:00 2001
From: Lennart Poettering <lennart@poettering.net>
Date: Tue, 30 May 2023 15:35:24 +0200
Subject: [PATCH] test: test O_CLOEXEC filtering of fdset fill logic

(cherry picked from commit d7aee3f41f69f46d8328f658cab84f8a4b05bb86)
Backport of the cloexec filter for v253, and for v252 (actually tested
with v252). Note that I've left the name _s of the function parameter as
it was before.
(cherry picked from commit 4c3b06f255642c39b6dccb8b063efaf66bce88c9)
(cherry picked from commit 1e932bf95e5536fea97bc48f1a409e4f1d0f7f30)

Conflict:code context adaptation
Reference:https://github.com/systemd/systemd-stable/commit/fc9deee642e554e6bdd39617375df76546c26891
---
 src/test/test-fdset.c | 42 ++++++++++++++++++++++++++++++++++++++----
 1 file changed, 38 insertions(+), 4 deletions(-)

diff --git a/src/test/test-fdset.c b/src/test/test-fdset.c
index 5d63eeee37..e2ef86343a 100644
--- a/src/test/test-fdset.c
+++ b/src/test/test-fdset.c
@@ -13,14 +13,48 @@
 static void test_fdset_new_fill(void) {
         int fd = -1;
         _cleanup_fdset_free_ FDSet *fdset = NULL;
-        char name[] = "/tmp/test-fdset_new_fill.XXXXXX";
 
-        fd = mkostemp_safe(name);
+        log_close();
+        log_set_open_when_needed(true);
+
+        fd = open("/dev/null", O_CLOEXEC|O_RDONLY);
         assert_se(fd >= 0);
-        assert_se(fdset_new_fill(&fdset) >= 0);
+
+        assert_se(fdset_new_fill(/* filter_cloexec= */ -1, &fdset) >= 0);
         assert_se(fdset_contains(fdset, fd));
+        fdset = fdset_free(fdset);
+        assert_se(fcntl(fd, F_GETFD) < 0);
+        assert_se(errno == EBADF);
 
-        unlink(name);
+        fd = open("/dev/null", O_CLOEXEC|O_RDONLY);
+        assert_se(fd >= 0);
+
+        assert_se(fdset_new_fill(/* filter_cloexec= */ 0, &fdset) >= 0);
+        assert_se(!fdset_contains(fdset, fd));
+        fdset = fdset_free(fdset);
+        assert_se(fcntl(fd, F_GETFD) >= 0);
+
+        assert_se(fdset_new_fill(/* filter_cloexec= */ 1, &fdset) >= 0);
+        assert_se(fdset_contains(fdset, fd));
+        fdset = fdset_free(fdset);
+        assert_se(fcntl(fd, F_GETFD) < 0);
+        assert_se(errno == EBADF);
+
+        fd = open("/dev/null", O_RDONLY);
+        assert_se(fd >= 0);
+
+        assert_se(fdset_new_fill(/* filter_cloexec= */ 1, &fdset) >= 0);
+        assert_se(!fdset_contains(fdset, fd));
+        fdset = fdset_free(fdset);
+        assert_se(fcntl(fd, F_GETFD) >= 0);
+
+        assert_se(fdset_new_fill(/* filter_cloexec= */ 0, &fdset) >= 0);
+        assert_se(fdset_contains(fdset, fd));
+        fdset = fdset_free(fdset);
+        assert_se(fcntl(fd, F_GETFD) < 0);
+        assert_se(errno == EBADF);
+
+        log_open();
 }
 
 static void test_fdset_put_dup(void) {
-- 
2.33.0

