1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include "alloc-util.h"
11 #include "conf-files.h"
14 #include "errno-util.h"
16 #include "exec-util.h"
21 #include "missing_syscall.h"
22 #include "path-util.h"
23 #include "process-util.h"
24 #include "serialize.h"
26 #include "signal-util.h"
27 #include "stat-util.h"
28 #include "string-table.h"
29 #include "string-util.h"
31 #include "terminal-util.h"
32 #include "tmpfile-util.h"
34 #define EXIT_SKIP_REMAINING 77
36 /* Put this test here for a lack of better place */
37 assert_cc(EAGAIN
== EWOULDBLOCK
);
39 static int do_spawn(const char *path
, char *argv
[], int stdout_fd
, pid_t
*pid
, bool set_systemd_exec_pid
) {
43 if (null_or_empty_path(path
) > 0) {
44 log_debug("%s is empty (a mask).", path
);
48 r
= safe_fork("(direxec)", FORK_DEATHSIG_SIGTERM
|FORK_LOG
|FORK_RLIMIT_NOFILE_SAFE
, &_pid
);
55 r
= rearrange_stdio(STDIN_FILENO
, TAKE_FD(stdout_fd
), STDERR_FILENO
);
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(
86 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
87 void* const callback_args
[_STDOUT_CONSUME_MAX
],
93 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
94 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 if (parallel_execution
) {
106 pids
= hashmap_new(NULL
);
111 /* Abort execution of this process after the timeout. We simply rely on SIGALRM as
112 * default action terminating the process, and turn on alarm(). */
114 if (timeout
!= USEC_INFINITY
)
115 alarm(DIV_ROUND_UP(timeout
, USEC_PER_SEC
));
117 STRV_FOREACH(e
, envp
)
119 return log_error_errno(errno
, "Failed to set environment variable: %m");
121 STRV_FOREACH(path
, paths
) {
122 _cleanup_free_
char *t
= NULL
;
123 _cleanup_close_
int fd
= -EBADF
;
126 t
= path_join(root
, *path
);
131 _cleanup_free_
char *bn
= NULL
;
133 r
= path_extract_filename(*path
, &bn
);
135 return log_error_errno(r
, "Failed to extract filename from path '%s': %m", *path
);
137 fd
= open_serialization_fd(bn
);
139 return log_error_errno(fd
, "Failed to open serialization file: %m");
143 _cleanup_free_
char *args
= NULL
;
145 args
= quote_command_line(strv_skip(argv
, 1), SHELL_ESCAPE_EMPTY
);
147 log_debug("About to execute %s%s%s", t
, argv
? " " : "", argv
? strnull(args
) : "");
150 r
= do_spawn(t
, argv
, fd
, &pid
, FLAGS_SET(flags
, EXEC_DIR_SET_SYSTEMD_EXEC_PID
));
154 if (parallel_execution
) {
155 r
= hashmap_put(pids
, PID_TO_PTR(pid
), t
);
160 bool skip_remaining
= false;
162 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG_ABNORMAL
);
166 if (FLAGS_SET(flags
, EXEC_DIR_SKIP_REMAINING
) && r
== EXIT_SKIP_REMAINING
) {
167 log_info("%s succeeded with exit status %i, not executing remaining executables.", *path
, r
);
168 skip_remaining
= true;
169 } else if (FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
))
170 log_warning("%s failed with exit status %i, ignoring.", *path
, r
);
172 log_error("%s failed with exit status %i.", *path
, r
);
178 if (lseek(fd
, 0, SEEK_SET
) < 0)
179 return log_error_errno(errno
, "Failed to seek on serialization fd: %m");
181 r
= callbacks
[STDOUT_GENERATE
](TAKE_FD(fd
), callback_args
[STDOUT_GENERATE
]);
183 return log_error_errno(r
, "Failed to process output from %s: %m", *path
);
192 r
= callbacks
[STDOUT_COLLECT
](output_fd
, callback_args
[STDOUT_COLLECT
]);
194 return log_error_errno(r
, "Callback two failed: %m");
197 while (!hashmap_isempty(pids
)) {
198 _cleanup_free_
char *t
= NULL
;
201 pid
= PTR_TO_PID(hashmap_first_key(pids
));
204 t
= hashmap_remove(pids
, PID_TO_PTR(pid
));
207 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
210 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
222 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
223 void* const callback_args
[_STDOUT_CONSUME_MAX
],
226 ExecDirFlags flags
) {
228 _cleanup_close_
int fd
= -EBADF
;
232 assert(!FLAGS_SET(flags
, EXEC_DIR_PARALLEL
| EXEC_DIR_SKIP_REMAINING
));
234 if (strv_isempty(paths
))
239 assert(callback_args
);
240 assert(callbacks
[STDOUT_GENERATE
]);
241 assert(callbacks
[STDOUT_COLLECT
]);
242 assert(callbacks
[STDOUT_CONSUME
]);
244 fd
= open_serialization_fd(name
);
246 return log_error_errno(fd
, "Failed to open serialization file: %m");
249 /* Executes all binaries in the directories serially or in parallel and waits for
250 * them to finish. Optionally a timeout is applied. If a file with the same name
251 * exists in more than one directory, the earliest one wins. */
253 r
= safe_fork("(sd-exec-strv)", FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
|FORK_LOG
, &executor_pid
);
257 r
= do_execute(paths
, root
, timeout
, callbacks
, callback_args
, fd
, argv
, envp
, flags
);
258 _exit(r
< 0 ? EXIT_FAILURE
: r
);
261 r
= wait_for_terminate_and_check("(sd-exec-strv)", executor_pid
, 0);
264 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
270 if (lseek(fd
, 0, SEEK_SET
) < 0)
271 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
273 r
= callbacks
[STDOUT_CONSUME
](TAKE_FD(fd
), callback_args
[STDOUT_CONSUME
]);
275 return log_error_errno(r
, "Failed to parse returned data: %m");
279 int execute_directories(
280 const char* const* directories
,
282 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
283 void* const callback_args
[_STDOUT_CONSUME_MAX
],
286 ExecDirFlags flags
) {
288 _cleanup_strv_free_
char **paths
= NULL
;
289 _cleanup_free_
char *name
= NULL
;
292 assert(!strv_isempty((char**) directories
));
294 r
= conf_files_list_strv(&paths
, NULL
, NULL
, CONF_FILES_EXECUTABLE
|CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, directories
);
296 return log_error_errno(r
, "Failed to enumerate executables: %m");
298 if (strv_isempty(paths
)) {
299 log_debug("No executables found.");
304 r
= path_extract_filename(directories
[0], &name
);
306 return log_error_errno(r
, "Failed to extract file name from '%s': %m", directories
[0]);
309 return execute_strv(name
, paths
, NULL
, timeout
, callbacks
, callback_args
, argv
, envp
, flags
);
312 static int gather_environment_generate(int fd
, void *arg
) {
313 char ***env
= ASSERT_PTR(arg
);
314 _cleanup_fclose_
FILE *f
= NULL
;
315 _cleanup_strv_free_
char **new = NULL
;
318 /* Read a series of VAR=value assignments from fd, use them to update the list of
319 * variables in env. Also update the exported environment.
321 * fd is always consumed, even on error.
330 r
= load_env_file_pairs(f
, NULL
, &new);
334 STRV_FOREACH_PAIR(x
, y
, new) {
335 if (!env_name_is_valid(*x
)) {
336 log_warning("Invalid variable assignment \"%s=...\", ignoring.", *x
);
340 r
= strv_env_assign(env
, *x
, *y
);
344 if (setenv(*x
, *y
, true) < 0)
351 static int gather_environment_collect(int fd
, void *arg
) {
352 _cleanup_fclose_
FILE *f
= NULL
;
353 char ***env
= ASSERT_PTR(arg
);
356 /* Write out a series of env=cescape(VAR=value) assignments to fd. */
364 r
= serialize_strv(f
, "env", *env
);
368 r
= fflush_and_check(f
);
375 static int gather_environment_consume(int fd
, void *arg
) {
376 _cleanup_fclose_
FILE *f
= NULL
;
377 char ***env
= ASSERT_PTR(arg
);
380 /* Read a series of env=cescape(VAR=value) assignments from fd into env. */
389 _cleanup_free_
char *line
= NULL
;
393 k
= read_line(f
, LONG_LINE_MAX
, &line
);
399 v
= startswith(line
, "env=");
401 log_debug("Serialization line \"%s\" unexpectedly didn't start with \"env=\".", line
);
408 k
= deserialize_environment(v
, env
);
410 log_debug_errno(k
, "Invalid serialization line \"%s\": %m", line
);
420 int exec_command_flags_from_strv(char **ex_opts
, ExecCommandFlags
*flags
) {
421 ExecCommandFlags ex_flag
, ret_flags
= 0;
425 STRV_FOREACH(opt
, ex_opts
) {
426 ex_flag
= exec_command_flags_from_string(*opt
);
429 ret_flags
|= ex_flag
;
437 int exec_command_flags_to_strv(ExecCommandFlags flags
, char ***ex_opts
) {
438 _cleanup_strv_free_
char **ret_opts
= NULL
;
439 ExecCommandFlags it
= flags
;
448 for (unsigned i
= 0; it
!= 0; it
&= ~(1 << i
), i
++)
449 if (FLAGS_SET(flags
, (1 << i
))) {
450 str
= exec_command_flags_to_string(1 << i
);
454 r
= strv_extend(&ret_opts
, str
);
459 *ex_opts
= TAKE_PTR(ret_opts
);
464 const gather_stdout_callback_t gather_environment
[] = {
465 gather_environment_generate
,
466 gather_environment_collect
,
467 gather_environment_consume
,
470 static const char* const exec_command_strings
[] = {
471 "ignore-failure", /* EXEC_COMMAND_IGNORE_FAILURE */
472 "privileged", /* EXEC_COMMAND_FULLY_PRIVILEGED */
473 "no-setuid", /* EXEC_COMMAND_NO_SETUID */
474 "ambient", /* EXEC_COMMAND_AMBIENT_MAGIC */
475 "no-env-expand", /* EXEC_COMMAND_NO_ENV_EXPAND */
478 const char* exec_command_flags_to_string(ExecCommandFlags i
) {
479 for (size_t idx
= 0; idx
< ELEMENTSOF(exec_command_strings
); idx
++)
481 return exec_command_strings
[idx
];
486 ExecCommandFlags
exec_command_flags_from_string(const char *s
) {
489 idx
= string_table_lookup(exec_command_strings
, ELEMENTSOF(exec_command_strings
), s
);
492 return _EXEC_COMMAND_FLAGS_INVALID
;
497 int fexecve_or_execve(int executable_fd
, const char *executable
, char *const argv
[], char *const envp
[]) {
498 /* Refuse invalid fds, regardless if fexecve() use is enabled or not */
499 if (executable_fd
< 0)
502 /* Block any attempts on exploiting Linux' liberal argv[] handling, i.e. CVE-2021-4034 and suchlike */
503 if (isempty(executable
) || strv_isempty(argv
))
508 execveat(executable_fd
, "", argv
, envp
, AT_EMPTY_PATH
);
510 if (IN_SET(errno
, ENOSYS
, ENOENT
) || ERRNO_IS_PRIVILEGE(errno
))
511 /* Old kernel or a script or an overzealous seccomp filter? Let's fall back to execve().
513 * fexecve(3): "If fd refers to a script (i.e., it is an executable text file that names a
514 * script interpreter with a first line that begins with the characters #!) and the
515 * close-on-exec flag has been set for fd, then fexecve() fails with the error ENOENT. This
516 * error occurs because, by the time the script interpreter is executed, fd has already been
517 * closed because of the close-on-exec flag. Thus, the close-on-exec flag can't be set on fd
518 * if it refers to a script."
520 * Unfortunately, if we unset close-on-exec, the script will be executed just fine, but (at
521 * least in case of bash) the script name, $0, will be shown as /dev/fd/nnn, which breaks
522 * scripts which make use of $0. Thus, let's fall back to execve() in this case.
525 execve(executable
, argv
, envp
);
529 int fork_agent(const char *name
, const int except
[], size_t n_except
, pid_t
*ret_pid
, const char *path
, ...) {
530 bool stdout_is_tty
, stderr_is_tty
;
538 /* Spawns a temporary TTY agent, making sure it goes away when we go away */
540 r
= safe_fork_full(name
,
542 (int*) except
, /* safe_fork_full only changes except if you pass in FORK_PACK_FDS, which we don't */
544 FORK_RESET_SIGNALS
|FORK_DEATHSIG_SIGTERM
|FORK_CLOSE_ALL_FDS
|FORK_REOPEN_LOG
|FORK_RLIMIT_NOFILE_SAFE
,
553 stdout_is_tty
= isatty(STDOUT_FILENO
);
554 stderr_is_tty
= isatty(STDERR_FILENO
);
556 if (!stdout_is_tty
|| !stderr_is_tty
) {
559 /* Detach from stdout/stderr and reopen /dev/tty for them. This is important to ensure that
560 * when systemctl is started via popen() or a similar call that expects to read EOF we
561 * actually do generate EOF and not delay this indefinitely by keeping an unused copy of
563 fd
= open("/dev/tty", O_WRONLY
);
565 if (errno
!= ENXIO
) {
566 log_error_errno(errno
, "Failed to open /dev/tty: %m");
570 /* If we get ENXIO here we have no controlling TTY even though stdout/stderr are
571 * connected to a TTY. That's a weird setup, but let's handle it gracefully: let's
572 * skip the forking of the agents, given the TTY setup is not in order. */
574 if (!stdout_is_tty
&& dup2(fd
, STDOUT_FILENO
) < 0) {
575 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
579 if (!stderr_is_tty
&& dup2(fd
, STDERR_FILENO
) < 0) {
580 log_error_errno(errno
, "Failed to dup2 /dev/tty: %m");
584 fd
= safe_close_above_stdio(fd
);
588 /* Count arguments */
590 for (n
= 0; va_arg(ap
, char*); n
++)
595 l
= newa(char*, n
+ 1);
597 /* Fill in arguments */
599 for (i
= 0; i
<= n
; i
++)
600 l
[i
] = va_arg(ap
, char*);