ac3a84
From 4fb6e9eddc7487a965b3e051115f9bb1d0413342 Mon Sep 17 00:00:00 2001
ac3a84
From: Lennart Poettering <lennart@poettering.net>
ac3a84
Date: Fri, 4 Nov 2022 18:20:47 +0100
ac3a84
Subject: [PATCH] process-util: add new FORK_CLOEXEC_OFF flag for disabling
ac3a84
 O_CLOEXEC on remaining fds
ac3a84
ac3a84
Often the fds that shall stay around in the child shall be passed
ac3a84
to a process over execve(), hence add an option to explicitly disable
ac3a84
O_CLOEXEC on them in the child.
ac3a84
ac3a84
(cherry picked from commit 981cfbe046297a18f2cb115ef81202f3bd68d2a3)
ac3a84
ac3a84
Related: #2138081
ac3a84
---
ac3a84
 src/basic/process-util.c | 8 ++++++++
ac3a84
 src/basic/process-util.h | 1 +
ac3a84
 2 files changed, 9 insertions(+)
ac3a84
ac3a84
diff --git a/src/basic/process-util.c b/src/basic/process-util.c
ac3a84
index fb0b38fa49..0213f5913f 100644
ac3a84
--- a/src/basic/process-util.c
ac3a84
+++ b/src/basic/process-util.c
ac3a84
@@ -1372,6 +1372,14 @@ int safe_fork_full(
ac3a84
                 }
ac3a84
         }
ac3a84
 
ac3a84
+        if (flags & FORK_CLOEXEC_OFF) {
ac3a84
+                r = fd_cloexec_many(except_fds, n_except_fds, false);
ac3a84
+                if (r < 0) {
ac3a84
+                        log_full_errno(prio, r, "Failed to turn off O_CLOEXEC on file descriptors: %m");
ac3a84
+                        _exit(EXIT_FAILURE);
ac3a84
+                }
ac3a84
+        }
ac3a84
+
ac3a84
         /* When we were asked to reopen the logs, do so again now */
ac3a84
         if (flags & FORK_REOPEN_LOG) {
ac3a84
                 log_open();
ac3a84
diff --git a/src/basic/process-util.h b/src/basic/process-util.h
ac3a84
index f8c374a310..ed2f73673e 100644
ac3a84
--- a/src/basic/process-util.h
ac3a84
+++ b/src/basic/process-util.h
ac3a84
@@ -150,6 +150,7 @@ typedef enum ForkFlags {
ac3a84
         FORK_STDOUT_TO_STDERR   = 1 << 11, /* Make stdout a copy of stderr */
ac3a84
         FORK_FLUSH_STDIO        = 1 << 12, /* fflush() stdout (and stderr) before forking */
ac3a84
         FORK_NEW_USERNS         = 1 << 13, /* Run child in its own user namespace */
ac3a84
+        FORK_CLOEXEC_OFF        = 1 << 14, /* In the child: turn off O_CLOEXEC on all fds in except_fds[] */
ac3a84
 } ForkFlags;
ac3a84
 
ac3a84
 int safe_fork_full(const char *name, const int except_fds[], size_t n_except_fds, ForkFlags flags, pid_t *ret_pid);