1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
11 #include "conf-files.h"
14 #include "errno-util.h"
15 #include "exec-util.h"
20 #include "missing_syscall.h"
21 #include "process-util.h"
22 #include "rlimit-util.h"
23 #include "serialize.h"
25 #include "signal-util.h"
26 #include "stat-util.h"
27 #include "string-table.h"
28 #include "string-util.h"
30 #include "terminal-util.h"
31 #include "tmpfile-util.h"
34 /* Put this test here for a lack of better place */
35 assert_cc(EAGAIN
== EWOULDBLOCK
);
37 static int do_spawn(const char *path
, char *argv
[], int stdout_fd
, pid_t
*pid
, bool set_systemd_exec_pid
) {
41 if (null_or_empty_path(path
)) {
42 log_debug("%s is empty (a mask).", path
);
46 r
= safe_fork("(direxec)", FORK_DEATHSIG
|FORK_LOG
, &_pid
);
53 r
= rearrange_stdio(STDIN_FILENO
, TAKE_FD(stdout_fd
), STDERR_FILENO
);
58 (void) rlimit_nofile_safe();
60 if (set_systemd_exec_pid
) {
61 r
= setenv_systemd_exec_pid(false);
63 log_warning_errno(r
, "Failed to set $SYSTEMD_EXEC_PID, ignoring: %m");
67 _argv
[0] = (char*) path
;
71 argv
[0] = (char*) path
;
74 log_error_errno(errno
, "Failed to execute %s: %m", path
);
82 static int do_execute(
85 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
86 void* const callback_args
[_STDOUT_CONSUME_MAX
],
92 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
93 _cleanup_strv_free_
char **paths
= NULL
;
95 bool parallel_execution
;
97 /* We fork this all off from a child process so that we can somewhat cleanly make
98 * use of SIGALRM to set a time limit.
100 * We attempt to perform parallel execution if configured by the user, however
101 * if `callbacks` is nonnull, execution must be serial.
103 parallel_execution
= FLAGS_SET(flags
, EXEC_DIR_PARALLEL
) && !callbacks
;
105 r
= conf_files_list_strv(&paths
, NULL
, NULL
, CONF_FILES_EXECUTABLE
|CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char* const*) directories
);
107 return log_error_errno(r
, "Failed to enumerate executables: %m");
109 if (parallel_execution
) {
110 pids
= hashmap_new(NULL
);
115 /* Abort execution of this process after the timeout. We simply rely on SIGALRM as
116 * default action terminating the process, and turn on alarm(). */
118 if (timeout
!= USEC_INFINITY
)
119 alarm(DIV_ROUND_UP(timeout
, USEC_PER_SEC
));
121 STRV_FOREACH(e
, envp
)
123 return log_error_errno(errno
, "Failed to set environment variable: %m");
125 STRV_FOREACH(path
, paths
) {
126 _cleanup_free_
char *t
= NULL
;
127 _cleanup_close_
int fd
= -1;
135 fd
= open_serialization_fd(basename(*path
));
137 return log_error_errno(fd
, "Failed to open serialization file: %m");
140 r
= do_spawn(t
, argv
, fd
, &pid
, FLAGS_SET(flags
, EXEC_DIR_SET_SYSTEMD_EXEC_PID
));
144 if (parallel_execution
) {
145 r
= hashmap_put(pids
, PID_TO_PTR(pid
), t
);
150 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
151 if (FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
)) {
158 if (lseek(fd
, 0, SEEK_SET
) < 0)
159 return log_error_errno(errno
, "Failed to seek on serialization fd: %m");
161 r
= callbacks
[STDOUT_GENERATE
](fd
, callback_args
[STDOUT_GENERATE
]);
164 return log_error_errno(r
, "Failed to process output from %s: %m", *path
);
170 r
= callbacks
[STDOUT_COLLECT
](output_fd
, callback_args
[STDOUT_COLLECT
]);
172 return log_error_errno(r
, "Callback two failed: %m");
175 while (!hashmap_isempty(pids
)) {
176 _cleanup_free_
char *t
= NULL
;
179 pid
= PTR_TO_PID(hashmap_first_key(pids
));
182 t
= hashmap_remove(pids
, PID_TO_PTR(pid
));
185 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
186 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
193 int execute_directories(
194 const char* const* directories
,
196 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
197 void* const callback_args
[_STDOUT_CONSUME_MAX
],
200 ExecDirFlags flags
) {
202 char **dirs
= (char**) directories
;
203 _cleanup_close_
int fd
= -1;
208 assert(!strv_isempty(dirs
));
210 name
= basename(dirs
[0]);
211 assert(!isempty(name
));
214 assert(callback_args
);
215 assert(callbacks
[STDOUT_GENERATE
]);
216 assert(callbacks
[STDOUT_COLLECT
]);
217 assert(callbacks
[STDOUT_CONSUME
]);
219 fd
= open_serialization_fd(name
);
221 return log_error_errno(fd
, "Failed to open serialization file: %m");
224 /* Executes all binaries in the directories serially or in parallel and waits for
225 * them to finish. Optionally a timeout is applied. If a file with the same name
226 * exists in more than one directory, the earliest one wins. */
228 r
= safe_fork("(sd-executor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &executor_pid
);
232 r
= do_execute(dirs
, timeout
, callbacks
, callback_args
, fd
, argv
, envp
, flags
);
233 _exit(r
< 0 ? EXIT_FAILURE
: r
);
236 r
= wait_for_terminate_and_check("(sd-executor)", executor_pid
, 0);
239 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
245 if (lseek(fd
, 0, SEEK_SET
) < 0)
246 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
248 r
= callbacks
[STDOUT_CONSUME
](fd
, callback_args
[STDOUT_CONSUME
]);
251 return log_error_errno(r
, "Failed to parse returned data: %m");
255 static int gather_environment_generate(int fd
, void *arg
) {
257 _cleanup_fclose_
FILE *f
= NULL
;
258 _cleanup_strv_free_
char **new = NULL
;
261 /* Read a series of VAR=value assignments from fd, use them to update the list of
262 * variables in env. Also update the exported environment.
264 * fd is always consumed, even on error.
275 r
= load_env_file_pairs(f
, NULL
, &new);
279 STRV_FOREACH_PAIR(x
, y
, new) {
280 if (!env_name_is_valid(*x
)) {
281 log_warning("Invalid variable assignment \"%s=...\", ignoring.", *x
);
285 r
= strv_env_assign(env
, *x
, *y
);
289 if (setenv(*x
, *y
, true) < 0)
296 static int gather_environment_collect(int fd
, void *arg
) {
297 _cleanup_fclose_
FILE *f
= NULL
;
301 /* Write out a series of env=cescape(VAR=value) assignments to fd. */
311 r
= serialize_strv(f
, "env", *env
);
315 r
= fflush_and_check(f
);
322 static int gather_environment_consume(int fd
, void *arg
) {
323 _cleanup_fclose_
FILE *f
= NULL
;
327 /* Read a series of env=cescape(VAR=value) assignments from fd into env. */
338 _cleanup_free_
char *line
= NULL
;
342 k
= read_line(f
, LONG_LINE_MAX
, &line
);
348 v
= startswith(line
, "env=");
350 log_debug("Serialization line \"%s\" unexpectedly didn't start with \"env=\".", line
);
357 k
= deserialize_environment(v
, env
);
359 log_debug_errno(k
, "Invalid serialization line \"%s\": %m", line
);
369 int exec_command_flags_from_strv(char **ex_opts
, ExecCommandFlags
*flags
) {
370 ExecCommandFlags ex_flag
, ret_flags
= 0;
374 STRV_FOREACH(opt
, ex_opts
) {
375 ex_flag
= exec_command_flags_from_string(*opt
);
378 ret_flags
|= ex_flag
;
386 int exec_command_flags_to_strv(ExecCommandFlags flags
, char ***ex_opts
) {
387 _cleanup_strv_free_
char **ret_opts
= NULL
;
388 ExecCommandFlags it
= flags
;
397 for (i
= 0; it
!= 0; it
&= ~(1 << i
), i
++) {
398 if (FLAGS_SET(flags
, (1 << i
))) {
399 str
= exec_command_flags_to_string(1 << i
);
403 r
= strv_extend(&ret_opts
, str
);
409 *ex_opts
= TAKE_PTR(ret_opts
);
414 const gather_stdout_callback_t gather_environment
[] = {
415 gather_environment_generate
,
416 gather_environment_collect
,
417 gather_environment_consume
,
420 static const char* const exec_command_strings
[] = {
421 "ignore-failure", /* EXEC_COMMAND_IGNORE_FAILURE */
422 "privileged", /* EXEC_COMMAND_FULLY_PRIVILEGED */
423 "no-setuid", /* EXEC_COMMAND_NO_SETUID */
424 "ambient", /* EXEC_COMMAND_AMBIENT_MAGIC */
425 "no-env-expand", /* EXEC_COMMAND_NO_ENV_EXPAND */
428 const char* exec_command_flags_to_string(ExecCommandFlags i
) {
431 for (idx
= 0; idx
< ELEMENTSOF(exec_command_strings
); idx
++)
433 return exec_command_strings
[idx
];
438 ExecCommandFlags
exec_command_flags_from_string(const char *s
) {
441 idx
= string_table_lookup(exec_command_strings
, ELEMENTSOF(exec_command_strings
), s
);
444 return _EXEC_COMMAND_FLAGS_INVALID
;
449 int fexecve_or_execve(int executable_fd
, const char *executable
, char *const argv
[], char *const envp
[]) {
450 /* Refuse invalid fds, regardless if fexecve() use is enabled or not */
451 if (executable_fd
< 0)
454 /* Block any attempts on exploiting Linux' liberal argv[] handling, i.e. CVE-2021-4034 and suchlike */
455 if (isempty(executable
) || strv_isempty(argv
))
460 execveat(executable_fd
, "", argv
, envp
, AT_EMPTY_PATH
);
462 if (IN_SET(errno
, ENOSYS
, ENOENT
) || ERRNO_IS_PRIVILEGE(errno
))
463 /* Old kernel or a script or an overzealous seccomp filter? Let's fall back to execve().
465 * fexecve(3): "If fd refers to a script (i.e., it is an executable text file that names a
466 * script interpreter with a first line that begins with the characters #!) and the
467 * close-on-exec flag has been set for fd, then fexecve() fails with the error ENOENT. This
468 * error occurs because, by the time the script interpreter is executed, fd has already been
469 * closed because of the close-on-exec flag. Thus, the close-on-exec flag can't be set on fd
470 * if it refers to a script."
472 * Unfortunately, if we unset close-on-exec, the script will be executed just fine, but (at
473 * least in case of bash) the script name, $0, will be shown as /dev/fd/nnn, which breaks
474 * scripts which make use of $0. Thus, let's fall back to execve() in this case.
477 execve(executable
, argv
, envp
);
481 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
482 bool stdout_is_tty
, stderr_is_tty
;
490 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
492 r
= safe_fork_full(name
,
495 FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_CLOSE_ALL_FDS
|FORK_REOPEN_LOG
,
504 stdout_is_tty
= isatty(STDOUT_FILENO
);
505 stderr_is_tty
= isatty(STDERR_FILENO
);
507 if (!stdout_is_tty
|| !stderr_is_tty
) {
510 /* Detach from stdout/stderr and reopen /dev/tty for them. This is important to ensure that
511 * when systemctl is started via popen() or a similar call that expects to read EOF we
512 * actually do generate EOF and not delay this indefinitely by keeping an unused copy of
514 fd
= open("/dev/tty", O_WRONLY
);
516 if (errno
!= ENXIO
) {
517 log_error_errno(errno
, "Failed to open /dev/tty: %m");
521 /* If we get ENXIO here we have no controlling TTY even though stdout/stderr are
522 * connected to a TTY. That's a weird setup, but let's handle it gracefully: let's
523 * skip the forking of the agents, given the TTY setup is not in order. */
525 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
526 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
530 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
531 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
535 fd
= safe_close_above_stdio(fd
);
539 (void) rlimit_nofile_safe();
541 /* Count arguments */
543 for (n
= 0; va_arg(ap
, char*); n
++)
548 l
= newa(char*, n
+ 1);
550 /* Fill in arguments */
552 for (i
= 0; i
<= n
; i
++)
553 l
[i
] = va_arg(ap
, char*);