From 0de094fd6c9e69dcd9eb4552628577e14892049d Mon Sep 17 00:00:00 2001 From: Giuseppe Scrivano Date: Thu, 2 Sep 2021 15:15:41 +0200 Subject: [PATCH] catatoinit: rewrite LISTEN_PID to the child process In order to get systemd fd passing let's rewrite the LISTEN_PID environment variable if it is pointing to catatonit init process. Closes: https://github.com/openSUSE/catatonit/issues/13 Signed-off-by: Giuseppe Scrivano --- catatonit.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/catatonit.c b/catatonit.c index fd746bb..6204a22 100644 --- a/catatonit.c +++ b/catatonit.c @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -193,6 +194,37 @@ static int make_foreground(sigset_t *sigmask) return 0; } +/* + * If the LISTEN_PID environment variable is set to the parent pid, rewrite it to + * point to the current pid. + */ +static void rewrite_listen_pid_env() +{ + char *listen_pid = getenv("LISTEN_PID"); + long long val; + + if (listen_pid == NULL) + return; + + errno = 0; + val = strtoll(listen_pid, NULL, 10); + if (errno == ERANGE) { + warn("LISTEN_PID has an invalid value"); + return; + } + + if (val == getppid()) { + char pid_str[32]; + int r; + + snprintf(pid_str, sizeof(pid_str), "%d", getpid()); + + r = setenv("LISTEN_PID", pid_str, 1); + if (r < 0) + warn("could not overwrite env variable LISTEN_PID: %m"); + } +} + /* * Spawn a child process with the given arguments and signal map and make it a * faux-pid1 by placing it in the foreground. This is the main process which @@ -207,6 +239,8 @@ static int spawn_pid1(char *file, char **argv, sigset_t *sigmask) return child; } + rewrite_listen_pid_env(); + /* * We are now in the child. Set up our sigmask, put ourselves in the * foreground, and then finally exec (with the environment inherited).