2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
27 #include <sys/capability.h>
28 #include <sys/eventfd.h>
30 #include <sys/personality.h>
31 #include <sys/prctl.h>
32 #include <sys/socket.h>
39 #include <security/pam_appl.h>
43 #include <selinux/selinux.h>
51 #include <sys/apparmor.h>
54 #include "sd-messages.h"
57 #include "alloc-util.h"
59 #include "apparmor-util.h"
64 #include "capability-util.h"
67 #include "errno-list.h"
69 #include "exit-status.h"
72 #include "formats-util.h"
74 #include "glob-util.h"
81 #include "namespace.h"
82 #include "parse-util.h"
83 #include "path-util.h"
84 #include "process-util.h"
85 #include "rlimit-util.h"
88 #include "seccomp-util.h"
90 #include "securebits.h"
91 #include "selinux-util.h"
92 #include "signal-util.h"
93 #include "smack-util.h"
95 #include "string-table.h"
96 #include "string-util.h"
98 #include "syslog-util.h"
99 #include "terminal-util.h"
101 #include "user-util.h"
103 #include "utmp-wtmp.h"
105 #define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
106 #define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
108 /* This assumes there is a 'tty' group */
109 #define TTY_MODE 0620
111 #define SNDBUF_SIZE (8*1024*1024)
113 static int shift_fds(int fds
[], unsigned n_fds
) {
114 int start
, restart_from
;
119 /* Modifies the fds array! (sorts it) */
129 for (i
= start
; i
< (int) n_fds
; i
++) {
132 /* Already at right index? */
136 nfd
= fcntl(fds
[i
], F_DUPFD
, i
+ 3);
143 /* Hmm, the fd we wanted isn't free? Then
144 * let's remember that and try again from here */
145 if (nfd
!= i
+3 && restart_from
< 0)
149 if (restart_from
< 0)
152 start
= restart_from
;
158 static int flags_fds(const int fds
[], unsigned n_fds
, bool nonblock
) {
167 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
169 for (i
= 0; i
< n_fds
; i
++) {
171 r
= fd_nonblock(fds
[i
], nonblock
);
175 /* We unconditionally drop FD_CLOEXEC from the fds,
176 * since after all we want to pass these fds to our
179 r
= fd_cloexec(fds
[i
], false);
187 static const char *exec_context_tty_path(const ExecContext
*context
) {
190 if (context
->stdio_as_fds
)
193 if (context
->tty_path
)
194 return context
->tty_path
;
196 return "/dev/console";
199 static void exec_context_tty_reset(const ExecContext
*context
, const ExecParameters
*p
) {
204 path
= exec_context_tty_path(context
);
206 if (context
->tty_vhangup
) {
207 if (p
&& p
->stdin_fd
>= 0)
208 (void) terminal_vhangup_fd(p
->stdin_fd
);
210 (void) terminal_vhangup(path
);
213 if (context
->tty_reset
) {
214 if (p
&& p
->stdin_fd
>= 0)
215 (void) reset_terminal_fd(p
->stdin_fd
, true);
217 (void) reset_terminal(path
);
220 if (context
->tty_vt_disallocate
&& path
)
221 (void) vt_disallocate(path
);
224 static bool is_terminal_input(ExecInput i
) {
227 EXEC_INPUT_TTY_FORCE
,
228 EXEC_INPUT_TTY_FAIL
);
231 static bool is_terminal_output(ExecOutput o
) {
234 EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
235 EXEC_OUTPUT_KMSG_AND_CONSOLE
,
236 EXEC_OUTPUT_JOURNAL_AND_CONSOLE
);
239 static bool exec_context_needs_term(const ExecContext
*c
) {
242 /* Return true if the execution context suggests we should set $TERM to something useful. */
244 if (is_terminal_input(c
->std_input
))
247 if (is_terminal_output(c
->std_output
))
250 if (is_terminal_output(c
->std_error
))
253 return !!c
->tty_path
;
256 static int open_null_as(int flags
, int nfd
) {
261 fd
= open("/dev/null", flags
|O_NOCTTY
);
266 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
274 static int connect_journal_socket(int fd
, uid_t uid
, gid_t gid
) {
275 union sockaddr_union sa
= {
276 .un
.sun_family
= AF_UNIX
,
277 .un
.sun_path
= "/run/systemd/journal/stdout",
279 uid_t olduid
= UID_INVALID
;
280 gid_t oldgid
= GID_INVALID
;
283 if (gid
!= GID_INVALID
) {
291 if (uid
!= UID_INVALID
) {
301 r
= connect(fd
, &sa
.sa
, SOCKADDR_UN_LEN(sa
.un
));
305 /* If we fail to restore the uid or gid, things will likely
306 fail later on. This should only happen if an LSM interferes. */
308 if (uid
!= UID_INVALID
)
309 (void) seteuid(olduid
);
312 if (gid
!= GID_INVALID
)
313 (void) setegid(oldgid
);
318 static int connect_logger_as(
320 const ExecContext
*context
,
330 assert(output
< _EXEC_OUTPUT_MAX
);
334 fd
= socket(AF_UNIX
, SOCK_STREAM
, 0);
338 r
= connect_journal_socket(fd
, uid
, gid
);
342 if (shutdown(fd
, SHUT_RD
) < 0) {
347 (void) fd_inc_sndbuf(fd
, SNDBUF_SIZE
);
357 context
->syslog_identifier
? context
->syslog_identifier
: ident
,
359 context
->syslog_priority
,
360 !!context
->syslog_level_prefix
,
361 output
== EXEC_OUTPUT_SYSLOG
|| output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
,
362 output
== EXEC_OUTPUT_KMSG
|| output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
,
363 is_terminal_output(output
));
368 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
373 static int open_terminal_as(const char *path
, mode_t mode
, int nfd
) {
379 fd
= open_terminal(path
, mode
| O_NOCTTY
);
384 r
= dup2(fd
, nfd
) < 0 ? -errno
: nfd
;
392 static int fixup_input(ExecInput std_input
, int socket_fd
, bool apply_tty_stdin
) {
394 if (is_terminal_input(std_input
) && !apply_tty_stdin
)
395 return EXEC_INPUT_NULL
;
397 if (std_input
== EXEC_INPUT_SOCKET
&& socket_fd
< 0)
398 return EXEC_INPUT_NULL
;
403 static int fixup_output(ExecOutput std_output
, int socket_fd
) {
405 if (std_output
== EXEC_OUTPUT_SOCKET
&& socket_fd
< 0)
406 return EXEC_OUTPUT_INHERIT
;
411 static int setup_input(
412 const ExecContext
*context
,
413 const ExecParameters
*params
,
415 int named_iofds
[3]) {
422 if (params
->stdin_fd
>= 0) {
423 if (dup2(params
->stdin_fd
, STDIN_FILENO
) < 0)
426 /* Try to make this the controlling tty, if it is a tty, and reset it */
427 (void) ioctl(STDIN_FILENO
, TIOCSCTTY
, context
->std_input
== EXEC_INPUT_TTY_FORCE
);
428 (void) reset_terminal_fd(STDIN_FILENO
, true);
433 i
= fixup_input(context
->std_input
, socket_fd
, params
->flags
& EXEC_APPLY_TTY_STDIN
);
437 case EXEC_INPUT_NULL
:
438 return open_null_as(O_RDONLY
, STDIN_FILENO
);
441 case EXEC_INPUT_TTY_FORCE
:
442 case EXEC_INPUT_TTY_FAIL
: {
445 fd
= acquire_terminal(exec_context_tty_path(context
),
446 i
== EXEC_INPUT_TTY_FAIL
,
447 i
== EXEC_INPUT_TTY_FORCE
,
453 if (fd
!= STDIN_FILENO
) {
454 r
= dup2(fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
462 case EXEC_INPUT_SOCKET
:
463 return dup2(socket_fd
, STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
465 case EXEC_INPUT_NAMED_FD
:
466 (void) fd_nonblock(named_iofds
[STDIN_FILENO
], false);
467 return dup2(named_iofds
[STDIN_FILENO
], STDIN_FILENO
) < 0 ? -errno
: STDIN_FILENO
;
470 assert_not_reached("Unknown input type");
474 static int setup_output(
476 const ExecContext
*context
,
477 const ExecParameters
*params
,
484 dev_t
*journal_stream_dev
,
485 ino_t
*journal_stream_ino
) {
495 assert(journal_stream_dev
);
496 assert(journal_stream_ino
);
498 if (fileno
== STDOUT_FILENO
&& params
->stdout_fd
>= 0) {
500 if (dup2(params
->stdout_fd
, STDOUT_FILENO
) < 0)
503 return STDOUT_FILENO
;
506 if (fileno
== STDERR_FILENO
&& params
->stderr_fd
>= 0) {
507 if (dup2(params
->stderr_fd
, STDERR_FILENO
) < 0)
510 return STDERR_FILENO
;
513 i
= fixup_input(context
->std_input
, socket_fd
, params
->flags
& EXEC_APPLY_TTY_STDIN
);
514 o
= fixup_output(context
->std_output
, socket_fd
);
516 if (fileno
== STDERR_FILENO
) {
518 e
= fixup_output(context
->std_error
, socket_fd
);
520 /* This expects the input and output are already set up */
522 /* Don't change the stderr file descriptor if we inherit all
523 * the way and are not on a tty */
524 if (e
== EXEC_OUTPUT_INHERIT
&&
525 o
== EXEC_OUTPUT_INHERIT
&&
526 i
== EXEC_INPUT_NULL
&&
527 !is_terminal_input(context
->std_input
) &&
531 /* Duplicate from stdout if possible */
532 if ((e
== o
&& e
!= EXEC_OUTPUT_NAMED_FD
) || e
== EXEC_OUTPUT_INHERIT
)
533 return dup2(STDOUT_FILENO
, fileno
) < 0 ? -errno
: fileno
;
537 } else if (o
== EXEC_OUTPUT_INHERIT
) {
538 /* If input got downgraded, inherit the original value */
539 if (i
== EXEC_INPUT_NULL
&& is_terminal_input(context
->std_input
))
540 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
542 /* If the input is connected to anything that's not a /dev/null, inherit that... */
543 if (i
!= EXEC_INPUT_NULL
)
544 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
546 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
550 /* We need to open /dev/null here anew, to get the right access mode. */
551 return open_null_as(O_WRONLY
, fileno
);
556 case EXEC_OUTPUT_NULL
:
557 return open_null_as(O_WRONLY
, fileno
);
559 case EXEC_OUTPUT_TTY
:
560 if (is_terminal_input(i
))
561 return dup2(STDIN_FILENO
, fileno
) < 0 ? -errno
: fileno
;
563 /* We don't reset the terminal if this is just about output */
564 return open_terminal_as(exec_context_tty_path(context
), O_WRONLY
, fileno
);
566 case EXEC_OUTPUT_SYSLOG
:
567 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE
:
568 case EXEC_OUTPUT_KMSG
:
569 case EXEC_OUTPUT_KMSG_AND_CONSOLE
:
570 case EXEC_OUTPUT_JOURNAL
:
571 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE
:
572 r
= connect_logger_as(unit
, context
, o
, ident
, fileno
, uid
, gid
);
574 log_unit_error_errno(unit
, r
, "Failed to connect %s to the journal socket, ignoring: %m", fileno
== STDOUT_FILENO
? "stdout" : "stderr");
575 r
= open_null_as(O_WRONLY
, fileno
);
579 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
580 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
581 * services to detect whether they are connected to the journal or not. */
583 if (fstat(fileno
, &st
) >= 0) {
584 *journal_stream_dev
= st
.st_dev
;
585 *journal_stream_ino
= st
.st_ino
;
590 case EXEC_OUTPUT_SOCKET
:
591 assert(socket_fd
>= 0);
592 return dup2(socket_fd
, fileno
) < 0 ? -errno
: fileno
;
594 case EXEC_OUTPUT_NAMED_FD
:
595 (void) fd_nonblock(named_iofds
[fileno
], false);
596 return dup2(named_iofds
[fileno
], fileno
) < 0 ? -errno
: fileno
;
599 assert_not_reached("Unknown error type");
603 static int chown_terminal(int fd
, uid_t uid
) {
608 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
612 /* This might fail. What matters are the results. */
613 (void) fchown(fd
, uid
, -1);
614 (void) fchmod(fd
, TTY_MODE
);
616 if (fstat(fd
, &st
) < 0)
619 if (st
.st_uid
!= uid
|| (st
.st_mode
& 0777) != TTY_MODE
)
625 static int setup_confirm_stdio(int *_saved_stdin
, int *_saved_stdout
) {
626 _cleanup_close_
int fd
= -1, saved_stdin
= -1, saved_stdout
= -1;
629 assert(_saved_stdin
);
630 assert(_saved_stdout
);
632 saved_stdin
= fcntl(STDIN_FILENO
, F_DUPFD
, 3);
636 saved_stdout
= fcntl(STDOUT_FILENO
, F_DUPFD
, 3);
637 if (saved_stdout
< 0)
640 fd
= acquire_terminal(
645 DEFAULT_CONFIRM_USEC
);
649 r
= chown_terminal(fd
, getuid());
653 r
= reset_terminal_fd(fd
, true);
657 if (dup2(fd
, STDIN_FILENO
) < 0)
660 if (dup2(fd
, STDOUT_FILENO
) < 0)
667 *_saved_stdin
= saved_stdin
;
668 *_saved_stdout
= saved_stdout
;
670 saved_stdin
= saved_stdout
= -1;
675 _printf_(1, 2) static int write_confirm_message(const char *format
, ...) {
676 _cleanup_close_
int fd
= -1;
681 fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
685 va_start(ap
, format
);
686 vdprintf(fd
, format
, ap
);
692 static int restore_confirm_stdio(int *saved_stdin
, int *saved_stdout
) {
696 assert(saved_stdout
);
700 if (*saved_stdin
>= 0)
701 if (dup2(*saved_stdin
, STDIN_FILENO
) < 0)
704 if (*saved_stdout
>= 0)
705 if (dup2(*saved_stdout
, STDOUT_FILENO
) < 0)
708 *saved_stdin
= safe_close(*saved_stdin
);
709 *saved_stdout
= safe_close(*saved_stdout
);
714 static int ask_for_confirmation(char *response
, char **argv
) {
715 int saved_stdout
= -1, saved_stdin
= -1, r
;
716 _cleanup_free_
char *line
= NULL
;
718 r
= setup_confirm_stdio(&saved_stdin
, &saved_stdout
);
722 line
= exec_command_line(argv
);
726 r
= ask_char(response
, "yns", "Execute %s? [Yes, No, Skip] ", line
);
728 restore_confirm_stdio(&saved_stdin
, &saved_stdout
);
733 static int get_fixed_user(const ExecContext
*c
, const char **user
,
734 uid_t
*uid
, gid_t
*gid
,
735 const char **home
, const char **shell
) {
744 /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
745 * (i.e. are "/" or "/bin/nologin"). */
748 r
= get_user_creds_clean(&name
, uid
, gid
, home
, shell
);
756 static int get_fixed_group(const ExecContext
*c
, const char **group
, gid_t
*gid
) {
766 r
= get_group_creds(&name
, gid
);
774 static int get_fixed_supplementary_groups(const ExecContext
*c
,
778 gid_t
**supplementary_gids
, int *ngids
) {
782 bool keep_groups
= false;
783 gid_t
*groups
= NULL
;
784 _cleanup_free_ gid_t
*l_gids
= NULL
;
788 if (!c
->supplementary_groups
)
792 * If SupplementaryGroups= was passed then NGROUPS_MAX has to
793 * be positive, otherwise fail.
796 ngroups_max
= (int) sysconf(_SC_NGROUPS_MAX
);
797 if (ngroups_max
<= 0) {
801 return -EOPNOTSUPP
; /* For all other values */
805 * If user is given, then lookup GID and supplementary group list.
806 * We avoid NSS lookups for gid=0.
808 if (user
&& gid_is_valid(gid
) && gid
!= 0) {
809 /* First step, initialize groups from /etc/groups */
810 if (initgroups(user
, gid
) < 0)
816 l_gids
= new(gid_t
, ngroups_max
);
822 * Lookup the list of groups that the user belongs to, we
823 * avoid NSS lookups here too for gid=0.
826 if (getgrouplist(user
, gid
, l_gids
, &k
) < 0)
831 STRV_FOREACH(i
, c
->supplementary_groups
) {
834 if (k
>= ngroups_max
)
838 r
= get_group_creds(&g
, l_gids
+k
);
846 * Sets ngids to zero to drop all supplementary groups, happens
847 * when we are under root and SupplementaryGroups= is empty.
854 /* Otherwise get the final list of supplementary groups */
855 groups
= memdup(l_gids
, sizeof(gid_t
) * k
);
859 *supplementary_gids
= groups
;
867 static int enforce_groups(const ExecContext
*context
, gid_t gid
,
868 gid_t
*supplementary_gids
, int ngids
) {
873 /* Handle SupplementaryGroups= even if it is empty */
874 if (context
->supplementary_groups
) {
875 r
= maybe_setgroups(ngids
, supplementary_gids
);
880 if (gid_is_valid(gid
)) {
881 /* Then set our gids */
882 if (setresgid(gid
, gid
, gid
) < 0)
889 static int enforce_user(const ExecContext
*context
, uid_t uid
) {
892 if (!uid_is_valid(uid
))
895 /* Sets (but doesn't look up) the uid and make sure we keep the
896 * capabilities while doing so. */
898 if (context
->capability_ambient_set
!= 0) {
900 /* First step: If we need to keep capabilities but
901 * drop privileges we need to make sure we keep our
902 * caps, while we drop privileges. */
904 int sb
= context
->secure_bits
| 1<<SECURE_KEEP_CAPS
;
906 if (prctl(PR_GET_SECUREBITS
) != sb
)
907 if (prctl(PR_SET_SECUREBITS
, sb
) < 0)
912 /* Second step: actually set the uids */
913 if (setresuid(uid
, uid
, uid
) < 0)
916 /* At this point we should have all necessary capabilities but
917 are otherwise a normal user. However, the caps might got
918 corrupted due to the setresuid() so we need clean them up
919 later. This is done outside of this call. */
926 static int null_conv(
928 const struct pam_message
**msg
,
929 struct pam_response
**resp
,
932 /* We don't support conversations */
939 static int setup_pam(
946 int fds
[], unsigned n_fds
) {
950 static const struct pam_conv conv
= {
955 _cleanup_(barrier_destroy
) Barrier barrier
= BARRIER_NULL
;
956 pam_handle_t
*handle
= NULL
;
958 int pam_code
= PAM_SUCCESS
, r
;
959 char **nv
, **e
= NULL
;
960 bool close_session
= false;
961 pid_t pam_pid
= 0, parent_pid
;
968 /* We set up PAM in the parent process, then fork. The child
969 * will then stay around until killed via PR_GET_PDEATHSIG or
970 * systemd via the cgroup logic. It will then remove the PAM
971 * session again. The parent process will exec() the actual
972 * daemon. We do things this way to ensure that the main PID
973 * of the daemon is the one we initially fork()ed. */
975 r
= barrier_create(&barrier
);
979 if (log_get_max_level() < LOG_DEBUG
)
982 pam_code
= pam_start(name
, user
, &conv
, &handle
);
983 if (pam_code
!= PAM_SUCCESS
) {
989 pam_code
= pam_set_item(handle
, PAM_TTY
, tty
);
990 if (pam_code
!= PAM_SUCCESS
)
994 STRV_FOREACH(nv
, *env
) {
995 pam_code
= pam_putenv(handle
, *nv
);
996 if (pam_code
!= PAM_SUCCESS
)
1000 pam_code
= pam_acct_mgmt(handle
, flags
);
1001 if (pam_code
!= PAM_SUCCESS
)
1004 pam_code
= pam_open_session(handle
, flags
);
1005 if (pam_code
!= PAM_SUCCESS
)
1008 close_session
= true;
1010 e
= pam_getenvlist(handle
);
1012 pam_code
= PAM_BUF_ERR
;
1016 /* Block SIGTERM, so that we know that it won't get lost in
1019 assert_se(sigprocmask_many(SIG_BLOCK
, &old_ss
, SIGTERM
, -1) >= 0);
1021 parent_pid
= getpid();
1030 int sig
, ret
= EXIT_PAM
;
1032 /* The child's job is to reset the PAM session on
1034 barrier_set_role(&barrier
, BARRIER_CHILD
);
1036 /* This string must fit in 10 chars (i.e. the length
1037 * of "/sbin/init"), to look pretty in /bin/ps */
1038 rename_process("(sd-pam)");
1040 /* Make sure we don't keep open the passed fds in this
1041 child. We assume that otherwise only those fds are
1042 open here that have been opened by PAM. */
1043 close_many(fds
, n_fds
);
1045 /* Drop privileges - we don't need any to pam_close_session
1046 * and this will make PR_SET_PDEATHSIG work in most cases.
1047 * If this fails, ignore the error - but expect sd-pam threads
1048 * to fail to exit normally */
1050 r
= maybe_setgroups(0, NULL
);
1052 log_warning_errno(r
, "Failed to setgroups() in sd-pam: %m");
1053 if (setresgid(gid
, gid
, gid
) < 0)
1054 log_warning_errno(errno
, "Failed to setresgid() in sd-pam: %m");
1055 if (setresuid(uid
, uid
, uid
) < 0)
1056 log_warning_errno(errno
, "Failed to setresuid() in sd-pam: %m");
1058 (void) ignore_signals(SIGPIPE
, -1);
1060 /* Wait until our parent died. This will only work if
1061 * the above setresuid() succeeds, otherwise the kernel
1062 * will not allow unprivileged parents kill their privileged
1063 * children this way. We rely on the control groups kill logic
1064 * to do the rest for us. */
1065 if (prctl(PR_SET_PDEATHSIG
, SIGTERM
) < 0)
1068 /* Tell the parent that our setup is done. This is especially
1069 * important regarding dropping privileges. Otherwise, unit
1070 * setup might race against our setresuid(2) call. */
1071 barrier_place(&barrier
);
1073 /* Check if our parent process might already have
1075 if (getppid() == parent_pid
) {
1078 assert_se(sigemptyset(&ss
) >= 0);
1079 assert_se(sigaddset(&ss
, SIGTERM
) >= 0);
1082 if (sigwait(&ss
, &sig
) < 0) {
1089 assert(sig
== SIGTERM
);
1094 /* If our parent died we'll end the session */
1095 if (getppid() != parent_pid
) {
1096 pam_code
= pam_close_session(handle
, flags
);
1097 if (pam_code
!= PAM_SUCCESS
)
1104 pam_end(handle
, pam_code
| flags
);
1108 barrier_set_role(&barrier
, BARRIER_PARENT
);
1110 /* If the child was forked off successfully it will do all the
1111 * cleanups, so forget about the handle here. */
1114 /* Unblock SIGTERM again in the parent */
1115 assert_se(sigprocmask(SIG_SETMASK
, &old_ss
, NULL
) >= 0);
1117 /* We close the log explicitly here, since the PAM modules
1118 * might have opened it, but we don't want this fd around. */
1121 /* Synchronously wait for the child to initialize. We don't care for
1122 * errors as we cannot recover. However, warn loudly if it happens. */
1123 if (!barrier_place_and_sync(&barrier
))
1124 log_error("PAM initialization failed");
1132 if (pam_code
!= PAM_SUCCESS
) {
1133 log_error("PAM failed: %s", pam_strerror(handle
, pam_code
));
1134 r
= -EPERM
; /* PAM errors do not map to errno */
1136 log_error_errno(r
, "PAM failed: %m");
1140 pam_code
= pam_close_session(handle
, flags
);
1142 pam_end(handle
, pam_code
| flags
);
1154 static void rename_process_from_path(const char *path
) {
1155 char process_name
[11];
1159 /* This resulting string must fit in 10 chars (i.e. the length
1160 * of "/sbin/init") to look pretty in /bin/ps */
1164 rename_process("(...)");
1170 /* The end of the process name is usually more
1171 * interesting, since the first bit might just be
1177 process_name
[0] = '(';
1178 memcpy(process_name
+1, p
, l
);
1179 process_name
[1+l
] = ')';
1180 process_name
[1+l
+1] = 0;
1182 rename_process(process_name
);
1187 static bool skip_seccomp_unavailable(const Unit
* u
, const char* msg
) {
1189 if (is_seccomp_available())
1193 log_unit_debug(u
, "SECCOMP features not detected in the kernel, skipping %s", msg
);
1198 static int apply_seccomp(const Unit
* u
, const ExecContext
*c
) {
1199 uint32_t negative_action
, action
;
1200 scmp_filter_ctx seccomp
;
1207 if (skip_seccomp_unavailable(u
, "syscall filtering"))
1210 negative_action
= c
->syscall_errno
== 0 ? SCMP_ACT_KILL
: SCMP_ACT_ERRNO(c
->syscall_errno
);
1212 seccomp
= seccomp_init(c
->syscall_whitelist
? negative_action
: SCMP_ACT_ALLOW
);
1216 if (c
->syscall_archs
) {
1218 SET_FOREACH(id
, c
->syscall_archs
, i
) {
1219 r
= seccomp_arch_add(seccomp
, PTR_TO_UINT32(id
) - 1);
1227 r
= seccomp_add_secondary_archs(seccomp
);
1232 action
= c
->syscall_whitelist
? SCMP_ACT_ALLOW
: negative_action
;
1233 SET_FOREACH(id
, c
->syscall_filter
, i
) {
1234 r
= seccomp_rule_add(seccomp
, action
, PTR_TO_INT(id
) - 1, 0);
1239 r
= seccomp_attr_set(seccomp
, SCMP_FLTATR_CTL_NNP
, 0);
1243 r
= seccomp_load(seccomp
);
1246 seccomp_release(seccomp
);
1250 static int apply_address_families(const Unit
* u
, const ExecContext
*c
) {
1251 scmp_filter_ctx seccomp
;
1257 if (skip_seccomp_unavailable(u
, "RestrictAddressFamilies="))
1260 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1264 if (c
->address_families_whitelist
) {
1265 int af
, first
= 0, last
= 0;
1268 /* If this is a whitelist, we first block the address
1269 * families that are out of range and then everything
1270 * that is not in the set. First, we find the lowest
1271 * and highest address family in the set. */
1273 SET_FOREACH(afp
, c
->address_families
, i
) {
1274 af
= PTR_TO_INT(afp
);
1276 if (af
<= 0 || af
>= af_max())
1279 if (first
== 0 || af
< first
)
1282 if (last
== 0 || af
> last
)
1286 assert((first
== 0) == (last
== 0));
1290 /* No entries in the valid range, block everything */
1291 r
= seccomp_rule_add(
1293 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1301 /* Block everything below the first entry */
1302 r
= seccomp_rule_add(
1304 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1307 SCMP_A0(SCMP_CMP_LT
, first
));
1311 /* Block everything above the last entry */
1312 r
= seccomp_rule_add(
1314 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1317 SCMP_A0(SCMP_CMP_GT
, last
));
1321 /* Block everything between the first and last
1323 for (af
= 1; af
< af_max(); af
++) {
1325 if (set_contains(c
->address_families
, INT_TO_PTR(af
)))
1328 r
= seccomp_rule_add(
1330 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1333 SCMP_A0(SCMP_CMP_EQ
, af
));
1342 /* If this is a blacklist, then generate one rule for
1343 * each address family that are then combined in OR
1346 SET_FOREACH(af
, c
->address_families
, i
) {
1348 r
= seccomp_rule_add(
1350 SCMP_ACT_ERRNO(EPROTONOSUPPORT
),
1353 SCMP_A0(SCMP_CMP_EQ
, PTR_TO_INT(af
)));
1359 r
= seccomp_load(seccomp
);
1362 seccomp_release(seccomp
);
1366 static int apply_memory_deny_write_execute(const Unit
* u
, const ExecContext
*c
) {
1367 scmp_filter_ctx seccomp
;
1372 if (skip_seccomp_unavailable(u
, "MemoryDenyWriteExecute="))
1375 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1379 r
= seccomp_rule_add(
1381 SCMP_ACT_ERRNO(EPERM
),
1384 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
|PROT_WRITE
, PROT_EXEC
|PROT_WRITE
));
1388 r
= seccomp_rule_add(
1390 SCMP_ACT_ERRNO(EPERM
),
1393 SCMP_A2(SCMP_CMP_MASKED_EQ
, PROT_EXEC
, PROT_EXEC
));
1397 r
= seccomp_load(seccomp
);
1400 seccomp_release(seccomp
);
1404 static int apply_restrict_realtime(const Unit
* u
, const ExecContext
*c
) {
1405 static const int permitted_policies
[] = {
1411 scmp_filter_ctx seccomp
;
1413 int r
, p
, max_policy
= 0;
1417 if (skip_seccomp_unavailable(u
, "RestrictRealtime="))
1420 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1424 /* Determine the highest policy constant we want to allow */
1425 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1426 if (permitted_policies
[i
] > max_policy
)
1427 max_policy
= permitted_policies
[i
];
1429 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1431 for (p
= 0; p
< max_policy
; p
++) {
1434 /* Check if this is in the whitelist. */
1435 for (i
= 0; i
< ELEMENTSOF(permitted_policies
); i
++)
1436 if (permitted_policies
[i
] == p
) {
1444 /* Deny this policy */
1445 r
= seccomp_rule_add(
1447 SCMP_ACT_ERRNO(EPERM
),
1448 SCMP_SYS(sched_setscheduler
),
1450 SCMP_A1(SCMP_CMP_EQ
, p
));
1455 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1456 * hence no need no check for < 0 values. */
1457 r
= seccomp_rule_add(
1459 SCMP_ACT_ERRNO(EPERM
),
1460 SCMP_SYS(sched_setscheduler
),
1462 SCMP_A1(SCMP_CMP_GT
, max_policy
));
1466 r
= seccomp_load(seccomp
);
1469 seccomp_release(seccomp
);
1473 static int apply_protect_sysctl(Unit
*u
, const ExecContext
*c
) {
1474 scmp_filter_ctx seccomp
;
1479 /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
1480 * let's protect even those systems where this is left on in the kernel. */
1482 if (skip_seccomp_unavailable(u
, "ProtectKernelTunables="))
1485 r
= seccomp_init_conservative(&seccomp
, SCMP_ACT_ALLOW
);
1489 r
= seccomp_rule_add(
1491 SCMP_ACT_ERRNO(EPERM
),
1497 r
= seccomp_load(seccomp
);
1500 seccomp_release(seccomp
);
1504 static int apply_protect_kernel_modules(Unit
*u
, const ExecContext
*c
) {
1507 /* Turn off module syscalls on ProtectKernelModules=yes */
1509 if (skip_seccomp_unavailable(u
, "ProtectKernelModules="))
1512 return seccomp_load_filter_set(SCMP_ACT_ALLOW
, syscall_filter_sets
+ SYSCALL_FILTER_SET_MODULE
, SCMP_ACT_ERRNO(EPERM
));
1515 static int apply_private_devices(Unit
*u
, const ExecContext
*c
) {
1518 /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
1520 if (skip_seccomp_unavailable(u
, "PrivateDevices="))
1523 return seccomp_load_filter_set(SCMP_ACT_ALLOW
, syscall_filter_sets
+ SYSCALL_FILTER_SET_RAW_IO
, SCMP_ACT_ERRNO(EPERM
));
1528 static void do_idle_pipe_dance(int idle_pipe
[4]) {
1531 idle_pipe
[1] = safe_close(idle_pipe
[1]);
1532 idle_pipe
[2] = safe_close(idle_pipe
[2]);
1534 if (idle_pipe
[0] >= 0) {
1537 r
= fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT_USEC
);
1539 if (idle_pipe
[3] >= 0 && r
== 0 /* timeout */) {
1542 /* Signal systemd that we are bored and want to continue. */
1543 n
= write(idle_pipe
[3], "x", 1);
1545 /* Wait for systemd to react to the signal above. */
1546 fd_wait_for_event(idle_pipe
[0], POLLHUP
, IDLE_TIMEOUT2_USEC
);
1549 idle_pipe
[0] = safe_close(idle_pipe
[0]);
1553 idle_pipe
[3] = safe_close(idle_pipe
[3]);
1556 static int build_environment(
1558 const ExecContext
*c
,
1559 const ExecParameters
*p
,
1562 const char *username
,
1564 dev_t journal_stream_dev
,
1565 ino_t journal_stream_ino
,
1568 _cleanup_strv_free_
char **our_env
= NULL
;
1576 our_env
= new0(char*, 14);
1581 _cleanup_free_
char *joined
= NULL
;
1583 if (asprintf(&x
, "LISTEN_PID="PID_FMT
, getpid()) < 0)
1585 our_env
[n_env
++] = x
;
1587 if (asprintf(&x
, "LISTEN_FDS=%u", n_fds
) < 0)
1589 our_env
[n_env
++] = x
;
1591 joined
= strv_join(p
->fd_names
, ":");
1595 x
= strjoin("LISTEN_FDNAMES=", joined
, NULL
);
1598 our_env
[n_env
++] = x
;
1601 if ((p
->flags
& EXEC_SET_WATCHDOG
) && p
->watchdog_usec
> 0) {
1602 if (asprintf(&x
, "WATCHDOG_PID="PID_FMT
, getpid()) < 0)
1604 our_env
[n_env
++] = x
;
1606 if (asprintf(&x
, "WATCHDOG_USEC="USEC_FMT
, p
->watchdog_usec
) < 0)
1608 our_env
[n_env
++] = x
;
1611 /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use D-Bus look up dynamic
1612 * users via PID 1, possibly dead-locking the dbus daemon. This way it will not use D-Bus to resolve names, but
1613 * check the database directly. */
1614 if (unit_has_name(u
, SPECIAL_DBUS_SERVICE
)) {
1615 x
= strdup("SYSTEMD_NSS_BYPASS_BUS=1");
1618 our_env
[n_env
++] = x
;
1622 x
= strappend("HOME=", home
);
1625 our_env
[n_env
++] = x
;
1629 x
= strappend("LOGNAME=", username
);
1632 our_env
[n_env
++] = x
;
1634 x
= strappend("USER=", username
);
1637 our_env
[n_env
++] = x
;
1641 x
= strappend("SHELL=", shell
);
1644 our_env
[n_env
++] = x
;
1647 if (!sd_id128_is_null(u
->invocation_id
)) {
1648 if (asprintf(&x
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(u
->invocation_id
)) < 0)
1651 our_env
[n_env
++] = x
;
1654 if (exec_context_needs_term(c
)) {
1655 const char *tty_path
, *term
= NULL
;
1657 tty_path
= exec_context_tty_path(c
);
1659 /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try to inherit
1660 * the $TERM set for PID 1. This is useful for containers so that the $TERM the container manager
1661 * passes to PID 1 ends up all the way in the console login shown. */
1663 if (path_equal(tty_path
, "/dev/console") && getppid() == 1)
1664 term
= getenv("TERM");
1666 term
= default_term_for_tty(tty_path
);
1668 x
= strappend("TERM=", term
);
1671 our_env
[n_env
++] = x
;
1674 if (journal_stream_dev
!= 0 && journal_stream_ino
!= 0) {
1675 if (asprintf(&x
, "JOURNAL_STREAM=" DEV_FMT
":" INO_FMT
, journal_stream_dev
, journal_stream_ino
) < 0)
1678 our_env
[n_env
++] = x
;
1681 our_env
[n_env
++] = NULL
;
1682 assert(n_env
<= 12);
1690 static int build_pass_environment(const ExecContext
*c
, char ***ret
) {
1691 _cleanup_strv_free_
char **pass_env
= NULL
;
1692 size_t n_env
= 0, n_bufsize
= 0;
1695 STRV_FOREACH(i
, c
->pass_environment
) {
1696 _cleanup_free_
char *x
= NULL
;
1702 x
= strjoin(*i
, "=", v
, NULL
);
1705 if (!GREEDY_REALLOC(pass_env
, n_bufsize
, n_env
+ 2))
1707 pass_env
[n_env
++] = x
;
1708 pass_env
[n_env
] = NULL
;
1718 static bool exec_needs_mount_namespace(
1719 const ExecContext
*context
,
1720 const ExecParameters
*params
,
1721 ExecRuntime
*runtime
) {
1726 if (!strv_isempty(context
->read_write_paths
) ||
1727 !strv_isempty(context
->read_only_paths
) ||
1728 !strv_isempty(context
->inaccessible_paths
))
1731 if (context
->mount_flags
!= 0)
1734 if (context
->private_tmp
&& runtime
&& (runtime
->tmp_dir
|| runtime
->var_tmp_dir
))
1737 if (context
->private_devices
||
1738 context
->protect_system
!= PROTECT_SYSTEM_NO
||
1739 context
->protect_home
!= PROTECT_HOME_NO
||
1740 context
->protect_kernel_tunables
||
1741 context
->protect_kernel_modules
||
1742 context
->protect_control_groups
)
1748 static int setup_private_users(uid_t uid
, gid_t gid
) {
1749 _cleanup_free_
char *uid_map
= NULL
, *gid_map
= NULL
;
1750 _cleanup_close_pair_
int errno_pipe
[2] = { -1, -1 };
1751 _cleanup_close_
int unshare_ready_fd
= -1;
1752 _cleanup_(sigkill_waitp
) pid_t pid
= 0;
1758 /* Set up a user namespace and map root to root, the selected UID/GID to itself, and everything else to
1759 * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
1760 * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
1761 * which waits for the parent to create the new user namespace while staying in the original namespace. The
1762 * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
1763 * continues execution normally. */
1765 if (uid
!= 0 && uid_is_valid(uid
))
1767 "0 0 1\n" /* Map root → root */
1768 UID_FMT
" " UID_FMT
" 1\n", /* Map $UID → $UID */
1771 uid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1775 if (gid
!= 0 && gid_is_valid(gid
))
1777 "0 0 1\n" /* Map root → root */
1778 GID_FMT
" " GID_FMT
" 1\n", /* Map $GID → $GID */
1781 gid_map
= strdup("0 0 1\n"); /* The case where the above is the same */
1785 /* Create a communication channel so that the parent can tell the child when it finished creating the user
1787 unshare_ready_fd
= eventfd(0, EFD_CLOEXEC
);
1788 if (unshare_ready_fd
< 0)
1791 /* Create a communication channel so that the child can tell the parent a proper error code in case it
1793 if (pipe2(errno_pipe
, O_CLOEXEC
) < 0)
1801 _cleanup_close_
int fd
= -1;
1805 /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
1806 * here, after the parent opened its own user namespace. */
1809 errno_pipe
[0] = safe_close(errno_pipe
[0]);
1811 /* Wait until the parent unshared the user namespace */
1812 if (read(unshare_ready_fd
, &c
, sizeof(c
)) < 0) {
1817 /* Disable the setgroups() system call in the child user namespace, for good. */
1818 a
= procfs_file_alloca(ppid
, "setgroups");
1819 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1821 if (errno
!= ENOENT
) {
1826 /* If the file is missing the kernel is too old, let's continue anyway. */
1828 if (write(fd
, "deny\n", 5) < 0) {
1833 fd
= safe_close(fd
);
1836 /* First write the GID map */
1837 a
= procfs_file_alloca(ppid
, "gid_map");
1838 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1843 if (write(fd
, gid_map
, strlen(gid_map
)) < 0) {
1847 fd
= safe_close(fd
);
1849 /* The write the UID map */
1850 a
= procfs_file_alloca(ppid
, "uid_map");
1851 fd
= open(a
, O_WRONLY
|O_CLOEXEC
);
1856 if (write(fd
, uid_map
, strlen(uid_map
)) < 0) {
1861 _exit(EXIT_SUCCESS
);
1864 (void) write(errno_pipe
[1], &r
, sizeof(r
));
1865 _exit(EXIT_FAILURE
);
1868 errno_pipe
[1] = safe_close(errno_pipe
[1]);
1870 if (unshare(CLONE_NEWUSER
) < 0)
1873 /* Let the child know that the namespace is ready now */
1874 if (write(unshare_ready_fd
, &c
, sizeof(c
)) < 0)
1877 /* Try to read an error code from the child */
1878 n
= read(errno_pipe
[0], &r
, sizeof(r
));
1881 if (n
== sizeof(r
)) { /* an error code was sent to us */
1886 if (n
!= 0) /* on success we should have read 0 bytes */
1889 r
= wait_for_terminate(pid
, &si
);
1894 /* If something strange happened with the child, let's consider this fatal, too */
1895 if (si
.si_code
!= CLD_EXITED
|| si
.si_status
!= 0)
1901 static int setup_runtime_directory(
1902 const ExecContext
*context
,
1903 const ExecParameters
*params
,
1913 STRV_FOREACH(rt
, context
->runtime_directory
) {
1914 _cleanup_free_
char *p
;
1916 p
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
1920 r
= mkdir_p_label(p
, context
->runtime_directory_mode
);
1924 r
= chmod_and_chown(p
, context
->runtime_directory_mode
, uid
, gid
);
1932 static int setup_smack(
1933 const ExecContext
*context
,
1934 const ExecCommand
*command
) {
1942 if (!mac_smack_use())
1945 if (context
->smack_process_label
) {
1946 r
= mac_smack_apply_pid(0, context
->smack_process_label
);
1950 #ifdef SMACK_DEFAULT_PROCESS_LABEL
1952 _cleanup_free_
char *exec_label
= NULL
;
1954 r
= mac_smack_read(command
->path
, SMACK_ATTR_EXEC
, &exec_label
);
1955 if (r
< 0 && r
!= -ENODATA
&& r
!= -EOPNOTSUPP
)
1958 r
= mac_smack_apply_pid(0, exec_label
? : SMACK_DEFAULT_PROCESS_LABEL
);
1968 static int compile_read_write_paths(
1969 const ExecContext
*context
,
1970 const ExecParameters
*params
,
1973 _cleanup_strv_free_
char **l
= NULL
;
1976 /* Compile the list of writable paths. This is the combination of the explicitly configured paths, plus all
1977 * runtime directories. */
1979 if (strv_isempty(context
->read_write_paths
) &&
1980 strv_isempty(context
->runtime_directory
)) {
1981 *ret
= NULL
; /* NOP if neither is set */
1985 l
= strv_copy(context
->read_write_paths
);
1989 STRV_FOREACH(rt
, context
->runtime_directory
) {
1992 s
= strjoin(params
->runtime_prefix
, "/", *rt
, NULL
);
1996 if (strv_consume(&l
, s
) < 0)
2006 static int apply_mount_namespace(Unit
*u
, const ExecContext
*context
,
2007 const ExecParameters
*params
,
2008 ExecRuntime
*runtime
) {
2010 _cleanup_free_
char **rw
= NULL
;
2011 char *tmp
= NULL
, *var
= NULL
;
2012 const char *root_dir
= NULL
;
2013 NameSpaceInfo ns_info
= {
2014 .private_dev
= context
->private_devices
,
2015 .protect_control_groups
= context
->protect_control_groups
,
2016 .protect_kernel_tunables
= context
->protect_kernel_tunables
,
2017 .protect_kernel_modules
= context
->protect_kernel_modules
,
2020 /* The runtime struct only contains the parent of the private /tmp,
2021 * which is non-accessible to world users. Inside of it there's a /tmp
2022 * that is sticky, and that's the one we want to use here. */
2024 if (context
->private_tmp
&& runtime
) {
2025 if (runtime
->tmp_dir
)
2026 tmp
= strjoina(runtime
->tmp_dir
, "/tmp");
2027 if (runtime
->var_tmp_dir
)
2028 var
= strjoina(runtime
->var_tmp_dir
, "/tmp");
2031 r
= compile_read_write_paths(context
, params
, &rw
);
2035 if (params
->flags
& EXEC_APPLY_CHROOT
)
2036 root_dir
= context
->root_directory
;
2038 r
= setup_namespace(root_dir
, &ns_info
, rw
,
2039 context
->read_only_paths
,
2040 context
->inaccessible_paths
,
2043 context
->protect_home
,
2044 context
->protect_system
,
2045 context
->mount_flags
);
2047 /* If we couldn't set up the namespace this is probably due to a
2048 * missing capability. In this case, silently proceeed. */
2049 if (IN_SET(r
, -EPERM
, -EACCES
)) {
2051 log_unit_debug_errno(u
, r
, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
2059 static int apply_working_directory(const ExecContext
*context
,
2060 const ExecParameters
*params
,
2061 const char *working_directory
,
2062 const bool needs_mount_ns
) {
2064 if (params
->flags
& EXEC_APPLY_CHROOT
) {
2065 if (!needs_mount_ns
&& context
->root_directory
)
2066 if (chroot(context
->root_directory
) < 0)
2069 if (chdir(working_directory
) < 0 &&
2070 !context
->working_directory_missing_ok
)
2076 d
= strjoina(strempty(context
->root_directory
), "/",
2077 strempty(working_directory
));
2079 !context
->working_directory_missing_ok
)
2086 static void append_socket_pair(int *array
, unsigned *n
, int pair
[2]) {
2094 array
[(*n
)++] = pair
[0];
2096 array
[(*n
)++] = pair
[1];
2099 static int close_remaining_fds(
2100 const ExecParameters
*params
,
2101 ExecRuntime
*runtime
,
2102 DynamicCreds
*dcreds
,
2105 int *fds
, unsigned n_fds
) {
2107 unsigned n_dont_close
= 0;
2108 int dont_close
[n_fds
+ 12];
2112 if (params
->stdin_fd
>= 0)
2113 dont_close
[n_dont_close
++] = params
->stdin_fd
;
2114 if (params
->stdout_fd
>= 0)
2115 dont_close
[n_dont_close
++] = params
->stdout_fd
;
2116 if (params
->stderr_fd
>= 0)
2117 dont_close
[n_dont_close
++] = params
->stderr_fd
;
2120 dont_close
[n_dont_close
++] = socket_fd
;
2122 memcpy(dont_close
+ n_dont_close
, fds
, sizeof(int) * n_fds
);
2123 n_dont_close
+= n_fds
;
2127 append_socket_pair(dont_close
, &n_dont_close
, runtime
->netns_storage_socket
);
2131 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->user
->storage_socket
);
2133 append_socket_pair(dont_close
, &n_dont_close
, dcreds
->group
->storage_socket
);
2136 if (user_lookup_fd
>= 0)
2137 dont_close
[n_dont_close
++] = user_lookup_fd
;
2139 return close_all_fds(dont_close
, n_dont_close
);
2142 static bool context_has_address_families(const ExecContext
*c
) {
2145 return c
->address_families_whitelist
||
2146 !set_isempty(c
->address_families
);
2149 static bool context_has_syscall_filters(const ExecContext
*c
) {
2152 return c
->syscall_whitelist
||
2153 !set_isempty(c
->syscall_filter
) ||
2154 !set_isempty(c
->syscall_archs
);
2157 static bool context_has_no_new_privileges(const ExecContext
*c
) {
2160 if (c
->no_new_privileges
)
2163 if (have_effective_cap(CAP_SYS_ADMIN
)) /* if we are privileged, we don't need NNP */
2166 return context_has_address_families(c
) || /* we need NNP if we have any form of seccomp and are unprivileged */
2167 c
->memory_deny_write_execute
||
2168 c
->restrict_realtime
||
2169 c
->protect_kernel_tunables
||
2170 c
->protect_kernel_modules
||
2171 c
->private_devices
||
2172 context_has_syscall_filters(c
);
2175 static int send_user_lookup(
2183 /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
2184 * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
2187 if (user_lookup_fd
< 0)
2190 if (!uid_is_valid(uid
) && !gid_is_valid(gid
))
2193 if (writev(user_lookup_fd
,
2195 { .iov_base
= &uid
, .iov_len
= sizeof(uid
) },
2196 { .iov_base
= &gid
, .iov_len
= sizeof(gid
) },
2197 { .iov_base
= unit
->id
, .iov_len
= strlen(unit
->id
) }}, 3) < 0)
2203 static int exec_child(
2205 ExecCommand
*command
,
2206 const ExecContext
*context
,
2207 const ExecParameters
*params
,
2208 ExecRuntime
*runtime
,
2209 DynamicCreds
*dcreds
,
2213 int *fds
, unsigned n_fds
,
2218 _cleanup_strv_free_
char **our_env
= NULL
, **pass_env
= NULL
, **accum_env
= NULL
, **final_argv
= NULL
;
2219 _cleanup_free_
char *mac_selinux_context_net
= NULL
;
2220 _cleanup_free_ gid_t
*supplementary_gids
= NULL
;
2221 const char *username
= NULL
, *groupname
= NULL
;
2222 const char *home
= NULL
, *shell
= NULL
, *wd
;
2223 dev_t journal_stream_dev
= 0;
2224 ino_t journal_stream_ino
= 0;
2225 bool needs_mount_namespace
;
2226 uid_t uid
= UID_INVALID
;
2227 gid_t gid
= GID_INVALID
;
2228 int i
, r
, ngids
= 0;
2234 assert(exit_status
);
2236 rename_process_from_path(command
->path
);
2238 /* We reset exactly these signals, since they are the
2239 * only ones we set to SIG_IGN in the main daemon. All
2240 * others we leave untouched because we set them to
2241 * SIG_DFL or a valid handler initially, both of which
2242 * will be demoted to SIG_DFL. */
2243 (void) default_signals(SIGNALS_CRASH_HANDLER
,
2244 SIGNALS_IGNORE
, -1);
2246 if (context
->ignore_sigpipe
)
2247 (void) ignore_signals(SIGPIPE
, -1);
2249 r
= reset_signal_mask();
2251 *exit_status
= EXIT_SIGNAL_MASK
;
2255 if (params
->idle_pipe
)
2256 do_idle_pipe_dance(params
->idle_pipe
);
2258 /* Close sockets very early to make sure we don't
2259 * block init reexecution because it cannot bind its
2264 r
= close_remaining_fds(params
, runtime
, dcreds
, user_lookup_fd
, socket_fd
, fds
, n_fds
);
2266 *exit_status
= EXIT_FDS
;
2270 if (!context
->same_pgrp
)
2272 *exit_status
= EXIT_SETSID
;
2276 exec_context_tty_reset(context
, params
);
2278 if (params
->flags
& EXEC_CONFIRM_SPAWN
) {
2281 r
= ask_for_confirmation(&response
, argv
);
2282 if (r
== -ETIMEDOUT
)
2283 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
2285 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r
));
2286 else if (response
== 's') {
2287 write_confirm_message("Skipping execution.\n");
2288 *exit_status
= EXIT_CONFIRM
;
2290 } else if (response
== 'n') {
2291 write_confirm_message("Failing execution.\n");
2297 if (context
->dynamic_user
&& dcreds
) {
2299 /* Make sure we bypass our own NSS module for any NSS checks */
2300 if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
2301 *exit_status
= EXIT_USER
;
2305 r
= dynamic_creds_realize(dcreds
, &uid
, &gid
);
2307 *exit_status
= EXIT_USER
;
2311 if (!uid_is_valid(uid
) || !gid_is_valid(gid
)) {
2312 *exit_status
= EXIT_USER
;
2317 username
= dcreds
->user
->name
;
2320 r
= get_fixed_user(context
, &username
, &uid
, &gid
, &home
, &shell
);
2322 *exit_status
= EXIT_USER
;
2326 r
= get_fixed_group(context
, &groupname
, &gid
);
2328 *exit_status
= EXIT_GROUP
;
2332 r
= get_fixed_supplementary_groups(context
, username
, groupname
,
2333 gid
, &supplementary_gids
, &ngids
);
2335 *exit_status
= EXIT_GROUP
;
2340 r
= send_user_lookup(unit
, user_lookup_fd
, uid
, gid
);
2342 *exit_status
= EXIT_USER
;
2346 user_lookup_fd
= safe_close(user_lookup_fd
);
2348 /* If a socket is connected to STDIN/STDOUT/STDERR, we
2349 * must sure to drop O_NONBLOCK */
2351 (void) fd_nonblock(socket_fd
, false);
2353 r
= setup_input(context
, params
, socket_fd
, named_iofds
);
2355 *exit_status
= EXIT_STDIN
;
2359 r
= setup_output(unit
, context
, params
, STDOUT_FILENO
, socket_fd
, named_iofds
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2361 *exit_status
= EXIT_STDOUT
;
2365 r
= setup_output(unit
, context
, params
, STDERR_FILENO
, socket_fd
, named_iofds
, basename(command
->path
), uid
, gid
, &journal_stream_dev
, &journal_stream_ino
);
2367 *exit_status
= EXIT_STDERR
;
2371 if (params
->cgroup_path
) {
2372 r
= cg_attach_everywhere(params
->cgroup_supported
, params
->cgroup_path
, 0, NULL
, NULL
);
2374 *exit_status
= EXIT_CGROUP
;
2379 if (context
->oom_score_adjust_set
) {
2380 char t
[DECIMAL_STR_MAX(context
->oom_score_adjust
)];
2382 /* When we can't make this change due to EPERM, then
2383 * let's silently skip over it. User namespaces
2384 * prohibit write access to this file, and we
2385 * shouldn't trip up over that. */
2387 sprintf(t
, "%i", context
->oom_score_adjust
);
2388 r
= write_string_file("/proc/self/oom_score_adj", t
, 0);
2389 if (r
== -EPERM
|| r
== -EACCES
) {
2391 log_unit_debug_errno(unit
, r
, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
2394 *exit_status
= EXIT_OOM_ADJUST
;
2399 if (context
->nice_set
)
2400 if (setpriority(PRIO_PROCESS
, 0, context
->nice
) < 0) {
2401 *exit_status
= EXIT_NICE
;
2405 if (context
->cpu_sched_set
) {
2406 struct sched_param param
= {
2407 .sched_priority
= context
->cpu_sched_priority
,
2410 r
= sched_setscheduler(0,
2411 context
->cpu_sched_policy
|
2412 (context
->cpu_sched_reset_on_fork
?
2413 SCHED_RESET_ON_FORK
: 0),
2416 *exit_status
= EXIT_SETSCHEDULER
;
2421 if (context
->cpuset
)
2422 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context
->cpuset_ncpus
), context
->cpuset
) < 0) {
2423 *exit_status
= EXIT_CPUAFFINITY
;
2427 if (context
->ioprio_set
)
2428 if (ioprio_set(IOPRIO_WHO_PROCESS
, 0, context
->ioprio
) < 0) {
2429 *exit_status
= EXIT_IOPRIO
;
2433 if (context
->timer_slack_nsec
!= NSEC_INFINITY
)
2434 if (prctl(PR_SET_TIMERSLACK
, context
->timer_slack_nsec
) < 0) {
2435 *exit_status
= EXIT_TIMERSLACK
;
2439 if (context
->personality
!= PERSONALITY_INVALID
)
2440 if (personality(context
->personality
) < 0) {
2441 *exit_status
= EXIT_PERSONALITY
;
2445 if (context
->utmp_id
)
2446 utmp_put_init_process(context
->utmp_id
, getpid(), getsid(0), context
->tty_path
,
2447 context
->utmp_mode
== EXEC_UTMP_INIT
? INIT_PROCESS
:
2448 context
->utmp_mode
== EXEC_UTMP_LOGIN
? LOGIN_PROCESS
:
2450 username
? "root" : context
->user
);
2452 if (context
->user
) {
2453 r
= chown_terminal(STDIN_FILENO
, uid
);
2455 *exit_status
= EXIT_STDIN
;
2460 /* If delegation is enabled we'll pass ownership of the cgroup
2461 * (but only in systemd's own controller hierarchy!) to the
2462 * user of the new process. */
2463 if (params
->cgroup_path
&& context
->user
&& params
->cgroup_delegate
) {
2464 r
= cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0644, uid
, gid
);
2466 *exit_status
= EXIT_CGROUP
;
2471 r
= cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, 0755, uid
, gid
);
2473 *exit_status
= EXIT_CGROUP
;
2478 if (!strv_isempty(context
->runtime_directory
) && params
->runtime_prefix
) {
2479 r
= setup_runtime_directory(context
, params
, uid
, gid
);
2481 *exit_status
= EXIT_RUNTIME_DIRECTORY
;
2486 r
= build_environment(
2498 *exit_status
= EXIT_MEMORY
;
2502 r
= build_pass_environment(context
, &pass_env
);
2504 *exit_status
= EXIT_MEMORY
;
2508 accum_env
= strv_env_merge(5,
2509 params
->environment
,
2512 context
->environment
,
2516 *exit_status
= EXIT_MEMORY
;
2519 accum_env
= strv_env_clean(accum_env
);
2521 (void) umask(context
->umask
);
2523 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2524 r
= setup_smack(context
, command
);
2526 *exit_status
= EXIT_SMACK_PROCESS_LABEL
;
2530 if (context
->pam_name
&& username
) {
2531 r
= setup_pam(context
->pam_name
, username
, uid
, gid
, context
->tty_path
, &accum_env
, fds
, n_fds
);
2533 *exit_status
= EXIT_PAM
;
2539 if (context
->private_network
&& runtime
&& runtime
->netns_storage_socket
[0] >= 0) {
2540 r
= setup_netns(runtime
->netns_storage_socket
);
2542 *exit_status
= EXIT_NETWORK
;
2547 needs_mount_namespace
= exec_needs_mount_namespace(context
, params
, runtime
);
2548 if (needs_mount_namespace
) {
2549 r
= apply_mount_namespace(unit
, context
, params
, runtime
);
2551 *exit_status
= EXIT_NAMESPACE
;
2556 if (context
->working_directory_home
)
2558 else if (context
->working_directory
)
2559 wd
= context
->working_directory
;
2563 /* Drop group as early as possbile */
2564 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2565 r
= enforce_groups(context
, gid
, supplementary_gids
, ngids
);
2567 *exit_status
= EXIT_GROUP
;
2572 r
= apply_working_directory(context
, params
, wd
, needs_mount_namespace
);
2574 *exit_status
= EXIT_CHROOT
;
2579 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) &&
2580 mac_selinux_use() &&
2581 params
->selinux_context_net
&&
2583 !command
->privileged
) {
2585 r
= mac_selinux_get_child_mls_label(socket_fd
, command
->path
, context
->selinux_context
, &mac_selinux_context_net
);
2587 *exit_status
= EXIT_SELINUX_CONTEXT
;
2593 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && context
->private_users
) {
2594 r
= setup_private_users(uid
, gid
);
2596 *exit_status
= EXIT_USER
;
2601 /* We repeat the fd closing here, to make sure that
2602 * nothing is leaked from the PAM modules. Note that
2603 * we are more aggressive this time since socket_fd
2604 * and the netns fds we don't need anymore. The custom
2605 * endpoint fd was needed to upload the policy and can
2606 * now be closed as well. */
2607 r
= close_all_fds(fds
, n_fds
);
2609 r
= shift_fds(fds
, n_fds
);
2611 r
= flags_fds(fds
, n_fds
, context
->non_blocking
);
2613 *exit_status
= EXIT_FDS
;
2617 if ((params
->flags
& EXEC_APPLY_PERMISSIONS
) && !command
->privileged
) {
2619 int secure_bits
= context
->secure_bits
;
2621 for (i
= 0; i
< _RLIMIT_MAX
; i
++) {
2623 if (!context
->rlimit
[i
])
2626 r
= setrlimit_closest(i
, context
->rlimit
[i
]);
2628 *exit_status
= EXIT_LIMITS
;
2633 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2634 if (context
->restrict_realtime
&& !context
->rlimit
[RLIMIT_RTPRIO
]) {
2635 if (setrlimit(RLIMIT_RTPRIO
, &RLIMIT_MAKE_CONST(0)) < 0) {
2636 *exit_status
= EXIT_LIMITS
;
2641 if (!cap_test_all(context
->capability_bounding_set
)) {
2642 r
= capability_bounding_set_drop(context
->capability_bounding_set
, false);
2644 *exit_status
= EXIT_CAPABILITIES
;
2649 /* This is done before enforce_user, but ambient set
2650 * does not survive over setresuid() if keep_caps is not set. */
2651 if (context
->capability_ambient_set
!= 0) {
2652 r
= capability_ambient_set_apply(context
->capability_ambient_set
, true);
2654 *exit_status
= EXIT_CAPABILITIES
;
2659 if (context
->user
) {
2660 r
= enforce_user(context
, uid
);
2662 *exit_status
= EXIT_USER
;
2665 if (context
->capability_ambient_set
!= 0) {
2667 /* Fix the ambient capabilities after user change. */
2668 r
= capability_ambient_set_apply(context
->capability_ambient_set
, false);
2670 *exit_status
= EXIT_CAPABILITIES
;
2674 /* If we were asked to change user and ambient capabilities
2675 * were requested, we had to add keep-caps to the securebits
2676 * so that we would maintain the inherited capability set
2677 * through the setresuid(). Make sure that the bit is added
2678 * also to the context secure_bits so that we don't try to
2679 * drop the bit away next. */
2681 secure_bits
|= 1<<SECURE_KEEP_CAPS
;
2685 /* PR_GET_SECUREBITS is not privileged, while
2686 * PR_SET_SECUREBITS is. So to suppress
2687 * potential EPERMs we'll try not to call
2688 * PR_SET_SECUREBITS unless necessary. */
2689 if (prctl(PR_GET_SECUREBITS
) != secure_bits
)
2690 if (prctl(PR_SET_SECUREBITS
, secure_bits
) < 0) {
2691 *exit_status
= EXIT_SECUREBITS
;
2695 if (context_has_no_new_privileges(context
))
2696 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2697 *exit_status
= EXIT_NO_NEW_PRIVILEGES
;
2702 if (context_has_address_families(context
)) {
2703 r
= apply_address_families(unit
, context
);
2705 *exit_status
= EXIT_ADDRESS_FAMILIES
;
2710 if (context
->memory_deny_write_execute
) {
2711 r
= apply_memory_deny_write_execute(unit
, context
);
2713 *exit_status
= EXIT_SECCOMP
;
2718 if (context
->restrict_realtime
) {
2719 r
= apply_restrict_realtime(unit
, context
);
2721 *exit_status
= EXIT_SECCOMP
;
2726 if (context
->protect_kernel_tunables
) {
2727 r
= apply_protect_sysctl(unit
, context
);
2729 *exit_status
= EXIT_SECCOMP
;
2734 if (context
->protect_kernel_modules
) {
2735 r
= apply_protect_kernel_modules(unit
, context
);
2737 *exit_status
= EXIT_SECCOMP
;
2742 if (context
->private_devices
) {
2743 r
= apply_private_devices(unit
, context
);
2745 *exit_status
= EXIT_SECCOMP
;
2750 if (context_has_syscall_filters(context
)) {
2751 r
= apply_seccomp(unit
, context
);
2753 *exit_status
= EXIT_SECCOMP
;
2760 if (mac_selinux_use()) {
2761 char *exec_context
= mac_selinux_context_net
?: context
->selinux_context
;
2764 r
= setexeccon(exec_context
);
2766 *exit_status
= EXIT_SELINUX_CONTEXT
;
2773 #ifdef HAVE_APPARMOR
2774 if (context
->apparmor_profile
&& mac_apparmor_use()) {
2775 r
= aa_change_onexec(context
->apparmor_profile
);
2776 if (r
< 0 && !context
->apparmor_profile_ignore
) {
2777 *exit_status
= EXIT_APPARMOR_PROFILE
;
2784 final_argv
= replace_env_argv(argv
, accum_env
);
2786 *exit_status
= EXIT_MEMORY
;
2790 if (_unlikely_(log_get_max_level() >= LOG_DEBUG
)) {
2791 _cleanup_free_
char *line
;
2793 line
= exec_command_line(final_argv
);
2796 log_struct(LOG_DEBUG
,
2798 "EXECUTABLE=%s", command
->path
,
2799 LOG_UNIT_MESSAGE(unit
, "Executing: %s", line
),
2805 execve(command
->path
, final_argv
, accum_env
);
2806 *exit_status
= EXIT_EXEC
;
2810 int exec_spawn(Unit
*unit
,
2811 ExecCommand
*command
,
2812 const ExecContext
*context
,
2813 const ExecParameters
*params
,
2814 ExecRuntime
*runtime
,
2815 DynamicCreds
*dcreds
,
2818 _cleanup_strv_free_
char **files_env
= NULL
;
2819 int *fds
= NULL
; unsigned n_fds
= 0;
2820 _cleanup_free_
char *line
= NULL
;
2822 int named_iofds
[3] = { -1, -1, -1 };
2831 assert(params
->fds
|| params
->n_fds
<= 0);
2833 if (context
->std_input
== EXEC_INPUT_SOCKET
||
2834 context
->std_output
== EXEC_OUTPUT_SOCKET
||
2835 context
->std_error
== EXEC_OUTPUT_SOCKET
) {
2837 if (params
->n_fds
!= 1) {
2838 log_unit_error(unit
, "Got more than one socket.");
2842 socket_fd
= params
->fds
[0];
2846 n_fds
= params
->n_fds
;
2849 r
= exec_context_named_iofds(unit
, context
, params
, named_iofds
);
2851 return log_unit_error_errno(unit
, r
, "Failed to load a named file descriptor: %m");
2853 r
= exec_context_load_environment(unit
, context
, &files_env
);
2855 return log_unit_error_errno(unit
, r
, "Failed to load environment files: %m");
2857 argv
= params
->argv
?: command
->argv
;
2858 line
= exec_command_line(argv
);
2862 log_struct(LOG_DEBUG
,
2864 LOG_UNIT_MESSAGE(unit
, "About to execute: %s", line
),
2865 "EXECUTABLE=%s", command
->path
,
2869 return log_unit_error_errno(unit
, errno
, "Failed to fork: %m");
2874 r
= exec_child(unit
,
2885 unit
->manager
->user_lookup_fds
[1],
2889 log_struct_errno(LOG_ERR
, r
,
2890 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED
),
2892 LOG_UNIT_MESSAGE(unit
, "Failed at step %s spawning %s: %m",
2893 exit_status_to_string(exit_status
, EXIT_STATUS_SYSTEMD
),
2895 "EXECUTABLE=%s", command
->path
,
2902 log_unit_debug(unit
, "Forked %s as "PID_FMT
, command
->path
, pid
);
2904 /* We add the new process to the cgroup both in the child (so
2905 * that we can be sure that no user code is ever executed
2906 * outside of the cgroup) and in the parent (so that we can be
2907 * sure that when we kill the cgroup the process will be
2909 if (params
->cgroup_path
)
2910 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER
, params
->cgroup_path
, pid
);
2912 exec_status_start(&command
->exec_status
, pid
);
2918 void exec_context_init(ExecContext
*c
) {
2922 c
->ioprio
= IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE
, 0);
2923 c
->cpu_sched_policy
= SCHED_OTHER
;
2924 c
->syslog_priority
= LOG_DAEMON
|LOG_INFO
;
2925 c
->syslog_level_prefix
= true;
2926 c
->ignore_sigpipe
= true;
2927 c
->timer_slack_nsec
= NSEC_INFINITY
;
2928 c
->personality
= PERSONALITY_INVALID
;
2929 c
->runtime_directory_mode
= 0755;
2930 c
->capability_bounding_set
= CAP_ALL
;
2933 void exec_context_done(ExecContext
*c
) {
2938 c
->environment
= strv_free(c
->environment
);
2939 c
->environment_files
= strv_free(c
->environment_files
);
2940 c
->pass_environment
= strv_free(c
->pass_environment
);
2942 for (l
= 0; l
< ELEMENTSOF(c
->rlimit
); l
++)
2943 c
->rlimit
[l
] = mfree(c
->rlimit
[l
]);
2945 for (l
= 0; l
< 3; l
++)
2946 c
->stdio_fdname
[l
] = mfree(c
->stdio_fdname
[l
]);
2948 c
->working_directory
= mfree(c
->working_directory
);
2949 c
->root_directory
= mfree(c
->root_directory
);
2950 c
->tty_path
= mfree(c
->tty_path
);
2951 c
->syslog_identifier
= mfree(c
->syslog_identifier
);
2952 c
->user
= mfree(c
->user
);
2953 c
->group
= mfree(c
->group
);
2955 c
->supplementary_groups
= strv_free(c
->supplementary_groups
);
2957 c
->pam_name
= mfree(c
->pam_name
);
2959 c
->read_only_paths
= strv_free(c
->read_only_paths
);
2960 c
->read_write_paths
= strv_free(c
->read_write_paths
);
2961 c
->inaccessible_paths
= strv_free(c
->inaccessible_paths
);
2964 CPU_FREE(c
->cpuset
);
2966 c
->utmp_id
= mfree(c
->utmp_id
);
2967 c
->selinux_context
= mfree(c
->selinux_context
);
2968 c
->apparmor_profile
= mfree(c
->apparmor_profile
);
2970 c
->syscall_filter
= set_free(c
->syscall_filter
);
2971 c
->syscall_archs
= set_free(c
->syscall_archs
);
2972 c
->address_families
= set_free(c
->address_families
);
2974 c
->runtime_directory
= strv_free(c
->runtime_directory
);
2977 int exec_context_destroy_runtime_directory(ExecContext
*c
, const char *runtime_prefix
) {
2982 if (!runtime_prefix
)
2985 STRV_FOREACH(i
, c
->runtime_directory
) {
2986 _cleanup_free_
char *p
;
2988 p
= strjoin(runtime_prefix
, "/", *i
, NULL
);
2992 /* We execute this synchronously, since we need to be
2993 * sure this is gone when we start the service
2995 (void) rm_rf(p
, REMOVE_ROOT
);
3001 void exec_command_done(ExecCommand
*c
) {
3004 c
->path
= mfree(c
->path
);
3006 c
->argv
= strv_free(c
->argv
);
3009 void exec_command_done_array(ExecCommand
*c
, unsigned n
) {
3012 for (i
= 0; i
< n
; i
++)
3013 exec_command_done(c
+i
);
3016 ExecCommand
* exec_command_free_list(ExecCommand
*c
) {
3020 LIST_REMOVE(command
, c
, i
);
3021 exec_command_done(i
);
3028 void exec_command_free_array(ExecCommand
**c
, unsigned n
) {
3031 for (i
= 0; i
< n
; i
++)
3032 c
[i
] = exec_command_free_list(c
[i
]);
3035 typedef struct InvalidEnvInfo
{
3040 static void invalid_env(const char *p
, void *userdata
) {
3041 InvalidEnvInfo
*info
= userdata
;
3043 log_unit_error(info
->unit
, "Ignoring invalid environment assignment '%s': %s", p
, info
->path
);
3046 const char* exec_context_fdname(const ExecContext
*c
, int fd_index
) {
3051 if (c
->std_input
!= EXEC_INPUT_NAMED_FD
)
3053 return c
->stdio_fdname
[STDIN_FILENO
] ?: "stdin";
3055 if (c
->std_output
!= EXEC_OUTPUT_NAMED_FD
)
3057 return c
->stdio_fdname
[STDOUT_FILENO
] ?: "stdout";
3059 if (c
->std_error
!= EXEC_OUTPUT_NAMED_FD
)
3061 return c
->stdio_fdname
[STDERR_FILENO
] ?: "stderr";
3067 int exec_context_named_iofds(Unit
*unit
, const ExecContext
*c
, const ExecParameters
*p
, int named_iofds
[3]) {
3068 unsigned i
, targets
;
3069 const char *stdio_fdname
[3];
3074 targets
= (c
->std_input
== EXEC_INPUT_NAMED_FD
) +
3075 (c
->std_output
== EXEC_OUTPUT_NAMED_FD
) +
3076 (c
->std_error
== EXEC_OUTPUT_NAMED_FD
);
3078 for (i
= 0; i
< 3; i
++)
3079 stdio_fdname
[i
] = exec_context_fdname(c
, i
);
3081 for (i
= 0; i
< p
->n_fds
&& targets
> 0; i
++)
3082 if (named_iofds
[STDIN_FILENO
] < 0 && c
->std_input
== EXEC_INPUT_NAMED_FD
&& stdio_fdname
[STDIN_FILENO
] && streq(p
->fd_names
[i
], stdio_fdname
[STDIN_FILENO
])) {
3083 named_iofds
[STDIN_FILENO
] = p
->fds
[i
];
3085 } else if (named_iofds
[STDOUT_FILENO
] < 0 && c
->std_output
== EXEC_OUTPUT_NAMED_FD
&& stdio_fdname
[STDOUT_FILENO
] && streq(p
->fd_names
[i
], stdio_fdname
[STDOUT_FILENO
])) {
3086 named_iofds
[STDOUT_FILENO
] = p
->fds
[i
];
3088 } else if (named_iofds
[STDERR_FILENO
] < 0 && c
->std_error
== EXEC_OUTPUT_NAMED_FD
&& stdio_fdname
[STDERR_FILENO
] && streq(p
->fd_names
[i
], stdio_fdname
[STDERR_FILENO
])) {
3089 named_iofds
[STDERR_FILENO
] = p
->fds
[i
];
3093 return (targets
== 0 ? 0 : -ENOENT
);
3096 int exec_context_load_environment(Unit
*unit
, const ExecContext
*c
, char ***l
) {
3097 char **i
, **r
= NULL
;
3102 STRV_FOREACH(i
, c
->environment_files
) {
3105 bool ignore
= false;
3107 _cleanup_globfree_ glob_t pglob
= {};
3117 if (!path_is_absolute(fn
)) {
3125 /* Filename supports globbing, take all matching files */
3127 if (glob(fn
, 0, NULL
, &pglob
) != 0) {
3132 return errno
> 0 ? -errno
: -EINVAL
;
3134 count
= pglob
.gl_pathc
;
3142 for (n
= 0; n
< count
; n
++) {
3143 k
= load_env_file(NULL
, pglob
.gl_pathv
[n
], NULL
, &p
);
3151 /* Log invalid environment variables with filename */
3153 InvalidEnvInfo info
= {
3155 .path
= pglob
.gl_pathv
[n
]
3158 p
= strv_env_clean_with_callback(p
, invalid_env
, &info
);
3166 m
= strv_env_merge(2, r
, p
);
3182 static bool tty_may_match_dev_console(const char *tty
) {
3183 _cleanup_free_
char *active
= NULL
;
3189 if (startswith(tty
, "/dev/"))
3192 /* trivial identity? */
3193 if (streq(tty
, "console"))
3196 console
= resolve_dev_console(&active
);
3197 /* if we could not resolve, assume it may */
3201 /* "tty0" means the active VC, so it may be the same sometimes */
3202 return streq(console
, tty
) || (streq(console
, "tty0") && tty_is_vc(tty
));
3205 bool exec_context_may_touch_console(ExecContext
*ec
) {
3207 return (ec
->tty_reset
||
3209 ec
->tty_vt_disallocate
||
3210 is_terminal_input(ec
->std_input
) ||
3211 is_terminal_output(ec
->std_output
) ||
3212 is_terminal_output(ec
->std_error
)) &&
3213 tty_may_match_dev_console(exec_context_tty_path(ec
));
3216 static void strv_fprintf(FILE *f
, char **l
) {
3222 fprintf(f
, " %s", *g
);
3225 void exec_context_dump(ExecContext
*c
, FILE* f
, const char *prefix
) {
3232 prefix
= strempty(prefix
);
3236 "%sWorkingDirectory: %s\n"
3237 "%sRootDirectory: %s\n"
3238 "%sNonBlocking: %s\n"
3239 "%sPrivateTmp: %s\n"
3240 "%sPrivateDevices: %s\n"
3241 "%sProtectKernelTunables: %s\n"
3242 "%sProtectKernelModules: %s\n"
3243 "%sProtectControlGroups: %s\n"
3244 "%sPrivateNetwork: %s\n"
3245 "%sPrivateUsers: %s\n"
3246 "%sProtectHome: %s\n"
3247 "%sProtectSystem: %s\n"
3248 "%sIgnoreSIGPIPE: %s\n"
3249 "%sMemoryDenyWriteExecute: %s\n"
3250 "%sRestrictRealtime: %s\n",
3252 prefix
, c
->working_directory
? c
->working_directory
: "/",
3253 prefix
, c
->root_directory
? c
->root_directory
: "/",
3254 prefix
, yes_no(c
->non_blocking
),
3255 prefix
, yes_no(c
->private_tmp
),
3256 prefix
, yes_no(c
->private_devices
),
3257 prefix
, yes_no(c
->protect_kernel_tunables
),
3258 prefix
, yes_no(c
->protect_kernel_modules
),
3259 prefix
, yes_no(c
->protect_control_groups
),
3260 prefix
, yes_no(c
->private_network
),
3261 prefix
, yes_no(c
->private_users
),
3262 prefix
, protect_home_to_string(c
->protect_home
),
3263 prefix
, protect_system_to_string(c
->protect_system
),
3264 prefix
, yes_no(c
->ignore_sigpipe
),
3265 prefix
, yes_no(c
->memory_deny_write_execute
),
3266 prefix
, yes_no(c
->restrict_realtime
));
3268 STRV_FOREACH(e
, c
->environment
)
3269 fprintf(f
, "%sEnvironment: %s\n", prefix
, *e
);
3271 STRV_FOREACH(e
, c
->environment_files
)
3272 fprintf(f
, "%sEnvironmentFile: %s\n", prefix
, *e
);
3274 STRV_FOREACH(e
, c
->pass_environment
)
3275 fprintf(f
, "%sPassEnvironment: %s\n", prefix
, *e
);
3277 fprintf(f
, "%sRuntimeDirectoryMode: %04o\n", prefix
, c
->runtime_directory_mode
);
3279 STRV_FOREACH(d
, c
->runtime_directory
)
3280 fprintf(f
, "%sRuntimeDirectory: %s\n", prefix
, *d
);
3287 if (c
->oom_score_adjust_set
)
3289 "%sOOMScoreAdjust: %i\n",
3290 prefix
, c
->oom_score_adjust
);
3292 for (i
= 0; i
< RLIM_NLIMITS
; i
++)
3294 fprintf(f
, "%s%s: " RLIM_FMT
"\n",
3295 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_max
);
3296 fprintf(f
, "%s%sSoft: " RLIM_FMT
"\n",
3297 prefix
, rlimit_to_string(i
), c
->rlimit
[i
]->rlim_cur
);
3300 if (c
->ioprio_set
) {
3301 _cleanup_free_
char *class_str
= NULL
;
3303 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c
->ioprio
), &class_str
);
3305 "%sIOSchedulingClass: %s\n"
3306 "%sIOPriority: %i\n",
3307 prefix
, strna(class_str
),
3308 prefix
, (int) IOPRIO_PRIO_DATA(c
->ioprio
));
3311 if (c
->cpu_sched_set
) {
3312 _cleanup_free_
char *policy_str
= NULL
;
3314 sched_policy_to_string_alloc(c
->cpu_sched_policy
, &policy_str
);
3316 "%sCPUSchedulingPolicy: %s\n"
3317 "%sCPUSchedulingPriority: %i\n"
3318 "%sCPUSchedulingResetOnFork: %s\n",
3319 prefix
, strna(policy_str
),
3320 prefix
, c
->cpu_sched_priority
,
3321 prefix
, yes_no(c
->cpu_sched_reset_on_fork
));
3325 fprintf(f
, "%sCPUAffinity:", prefix
);
3326 for (i
= 0; i
< c
->cpuset_ncpus
; i
++)
3327 if (CPU_ISSET_S(i
, CPU_ALLOC_SIZE(c
->cpuset_ncpus
), c
->cpuset
))
3328 fprintf(f
, " %u", i
);
3332 if (c
->timer_slack_nsec
!= NSEC_INFINITY
)
3333 fprintf(f
, "%sTimerSlackNSec: "NSEC_FMT
"\n", prefix
, c
->timer_slack_nsec
);
3336 "%sStandardInput: %s\n"
3337 "%sStandardOutput: %s\n"
3338 "%sStandardError: %s\n",
3339 prefix
, exec_input_to_string(c
->std_input
),
3340 prefix
, exec_output_to_string(c
->std_output
),
3341 prefix
, exec_output_to_string(c
->std_error
));
3347 "%sTTYVHangup: %s\n"
3348 "%sTTYVTDisallocate: %s\n",
3349 prefix
, c
->tty_path
,
3350 prefix
, yes_no(c
->tty_reset
),
3351 prefix
, yes_no(c
->tty_vhangup
),
3352 prefix
, yes_no(c
->tty_vt_disallocate
));
3354 if (c
->std_output
== EXEC_OUTPUT_SYSLOG
||
3355 c
->std_output
== EXEC_OUTPUT_KMSG
||
3356 c
->std_output
== EXEC_OUTPUT_JOURNAL
||
3357 c
->std_output
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3358 c
->std_output
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3359 c
->std_output
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
||
3360 c
->std_error
== EXEC_OUTPUT_SYSLOG
||
3361 c
->std_error
== EXEC_OUTPUT_KMSG
||
3362 c
->std_error
== EXEC_OUTPUT_JOURNAL
||
3363 c
->std_error
== EXEC_OUTPUT_SYSLOG_AND_CONSOLE
||
3364 c
->std_error
== EXEC_OUTPUT_KMSG_AND_CONSOLE
||
3365 c
->std_error
== EXEC_OUTPUT_JOURNAL_AND_CONSOLE
) {
3367 _cleanup_free_
char *fac_str
= NULL
, *lvl_str
= NULL
;
3369 log_facility_unshifted_to_string_alloc(c
->syslog_priority
>> 3, &fac_str
);
3370 log_level_to_string_alloc(LOG_PRI(c
->syslog_priority
), &lvl_str
);
3373 "%sSyslogFacility: %s\n"
3374 "%sSyslogLevel: %s\n",
3375 prefix
, strna(fac_str
),
3376 prefix
, strna(lvl_str
));
3380 fprintf(f
, "%sSecure Bits:%s%s%s%s%s%s\n",
3382 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS
) ? " keep-caps" : "",
3383 (c
->secure_bits
& 1<<SECURE_KEEP_CAPS_LOCKED
) ? " keep-caps-locked" : "",
3384 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP
) ? " no-setuid-fixup" : "",
3385 (c
->secure_bits
& 1<<SECURE_NO_SETUID_FIXUP_LOCKED
) ? " no-setuid-fixup-locked" : "",
3386 (c
->secure_bits
& 1<<SECURE_NOROOT
) ? " noroot" : "",
3387 (c
->secure_bits
& 1<<SECURE_NOROOT_LOCKED
) ? "noroot-locked" : "");
3389 if (c
->capability_bounding_set
!= CAP_ALL
) {
3391 fprintf(f
, "%sCapabilityBoundingSet:", prefix
);
3393 for (l
= 0; l
<= cap_last_cap(); l
++)
3394 if (c
->capability_bounding_set
& (UINT64_C(1) << l
))
3395 fprintf(f
, " %s", strna(capability_to_name(l
)));
3400 if (c
->capability_ambient_set
!= 0) {
3402 fprintf(f
, "%sAmbientCapabilities:", prefix
);
3404 for (l
= 0; l
<= cap_last_cap(); l
++)
3405 if (c
->capability_ambient_set
& (UINT64_C(1) << l
))
3406 fprintf(f
, " %s", strna(capability_to_name(l
)));
3412 fprintf(f
, "%sUser: %s\n", prefix
, c
->user
);
3414 fprintf(f
, "%sGroup: %s\n", prefix
, c
->group
);
3416 fprintf(f
, "%sDynamicUser: %s\n", prefix
, yes_no(c
->dynamic_user
));
3418 if (strv_length(c
->supplementary_groups
) > 0) {
3419 fprintf(f
, "%sSupplementaryGroups:", prefix
);
3420 strv_fprintf(f
, c
->supplementary_groups
);
3425 fprintf(f
, "%sPAMName: %s\n", prefix
, c
->pam_name
);
3427 if (strv_length(c
->read_write_paths
) > 0) {
3428 fprintf(f
, "%sReadWritePaths:", prefix
);
3429 strv_fprintf(f
, c
->read_write_paths
);
3433 if (strv_length(c
->read_only_paths
) > 0) {
3434 fprintf(f
, "%sReadOnlyPaths:", prefix
);
3435 strv_fprintf(f
, c
->read_only_paths
);
3439 if (strv_length(c
->inaccessible_paths
) > 0) {
3440 fprintf(f
, "%sInaccessiblePaths:", prefix
);
3441 strv_fprintf(f
, c
->inaccessible_paths
);
3447 "%sUtmpIdentifier: %s\n",
3448 prefix
, c
->utmp_id
);
3450 if (c
->selinux_context
)
3452 "%sSELinuxContext: %s%s\n",
3453 prefix
, c
->selinux_context_ignore
? "-" : "", c
->selinux_context
);
3455 if (c
->personality
!= PERSONALITY_INVALID
)
3457 "%sPersonality: %s\n",
3458 prefix
, strna(personality_to_string(c
->personality
)));
3460 if (c
->syscall_filter
) {
3468 "%sSystemCallFilter: ",
3471 if (!c
->syscall_whitelist
)
3475 SET_FOREACH(id
, c
->syscall_filter
, j
) {
3476 _cleanup_free_
char *name
= NULL
;
3483 name
= seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE
, PTR_TO_INT(id
) - 1);
3484 fputs(strna(name
), f
);
3491 if (c
->syscall_archs
) {
3498 "%sSystemCallArchitectures:",
3502 SET_FOREACH(id
, c
->syscall_archs
, j
)
3503 fprintf(f
, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id
) - 1)));
3508 if (c
->syscall_errno
> 0)
3510 "%sSystemCallErrorNumber: %s\n",
3511 prefix
, strna(errno_to_name(c
->syscall_errno
)));
3513 if (c
->apparmor_profile
)
3515 "%sAppArmorProfile: %s%s\n",
3516 prefix
, c
->apparmor_profile_ignore
? "-" : "", c
->apparmor_profile
);
3519 bool exec_context_maintains_privileges(ExecContext
*c
) {
3522 /* Returns true if the process forked off would run under
3523 * an unchanged UID or as root. */
3528 if (streq(c
->user
, "root") || streq(c
->user
, "0"))
3534 void exec_status_start(ExecStatus
*s
, pid_t pid
) {
3539 dual_timestamp_get(&s
->start_timestamp
);
3542 void exec_status_exit(ExecStatus
*s
, ExecContext
*context
, pid_t pid
, int code
, int status
) {
3545 if (s
->pid
&& s
->pid
!= pid
)
3549 dual_timestamp_get(&s
->exit_timestamp
);
3555 if (context
->utmp_id
)
3556 utmp_put_dead_process(context
->utmp_id
, pid
, code
, status
);
3558 exec_context_tty_reset(context
, NULL
);
3562 void exec_status_dump(ExecStatus
*s
, FILE *f
, const char *prefix
) {
3563 char buf
[FORMAT_TIMESTAMP_MAX
];
3571 prefix
= strempty(prefix
);
3574 "%sPID: "PID_FMT
"\n",
3577 if (dual_timestamp_is_set(&s
->start_timestamp
))
3579 "%sStart Timestamp: %s\n",
3580 prefix
, format_timestamp(buf
, sizeof(buf
), s
->start_timestamp
.realtime
));
3582 if (dual_timestamp_is_set(&s
->exit_timestamp
))
3584 "%sExit Timestamp: %s\n"
3586 "%sExit Status: %i\n",
3587 prefix
, format_timestamp(buf
, sizeof(buf
), s
->exit_timestamp
.realtime
),
3588 prefix
, sigchld_code_to_string(s
->code
),
3592 char *exec_command_line(char **argv
) {
3600 STRV_FOREACH(a
, argv
)
3603 if (!(n
= new(char, k
)))
3607 STRV_FOREACH(a
, argv
) {
3614 if (strpbrk(*a
, WHITESPACE
)) {
3625 /* FIXME: this doesn't really handle arguments that have
3626 * spaces and ticks in them */
3631 void exec_command_dump(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3632 _cleanup_free_
char *cmd
= NULL
;
3633 const char *prefix2
;
3638 prefix
= strempty(prefix
);
3639 prefix2
= strjoina(prefix
, "\t");
3641 cmd
= exec_command_line(c
->argv
);
3643 "%sCommand Line: %s\n",
3644 prefix
, cmd
? cmd
: strerror(ENOMEM
));
3646 exec_status_dump(&c
->exec_status
, f
, prefix2
);
3649 void exec_command_dump_list(ExecCommand
*c
, FILE *f
, const char *prefix
) {
3652 prefix
= strempty(prefix
);
3654 LIST_FOREACH(command
, c
, c
)
3655 exec_command_dump(c
, f
, prefix
);
3658 void exec_command_append_list(ExecCommand
**l
, ExecCommand
*e
) {
3665 /* It's kind of important, that we keep the order here */
3666 LIST_FIND_TAIL(command
, *l
, end
);
3667 LIST_INSERT_AFTER(command
, *l
, end
, e
);
3672 int exec_command_set(ExecCommand
*c
, const char *path
, ...) {
3680 l
= strv_new_ap(path
, ap
);
3701 int exec_command_append(ExecCommand
*c
, const char *path
, ...) {
3702 _cleanup_strv_free_
char **l
= NULL
;
3710 l
= strv_new_ap(path
, ap
);
3716 r
= strv_extend_strv(&c
->argv
, l
, false);
3724 static int exec_runtime_allocate(ExecRuntime
**rt
) {
3729 *rt
= new0(ExecRuntime
, 1);
3734 (*rt
)->netns_storage_socket
[0] = (*rt
)->netns_storage_socket
[1] = -1;
3739 int exec_runtime_make(ExecRuntime
**rt
, ExecContext
*c
, const char *id
) {
3749 if (!c
->private_network
&& !c
->private_tmp
)
3752 r
= exec_runtime_allocate(rt
);
3756 if (c
->private_network
&& (*rt
)->netns_storage_socket
[0] < 0) {
3757 if (socketpair(AF_UNIX
, SOCK_DGRAM
|SOCK_CLOEXEC
, 0, (*rt
)->netns_storage_socket
) < 0)
3761 if (c
->private_tmp
&& !(*rt
)->tmp_dir
) {
3762 r
= setup_tmp_dirs(id
, &(*rt
)->tmp_dir
, &(*rt
)->var_tmp_dir
);
3770 ExecRuntime
*exec_runtime_ref(ExecRuntime
*r
) {
3772 assert(r
->n_ref
> 0);
3778 ExecRuntime
*exec_runtime_unref(ExecRuntime
*r
) {
3783 assert(r
->n_ref
> 0);
3790 free(r
->var_tmp_dir
);
3791 safe_close_pair(r
->netns_storage_socket
);
3795 int exec_runtime_serialize(Unit
*u
, ExecRuntime
*rt
, FILE *f
, FDSet
*fds
) {
3804 unit_serialize_item(u
, f
, "tmp-dir", rt
->tmp_dir
);
3806 if (rt
->var_tmp_dir
)
3807 unit_serialize_item(u
, f
, "var-tmp-dir", rt
->var_tmp_dir
);
3809 if (rt
->netns_storage_socket
[0] >= 0) {
3812 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[0]);
3816 unit_serialize_item_format(u
, f
, "netns-socket-0", "%i", copy
);
3819 if (rt
->netns_storage_socket
[1] >= 0) {
3822 copy
= fdset_put_dup(fds
, rt
->netns_storage_socket
[1]);
3826 unit_serialize_item_format(u
, f
, "netns-socket-1", "%i", copy
);
3832 int exec_runtime_deserialize_item(Unit
*u
, ExecRuntime
**rt
, const char *key
, const char *value
, FDSet
*fds
) {
3839 if (streq(key
, "tmp-dir")) {
3842 r
= exec_runtime_allocate(rt
);
3846 copy
= strdup(value
);
3850 free((*rt
)->tmp_dir
);
3851 (*rt
)->tmp_dir
= copy
;
3853 } else if (streq(key
, "var-tmp-dir")) {
3856 r
= exec_runtime_allocate(rt
);
3860 copy
= strdup(value
);
3864 free((*rt
)->var_tmp_dir
);
3865 (*rt
)->var_tmp_dir
= copy
;
3867 } else if (streq(key
, "netns-socket-0")) {
3870 r
= exec_runtime_allocate(rt
);
3874 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3875 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3877 safe_close((*rt
)->netns_storage_socket
[0]);
3878 (*rt
)->netns_storage_socket
[0] = fdset_remove(fds
, fd
);
3880 } else if (streq(key
, "netns-socket-1")) {
3883 r
= exec_runtime_allocate(rt
);
3887 if (safe_atoi(value
, &fd
) < 0 || !fdset_contains(fds
, fd
))
3888 log_unit_debug(u
, "Failed to parse netns socket value: %s", value
);
3890 safe_close((*rt
)->netns_storage_socket
[1]);
3891 (*rt
)->netns_storage_socket
[1] = fdset_remove(fds
, fd
);
3899 static void *remove_tmpdir_thread(void *p
) {
3900 _cleanup_free_
char *path
= p
;
3902 (void) rm_rf(path
, REMOVE_ROOT
|REMOVE_PHYSICAL
);
3906 void exec_runtime_destroy(ExecRuntime
*rt
) {
3912 /* If there are multiple users of this, let's leave the stuff around */
3917 log_debug("Spawning thread to nuke %s", rt
->tmp_dir
);
3919 r
= asynchronous_job(remove_tmpdir_thread
, rt
->tmp_dir
);
3921 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->tmp_dir
);
3928 if (rt
->var_tmp_dir
) {
3929 log_debug("Spawning thread to nuke %s", rt
->var_tmp_dir
);
3931 r
= asynchronous_job(remove_tmpdir_thread
, rt
->var_tmp_dir
);
3933 log_warning_errno(r
, "Failed to nuke %s: %m", rt
->var_tmp_dir
);
3934 free(rt
->var_tmp_dir
);
3937 rt
->var_tmp_dir
= NULL
;
3940 safe_close_pair(rt
->netns_storage_socket
);
3943 static const char* const exec_input_table
[_EXEC_INPUT_MAX
] = {
3944 [EXEC_INPUT_NULL
] = "null",
3945 [EXEC_INPUT_TTY
] = "tty",
3946 [EXEC_INPUT_TTY_FORCE
] = "tty-force",
3947 [EXEC_INPUT_TTY_FAIL
] = "tty-fail",
3948 [EXEC_INPUT_SOCKET
] = "socket",
3949 [EXEC_INPUT_NAMED_FD
] = "fd",
3952 DEFINE_STRING_TABLE_LOOKUP(exec_input
, ExecInput
);
3954 static const char* const exec_output_table
[_EXEC_OUTPUT_MAX
] = {
3955 [EXEC_OUTPUT_INHERIT
] = "inherit",
3956 [EXEC_OUTPUT_NULL
] = "null",
3957 [EXEC_OUTPUT_TTY
] = "tty",
3958 [EXEC_OUTPUT_SYSLOG
] = "syslog",
3959 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE
] = "syslog+console",
3960 [EXEC_OUTPUT_KMSG
] = "kmsg",
3961 [EXEC_OUTPUT_KMSG_AND_CONSOLE
] = "kmsg+console",
3962 [EXEC_OUTPUT_JOURNAL
] = "journal",
3963 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE
] = "journal+console",
3964 [EXEC_OUTPUT_SOCKET
] = "socket",
3965 [EXEC_OUTPUT_NAMED_FD
] = "fd",
3968 DEFINE_STRING_TABLE_LOOKUP(exec_output
, ExecOutput
);
3970 static const char* const exec_utmp_mode_table
[_EXEC_UTMP_MODE_MAX
] = {
3971 [EXEC_UTMP_INIT
] = "init",
3972 [EXEC_UTMP_LOGIN
] = "login",
3973 [EXEC_UTMP_USER
] = "user",
3976 DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode
, ExecUtmpMode
);