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
) {
256 char ***env
= ASSERT_PTR(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.
273 r
= load_env_file_pairs(f
, NULL
, &new);
277 STRV_FOREACH_PAIR(x
, y
, new) {
278 if (!env_name_is_valid(*x
)) {
279 log_warning("Invalid variable assignment \"%s=...\", ignoring.", *x
);
283 r
= strv_env_assign(env
, *x
, *y
);
287 if (setenv(*x
, *y
, true) < 0)
294 static int gather_environment_collect(int fd
, void *arg
) {
295 _cleanup_fclose_
FILE *f
= NULL
;
296 char ***env
= ASSERT_PTR(arg
);
299 /* Write out a series of env=cescape(VAR=value) assignments to fd. */
307 r
= serialize_strv(f
, "env", *env
);
311 r
= fflush_and_check(f
);
318 static int gather_environment_consume(int fd
, void *arg
) {
319 _cleanup_fclose_
FILE *f
= NULL
;
320 char ***env
= ASSERT_PTR(arg
);
323 /* Read a series of env=cescape(VAR=value) assignments from fd into env. */
332 _cleanup_free_
char *line
= NULL
;
336 k
= read_line(f
, LONG_LINE_MAX
, &line
);
342 v
= startswith(line
, "env=");
344 log_debug("Serialization line \"%s\" unexpectedly didn't start with \"env=\".", line
);
351 k
= deserialize_environment(v
, env
);
353 log_debug_errno(k
, "Invalid serialization line \"%s\": %m", line
);
363 int exec_command_flags_from_strv(char **ex_opts
, ExecCommandFlags
*flags
) {
364 ExecCommandFlags ex_flag
, ret_flags
= 0;
368 STRV_FOREACH(opt
, ex_opts
) {
369 ex_flag
= exec_command_flags_from_string(*opt
);
372 ret_flags
|= ex_flag
;
380 int exec_command_flags_to_strv(ExecCommandFlags flags
, char ***ex_opts
) {
381 _cleanup_strv_free_
char **ret_opts
= NULL
;
382 ExecCommandFlags it
= flags
;
391 for (i
= 0; it
!= 0; it
&= ~(1 << i
), i
++) {
392 if (FLAGS_SET(flags
, (1 << i
))) {
393 str
= exec_command_flags_to_string(1 << i
);
397 r
= strv_extend(&ret_opts
, str
);
403 *ex_opts
= TAKE_PTR(ret_opts
);
408 const gather_stdout_callback_t gather_environment
[] = {
409 gather_environment_generate
,
410 gather_environment_collect
,
411 gather_environment_consume
,
414 static const char* const exec_command_strings
[] = {
415 "ignore-failure", /* EXEC_COMMAND_IGNORE_FAILURE */
416 "privileged", /* EXEC_COMMAND_FULLY_PRIVILEGED */
417 "no-setuid", /* EXEC_COMMAND_NO_SETUID */
418 "ambient", /* EXEC_COMMAND_AMBIENT_MAGIC */
419 "no-env-expand", /* EXEC_COMMAND_NO_ENV_EXPAND */
422 const char* exec_command_flags_to_string(ExecCommandFlags i
) {
425 for (idx
= 0; idx
< ELEMENTSOF(exec_command_strings
); idx
++)
427 return exec_command_strings
[idx
];
432 ExecCommandFlags
exec_command_flags_from_string(const char *s
) {
435 idx
= string_table_lookup(exec_command_strings
, ELEMENTSOF(exec_command_strings
), s
);
438 return _EXEC_COMMAND_FLAGS_INVALID
;
443 int fexecve_or_execve(int executable_fd
, const char *executable
, char *const argv
[], char *const envp
[]) {
444 /* Refuse invalid fds, regardless if fexecve() use is enabled or not */
445 if (executable_fd
< 0)
448 /* Block any attempts on exploiting Linux' liberal argv[] handling, i.e. CVE-2021-4034 and suchlike */
449 if (isempty(executable
) || strv_isempty(argv
))
454 execveat(executable_fd
, "", argv
, envp
, AT_EMPTY_PATH
);
456 if (IN_SET(errno
, ENOSYS
, ENOENT
) || ERRNO_IS_PRIVILEGE(errno
))
457 /* Old kernel or a script or an overzealous seccomp filter? Let's fall back to execve().
459 * fexecve(3): "If fd refers to a script (i.e., it is an executable text file that names a
460 * script interpreter with a first line that begins with the characters #!) and the
461 * close-on-exec flag has been set for fd, then fexecve() fails with the error ENOENT. This
462 * error occurs because, by the time the script interpreter is executed, fd has already been
463 * closed because of the close-on-exec flag. Thus, the close-on-exec flag can't be set on fd
464 * if it refers to a script."
466 * Unfortunately, if we unset close-on-exec, the script will be executed just fine, but (at
467 * least in case of bash) the script name, $0, will be shown as /dev/fd/nnn, which breaks
468 * scripts which make use of $0. Thus, let's fall back to execve() in this case.
471 execve(executable
, argv
, envp
);
475 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
476 bool stdout_is_tty
, stderr_is_tty
;
484 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
486 r
= safe_fork_full(name
,
489 FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_CLOSE_ALL_FDS
|FORK_REOPEN_LOG
,
498 stdout_is_tty
= isatty(STDOUT_FILENO
);
499 stderr_is_tty
= isatty(STDERR_FILENO
);
501 if (!stdout_is_tty
|| !stderr_is_tty
) {
504 /* Detach from stdout/stderr and reopen /dev/tty for them. This is important to ensure that
505 * when systemctl is started via popen() or a similar call that expects to read EOF we
506 * actually do generate EOF and not delay this indefinitely by keeping an unused copy of
508 fd
= open("/dev/tty", O_WRONLY
);
510 if (errno
!= ENXIO
) {
511 log_error_errno(errno
, "Failed to open /dev/tty: %m");
515 /* If we get ENXIO here we have no controlling TTY even though stdout/stderr are
516 * connected to a TTY. That's a weird setup, but let's handle it gracefully: let's
517 * skip the forking of the agents, given the TTY setup is not in order. */
519 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
520 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
524 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
525 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
529 fd
= safe_close_above_stdio(fd
);
533 (void) rlimit_nofile_safe();
535 /* Count arguments */
537 for (n
= 0; va_arg(ap
, char*); n
++)
542 l
= newa(char*, n
+ 1);
544 /* Fill in arguments */
546 for (i
= 0; i
<= n
; i
++)
547 l
[i
] = va_arg(ap
, char*);