1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include "alloc-util.h"
11 #include "conf-files.h"
14 #include "exec-util.h"
19 #include "process-util.h"
20 #include "rlimit-util.h"
21 #include "serialize.h"
23 #include "signal-util.h"
24 #include "stat-util.h"
25 #include "string-table.h"
26 #include "string-util.h"
28 #include "terminal-util.h"
29 #include "tmpfile-util.h"
32 /* Put this test here for a lack of better place */
33 assert_cc(EAGAIN
== EWOULDBLOCK
);
35 static int do_spawn(const char *path
, char *argv
[], int stdout_fd
, pid_t
*pid
) {
40 if (null_or_empty_path(path
)) {
41 log_debug("%s is empty (a mask).", path
);
45 r
= safe_fork("(direxec)", FORK_DEATHSIG
|FORK_LOG
, &_pid
);
52 r
= rearrange_stdio(STDIN_FILENO
, stdout_fd
, STDERR_FILENO
);
57 (void) rlimit_nofile_safe();
60 _argv
[0] = (char*) path
;
64 argv
[0] = (char*) path
;
67 log_error_errno(errno
, "Failed to execute %s: %m", path
);
75 static int do_execute(
78 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
79 void* const callback_args
[_STDOUT_CONSUME_MAX
],
85 _cleanup_hashmap_free_free_ Hashmap
*pids
= NULL
;
86 _cleanup_strv_free_
char **paths
= NULL
;
89 bool parallel_execution
;
91 /* We fork this all off from a child process so that we can somewhat cleanly make
92 * use of SIGALRM to set a time limit.
94 * We attempt to perform parallel execution if configured by the user, however
95 * if `callbacks` is nonnull, execution must be serial.
97 parallel_execution
= FLAGS_SET(flags
, EXEC_DIR_PARALLEL
) && !callbacks
;
99 r
= conf_files_list_strv(&paths
, NULL
, NULL
, CONF_FILES_EXECUTABLE
|CONF_FILES_REGULAR
|CONF_FILES_FILTER_MASKED
, (const char* const*) directories
);
101 return log_error_errno(r
, "Failed to enumerate executables: %m");
103 if (parallel_execution
) {
104 pids
= hashmap_new(NULL
);
109 /* Abort execution of this process after the timeout. We simply rely on SIGALRM as
110 * default action terminating the process, and turn on alarm(). */
112 if (timeout
!= USEC_INFINITY
)
113 alarm(DIV_ROUND_UP(timeout
, USEC_PER_SEC
));
115 STRV_FOREACH(e
, envp
)
117 return log_error_errno(errno
, "Failed to set environment variable: %m");
119 STRV_FOREACH(path
, paths
) {
120 _cleanup_free_
char *t
= NULL
;
121 _cleanup_close_
int fd
= -1;
129 fd
= open_serialization_fd(basename(*path
));
131 return log_error_errno(fd
, "Failed to open serialization file: %m");
134 r
= do_spawn(t
, argv
, fd
, &pid
);
138 if (parallel_execution
) {
139 r
= hashmap_put(pids
, PID_TO_PTR(pid
), t
);
144 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
145 if (FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
)) {
152 if (lseek(fd
, 0, SEEK_SET
) < 0)
153 return log_error_errno(errno
, "Failed to seek on serialization fd: %m");
155 r
= callbacks
[STDOUT_GENERATE
](fd
, callback_args
[STDOUT_GENERATE
]);
158 return log_error_errno(r
, "Failed to process output from %s: %m", *path
);
164 r
= callbacks
[STDOUT_COLLECT
](output_fd
, callback_args
[STDOUT_COLLECT
]);
166 return log_error_errno(r
, "Callback two failed: %m");
169 while (!hashmap_isempty(pids
)) {
170 _cleanup_free_
char *t
= NULL
;
173 pid
= PTR_TO_PID(hashmap_first_key(pids
));
176 t
= hashmap_remove(pids
, PID_TO_PTR(pid
));
179 r
= wait_for_terminate_and_check(t
, pid
, WAIT_LOG
);
180 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
187 int execute_directories(
188 const char* const* directories
,
190 gather_stdout_callback_t
const callbacks
[_STDOUT_CONSUME_MAX
],
191 void* const callback_args
[_STDOUT_CONSUME_MAX
],
194 ExecDirFlags flags
) {
196 char **dirs
= (char**) directories
;
197 _cleanup_close_
int fd
= -1;
202 assert(!strv_isempty(dirs
));
204 name
= basename(dirs
[0]);
205 assert(!isempty(name
));
208 assert(callback_args
);
209 assert(callbacks
[STDOUT_GENERATE
]);
210 assert(callbacks
[STDOUT_COLLECT
]);
211 assert(callbacks
[STDOUT_CONSUME
]);
213 fd
= open_serialization_fd(name
);
215 return log_error_errno(fd
, "Failed to open serialization file: %m");
218 /* Executes all binaries in the directories serially or in parallel and waits for
219 * them to finish. Optionally a timeout is applied. If a file with the same name
220 * exists in more than one directory, the earliest one wins. */
222 r
= safe_fork("(sd-executor)", FORK_RESET_SIGNALS
|FORK_DEATHSIG
|FORK_LOG
, &executor_pid
);
226 r
= do_execute(dirs
, timeout
, callbacks
, callback_args
, fd
, argv
, envp
, flags
);
227 _exit(r
< 0 ? EXIT_FAILURE
: r
);
230 r
= wait_for_terminate_and_check("(sd-executor)", executor_pid
, 0);
233 if (!FLAGS_SET(flags
, EXEC_DIR_IGNORE_ERRORS
) && r
> 0)
239 if (lseek(fd
, 0, SEEK_SET
) < 0)
240 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
242 r
= callbacks
[STDOUT_CONSUME
](fd
, callback_args
[STDOUT_CONSUME
]);
245 return log_error_errno(r
, "Failed to parse returned data: %m");
249 static int gather_environment_generate(int fd
, void *arg
) {
250 char ***env
= arg
, **x
, **y
;
251 _cleanup_fclose_
FILE *f
= NULL
;
252 _cleanup_strv_free_
char **new = NULL
;
255 /* Read a series of VAR=value assignments from fd, use them to update the list of
256 * variables in env. Also update the exported environment.
258 * fd is always consumed, even on error.
269 r
= load_env_file_pairs(f
, NULL
, &new);
273 STRV_FOREACH_PAIR(x
, y
, new) {
276 if (!env_name_is_valid(*x
)) {
277 log_warning("Invalid variable assignment \"%s=...\", ignoring.", *x
);
281 p
= strjoin(*x
, "=", *y
);
285 r
= strv_env_replace(env
, p
);
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;
375 STRV_FOREACH(opt
, ex_opts
) {
376 ex_flag
= exec_command_flags_from_string(*opt
);
378 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
;
396 for (i
= 0; it
!= 0; it
&= ~(1 << i
), i
++) {
397 if (FLAGS_SET(flags
, (1 << i
))) {
398 str
= exec_command_flags_to_string(1 << i
);
402 r
= strv_extend(&ret_opts
, str
);
408 *ex_opts
= TAKE_PTR(ret_opts
);
413 const gather_stdout_callback_t gather_environment
[] = {
414 gather_environment_generate
,
415 gather_environment_collect
,
416 gather_environment_consume
,
419 static const char* const exec_command_strings
[] = {
420 "ignore-failure", /* EXEC_COMMAND_IGNORE_FAILURE */
421 "privileged", /* EXEC_COMMAND_FULLY_PRIVILEGED */
422 "no-setuid", /* EXEC_COMMAND_NO_SETUID */
423 "ambient", /* EXEC_COMMAND_AMBIENT_MAGIC */
424 "no-env-expand", /* EXEC_COMMAND_NO_ENV_EXPAND */
427 const char* exec_command_flags_to_string(ExecCommandFlags i
) {
430 for (idx
= 0; idx
< ELEMENTSOF(exec_command_strings
); idx
++)
432 return exec_command_strings
[idx
];
437 ExecCommandFlags
exec_command_flags_from_string(const char *s
) {
440 idx
= string_table_lookup(exec_command_strings
, ELEMENTSOF(exec_command_strings
), s
);
443 return _EXEC_COMMAND_FLAGS_INVALID
;