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