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
;
96 bool parallel_execution
;
98 /* We fork this all off from a child process so that we can somewhat cleanly make
99 * use of SIGALRM to set a time limit.
101 * We attempt to perform parallel execution if configured by the user, however
102 * if `callbacks` is nonnull, execution must be serial.
104 parallel_execution
= FLAGS_SET(flags
, EXEC_DIR_PARALLEL
) && !callbacks
;
106 r
= conf_files_list_strv(&paths
, NULL
, NULL
, CONF_FILES_EXECUTABLE
|CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char* const*) directories
);
108 return log_error_errno(r
, "Failed to enumerate executables: %m");
110 if (parallel_execution
) {
111 pids
= hashmap_new(NULL
);
116 /* Abort execution of this process after the timeout. We simply rely on SIGALRM as
117 * default action terminating the process, and turn on alarm(). */
119 if (timeout
!= USEC_INFINITY
)
120 alarm(DIV_ROUND_UP(timeout
, USEC_PER_SEC
));
122 STRV_FOREACH(e
, envp
)
124 return log_error_errno(errno
, "Failed to set environment variable: %m");
126 STRV_FOREACH(path
, paths
) {
127 _cleanup_free_
char *t
= NULL
;
128 _cleanup_close_
int fd
= -1;
136 fd
= open_serialization_fd(basename(*path
));
138 return log_error_errno(fd
, "Failed to open serialization file: %m");
141 r
= do_spawn(t
, argv
, fd
, &pid
, FLAGS_SET(flags
, EXEC_DIR_SET_SYSTEMD_EXEC_PID
));
145 if (parallel_execution
) {
146 r
= hashmap_put(pids
, PID_TO_PTR(pid
), t
);
151 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
152 if (FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
)) {
159 if (lseek(fd
, 0, SEEK_SET
) < 0)
160 return log_error_errno(errno
, "Failed to seek on serialization fd: %m");
162 r
= callbacks
[STDOUT_GENERATE
](fd
, callback_args
[STDOUT_GENERATE
]);
165 return log_error_errno(r
, "Failed to process output from %s: %m", *path
);
171 r
= callbacks
[STDOUT_COLLECT
](output_fd
, callback_args
[STDOUT_COLLECT
]);
173 return log_error_errno(r
, "Callback two failed: %m");
176 while (!hashmap_isempty(pids
)) {
177 _cleanup_free_
char *t
= NULL
;
180 pid
= PTR_TO_PID(hashmap_first_key(pids
));
183 t
= hashmap_remove(pids
, PID_TO_PTR(pid
));
186 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
187 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
194 int execute_directories(
195 const char* const* directories
,
197 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
198 void* const callback_args
[_STDOUT_CONSUME_MAX
],
201 ExecDirFlags flags
) {
203 char **dirs
= (char**) directories
;
204 _cleanup_close_
int fd
= -1;
209 assert(!strv_isempty(dirs
));
211 name
= basename(dirs
[0]);
212 assert(!isempty(name
));
215 assert(callback_args
);
216 assert(callbacks
[STDOUT_GENERATE
]);
217 assert(callbacks
[STDOUT_COLLECT
]);
218 assert(callbacks
[STDOUT_CONSUME
]);
220 fd
= open_serialization_fd(name
);
222 return log_error_errno(fd
, "Failed to open serialization file: %m");
225 /* Executes all binaries in the directories serially or in parallel and waits for
226 * them to finish. Optionally a timeout is applied. If a file with the same name
227 * exists in more than one directory, the earliest one wins. */
229 r
= safe_fork("(sd-executor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &executor_pid
);
233 r
= do_execute(dirs
, timeout
, callbacks
, callback_args
, fd
, argv
, envp
, flags
);
234 _exit(r
< 0 ? EXIT_FAILURE
: r
);
237 r
= wait_for_terminate_and_check("(sd-executor)", executor_pid
, 0);
240 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
246 if (lseek(fd
, 0, SEEK_SET
) < 0)
247 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
249 r
= callbacks
[STDOUT_CONSUME
](fd
, callback_args
[STDOUT_CONSUME
]);
252 return log_error_errno(r
, "Failed to parse returned data: %m");
256 static int gather_environment_generate(int fd
, void *arg
) {
257 char ***env
= arg
, **x
, **y
;
258 _cleanup_fclose_
FILE *f
= NULL
;
259 _cleanup_strv_free_
char **new = NULL
;
262 /* Read a series of VAR=value assignments from fd, use them to update the list of
263 * variables in env. Also update the exported environment.
265 * fd is always consumed, even on error.
276 r
= load_env_file_pairs(f
, NULL
, &new);
280 STRV_FOREACH_PAIR(x
, y
, new) {
281 if (!env_name_is_valid(*x
)) {
282 log_warning("Invalid variable assignment \"%s=...\", ignoring.", *x
);
286 r
= strv_env_assign(env
, *x
, *y
);
290 if (setenv(*x
, *y
, true) < 0)
297 static int gather_environment_collect(int fd
, void *arg
) {
298 _cleanup_fclose_
FILE *f
= NULL
;
302 /* Write out a series of env=cescape(VAR=value) assignments to fd. */
312 r
= serialize_strv(f
, "env", *env
);
316 r
= fflush_and_check(f
);
323 static int gather_environment_consume(int fd
, void *arg
) {
324 _cleanup_fclose_
FILE *f
= NULL
;
328 /* Read a series of env=cescape(VAR=value) assignments from fd into env. */
339 _cleanup_free_
char *line
= NULL
;
343 k
= read_line(f
, LONG_LINE_MAX
, &line
);
349 v
= startswith(line
, "env=");
351 log_debug("Serialization line \"%s\" unexpectedly didn't start with \"env=\".", line
);
358 k
= deserialize_environment(v
, env
);
360 log_debug_errno(k
, "Invalid serialization line \"%s\": %m", line
);
370 int exec_command_flags_from_strv(char **ex_opts
, ExecCommandFlags
*flags
) {
371 ExecCommandFlags ex_flag
, ret_flags
= 0;
376 STRV_FOREACH(opt
, ex_opts
) {
377 ex_flag
= exec_command_flags_from_string(*opt
);
380 ret_flags
|= ex_flag
;
388 int exec_command_flags_to_strv(ExecCommandFlags flags
, char ***ex_opts
) {
389 _cleanup_strv_free_
char **ret_opts
= NULL
;
390 ExecCommandFlags it
= flags
;
399 for (i
= 0; it
!= 0; it
&= ~(1 << i
), i
++) {
400 if (FLAGS_SET(flags
, (1 << i
))) {
401 str
= exec_command_flags_to_string(1 << i
);
405 r
= strv_extend(&ret_opts
, str
);
411 *ex_opts
= TAKE_PTR(ret_opts
);
416 const gather_stdout_callback_t gather_environment
[] = {
417 gather_environment_generate
,
418 gather_environment_collect
,
419 gather_environment_consume
,
422 static const char* const exec_command_strings
[] = {
423 "ignore-failure", /* EXEC_COMMAND_IGNORE_FAILURE */
424 "privileged", /* EXEC_COMMAND_FULLY_PRIVILEGED */
425 "no-setuid", /* EXEC_COMMAND_NO_SETUID */
426 "ambient", /* EXEC_COMMAND_AMBIENT_MAGIC */
427 "no-env-expand", /* EXEC_COMMAND_NO_ENV_EXPAND */
430 const char* exec_command_flags_to_string(ExecCommandFlags i
) {
433 for (idx
= 0; idx
< ELEMENTSOF(exec_command_strings
); idx
++)
435 return exec_command_strings
[idx
];
440 ExecCommandFlags
exec_command_flags_from_string(const char *s
) {
443 idx
= string_table_lookup(exec_command_strings
, ELEMENTSOF(exec_command_strings
), s
);
446 return _EXEC_COMMAND_FLAGS_INVALID
;
451 int fexecve_or_execve(int executable_fd
, const char *executable
, char *const argv
[], char *const envp
[]) {
452 /* Refuse invalid fds, regardless if fexecve() use is enabled or not */
453 if (executable_fd
< 0)
456 /* Block any attempts on exploiting Linux' liberal argv[] handling, i.e. CVE-2021-4034 and suchlike */
457 if (isempty(executable
) || strv_isempty(argv
))
462 execveat(executable_fd
, "", argv
, envp
, AT_EMPTY_PATH
);
464 if (IN_SET(errno
, ENOSYS
, ENOENT
) || ERRNO_IS_PRIVILEGE(errno
))
465 /* Old kernel or a script or an overzealous seccomp filter? Let's fall back to execve().
467 * fexecve(3): "If fd refers to a script (i.e., it is an executable text file that names a
468 * script interpreter with a first line that begins with the characters #!) and the
469 * close-on-exec flag has been set for fd, then fexecve() fails with the error ENOENT. This
470 * error occurs because, by the time the script interpreter is executed, fd has already been
471 * closed because of the close-on-exec flag. Thus, the close-on-exec flag can't be set on fd
472 * if it refers to a script."
474 * Unfortunately, if we unset close-on-exec, the script will be executed just fine, but (at
475 * least in case of bash) the script name, $0, will be shown as /dev/fd/nnn, which breaks
476 * scripts which make use of $0. Thus, let's fall back to execve() in this case.
479 execve(executable
, argv
, envp
);
483 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
484 bool stdout_is_tty
, stderr_is_tty
;
492 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
494 r
= safe_fork_full(name
,
497 FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_CLOSE_ALL_FDS
|FORK_REOPEN_LOG
,
506 stdout_is_tty
= isatty(STDOUT_FILENO
);
507 stderr_is_tty
= isatty(STDERR_FILENO
);
509 if (!stdout_is_tty
|| !stderr_is_tty
) {
512 /* Detach from stdout/stderr and reopen /dev/tty for them. This is important to ensure that
513 * when systemctl is started via popen() or a similar call that expects to read EOF we
514 * actually do generate EOF and not delay this indefinitely by keeping an unused copy of
516 fd
= open("/dev/tty", O_WRONLY
);
518 if (errno
!= ENXIO
) {
519 log_error_errno(errno
, "Failed to open /dev/tty: %m");
523 /* If we get ENXIO here we have no controlling TTY even though stdout/stderr are
524 * connected to a TTY. That's a weird setup, but let's handle it gracefully: let's
525 * skip the forking of the agents, given the TTY setup is not in order. */
527 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
528 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
532 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
533 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
537 fd
= safe_close_above_stdio(fd
);
541 (void) rlimit_nofile_safe();
543 /* Count arguments */
545 for (n
= 0; va_arg(ap
, char*); n
++)
550 l
= newa(char*, n
+ 1);
552 /* Fill in arguments */
554 for (i
= 0; i
<= n
; i
++)
555 l
[i
] = va_arg(ap
, char*);