chiark / gitweb /
build-sys: prep release 12
[elogind.git] / src / execute.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <dirent.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #include <string.h>
28 #include <signal.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31 #include <sys/prctl.h>
32 #include <linux/sched.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <grp.h>
36 #include <pwd.h>
37 #include <sys/mount.h>
38 #include <linux/fs.h>
39 #include <linux/oom.h>
40
41 #ifdef HAVE_PAM
42 #include <security/pam_appl.h>
43 #endif
44
45 #include "execute.h"
46 #include "strv.h"
47 #include "macro.h"
48 #include "util.h"
49 #include "log.h"
50 #include "ioprio.h"
51 #include "securebits.h"
52 #include "cgroup.h"
53 #include "namespace.h"
54 #include "tcpwrap.h"
55 #include "exit-status.h"
56 #include "missing.h"
57 #include "utmp-wtmp.h"
58
59 /* This assumes there is a 'tty' group */
60 #define TTY_MODE 0620
61
62 static int shift_fds(int fds[], unsigned n_fds) {
63         int start, restart_from;
64
65         if (n_fds <= 0)
66                 return 0;
67
68         /* Modifies the fds array! (sorts it) */
69
70         assert(fds);
71
72         start = 0;
73         for (;;) {
74                 int i;
75
76                 restart_from = -1;
77
78                 for (i = start; i < (int) n_fds; i++) {
79                         int nfd;
80
81                         /* Already at right index? */
82                         if (fds[i] == i+3)
83                                 continue;
84
85                         if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
86                                 return -errno;
87
88                         close_nointr_nofail(fds[i]);
89                         fds[i] = nfd;
90
91                         /* Hmm, the fd we wanted isn't free? Then
92                          * let's remember that and try again from here*/
93                         if (nfd != i+3 && restart_from < 0)
94                                 restart_from = i;
95                 }
96
97                 if (restart_from < 0)
98                         break;
99
100                 start = restart_from;
101         }
102
103         return 0;
104 }
105
106 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
107         unsigned i;
108         int r;
109
110         if (n_fds <= 0)
111                 return 0;
112
113         assert(fds);
114
115         /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
116
117         for (i = 0; i < n_fds; i++) {
118
119                 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
120                         return r;
121
122                 /* We unconditionally drop FD_CLOEXEC from the fds,
123                  * since after all we want to pass these fds to our
124                  * children */
125
126                 if ((r = fd_cloexec(fds[i], false)) < 0)
127                         return r;
128         }
129
130         return 0;
131 }
132
133 static const char *tty_path(const ExecContext *context) {
134         assert(context);
135
136         if (context->tty_path)
137                 return context->tty_path;
138
139         return "/dev/console";
140 }
141
142 static int open_null_as(int flags, int nfd) {
143         int fd, r;
144
145         assert(nfd >= 0);
146
147         if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
148                 return -errno;
149
150         if (fd != nfd) {
151                 r = dup2(fd, nfd) < 0 ? -errno : nfd;
152                 close_nointr_nofail(fd);
153         } else
154                 r = nfd;
155
156         return r;
157 }
158
159 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
160         int fd, r;
161         union {
162                 struct sockaddr sa;
163                 struct sockaddr_un un;
164         } sa;
165
166         assert(context);
167         assert(output < _EXEC_OUTPUT_MAX);
168         assert(ident);
169         assert(nfd >= 0);
170
171         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
172                 return -errno;
173
174         zero(sa);
175         sa.sa.sa_family = AF_UNIX;
176         strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
177
178         if (connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + 1 + sizeof(LOGGER_SOCKET) - 1) < 0) {
179                 close_nointr_nofail(fd);
180                 return -errno;
181         }
182
183         if (shutdown(fd, SHUT_RD) < 0) {
184                 close_nointr_nofail(fd);
185                 return -errno;
186         }
187
188         /* We speak a very simple protocol between log server
189          * and client: one line for the log destination (kmsg
190          * or syslog), followed by the priority field,
191          * followed by the process name. Since we replaced
192          * stdin/stderr we simple use stdio to write to
193          * it. Note that we use stderr, to minimize buffer
194          * flushing issues. */
195
196         dprintf(fd,
197                 "%s\n"
198                 "%i\n"
199                 "%s\n"
200                 "%i\n",
201                 output == EXEC_OUTPUT_KMSG ? "kmsg" : "syslog",
202                 context->syslog_priority,
203                 context->syslog_identifier ? context->syslog_identifier : ident,
204                 context->syslog_level_prefix);
205
206         if (fd != nfd) {
207                 r = dup2(fd, nfd) < 0 ? -errno : nfd;
208                 close_nointr_nofail(fd);
209         } else
210                 r = nfd;
211
212         return r;
213 }
214 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
215         int fd, r;
216
217         assert(path);
218         assert(nfd >= 0);
219
220         if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
221                 return fd;
222
223         if (fd != nfd) {
224                 r = dup2(fd, nfd) < 0 ? -errno : nfd;
225                 close_nointr_nofail(fd);
226         } else
227                 r = nfd;
228
229         return r;
230 }
231
232 static bool is_terminal_input(ExecInput i) {
233         return
234                 i == EXEC_INPUT_TTY ||
235                 i == EXEC_INPUT_TTY_FORCE ||
236                 i == EXEC_INPUT_TTY_FAIL;
237 }
238
239 static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
240
241         if (is_terminal_input(std_input) && !apply_tty_stdin)
242                 return EXEC_INPUT_NULL;
243
244         if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
245                 return EXEC_INPUT_NULL;
246
247         return std_input;
248 }
249
250 static int fixup_output(ExecOutput std_output, int socket_fd) {
251
252         if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
253                 return EXEC_OUTPUT_INHERIT;
254
255         return std_output;
256 }
257
258 static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
259         ExecInput i;
260
261         assert(context);
262
263         i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
264
265         switch (i) {
266
267         case EXEC_INPUT_NULL:
268                 return open_null_as(O_RDONLY, STDIN_FILENO);
269
270         case EXEC_INPUT_TTY:
271         case EXEC_INPUT_TTY_FORCE:
272         case EXEC_INPUT_TTY_FAIL: {
273                 int fd, r;
274
275                 if ((fd = acquire_terminal(
276                                      tty_path(context),
277                                      i == EXEC_INPUT_TTY_FAIL,
278                                      i == EXEC_INPUT_TTY_FORCE,
279                                      false)) < 0)
280                         return fd;
281
282                 if (fd != STDIN_FILENO) {
283                         r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
284                         close_nointr_nofail(fd);
285                 } else
286                         r = STDIN_FILENO;
287
288                 return r;
289         }
290
291         case EXEC_INPUT_SOCKET:
292                 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
293
294         default:
295                 assert_not_reached("Unknown input type");
296         }
297 }
298
299 static int setup_output(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
300         ExecOutput o;
301         ExecInput i;
302
303         assert(context);
304         assert(ident);
305
306         i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
307         o = fixup_output(context->std_output, socket_fd);
308
309         /* This expects the input is already set up */
310
311         switch (o) {
312
313         case EXEC_OUTPUT_INHERIT:
314
315                 /* If input got downgraded, inherit the original value */
316                 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
317                         return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
318
319                 /* If the input is connected to anything that's not a /dev/null, inherit that... */
320                 if (i != EXEC_INPUT_NULL)
321                         return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
322
323                 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
324                 if (getppid() != 1)
325                         return STDOUT_FILENO;
326
327                 /* We need to open /dev/null here anew, to get the
328                  * right access mode. So we fall through */
329
330         case EXEC_OUTPUT_NULL:
331                 return open_null_as(O_WRONLY, STDOUT_FILENO);
332
333         case EXEC_OUTPUT_TTY:
334                 if (is_terminal_input(i))
335                         return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
336
337                 /* We don't reset the terminal if this is just about output */
338                 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
339
340         case EXEC_OUTPUT_SYSLOG:
341         case EXEC_OUTPUT_KMSG:
342                 return connect_logger_as(context, o, ident, STDOUT_FILENO);
343
344         case EXEC_OUTPUT_SOCKET:
345                 assert(socket_fd >= 0);
346                 return dup2(socket_fd, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
347
348         default:
349                 assert_not_reached("Unknown output type");
350         }
351 }
352
353 static int setup_error(const ExecContext *context, int socket_fd, const char *ident, bool apply_tty_stdin) {
354         ExecOutput o, e;
355         ExecInput i;
356
357         assert(context);
358         assert(ident);
359
360         i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
361         o = fixup_output(context->std_output, socket_fd);
362         e = fixup_output(context->std_error, socket_fd);
363
364         /* This expects the input and output are already set up */
365
366         /* Don't change the stderr file descriptor if we inherit all
367          * the way and are not on a tty */
368         if (e == EXEC_OUTPUT_INHERIT &&
369             o == EXEC_OUTPUT_INHERIT &&
370             i == EXEC_INPUT_NULL &&
371             !is_terminal_input(context->std_input) &&
372             getppid () != 1)
373                 return STDERR_FILENO;
374
375         /* Duplicate from stdout if possible */
376         if (e == o || e == EXEC_OUTPUT_INHERIT)
377                 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
378
379         switch (e) {
380
381         case EXEC_OUTPUT_NULL:
382                 return open_null_as(O_WRONLY, STDERR_FILENO);
383
384         case EXEC_OUTPUT_TTY:
385                 if (is_terminal_input(i))
386                         return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
387
388                 /* We don't reset the terminal if this is just about output */
389                 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
390
391         case EXEC_OUTPUT_SYSLOG:
392         case EXEC_OUTPUT_KMSG:
393                 return connect_logger_as(context, e, ident, STDERR_FILENO);
394
395         case EXEC_OUTPUT_SOCKET:
396                 assert(socket_fd >= 0);
397                 return dup2(socket_fd, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
398
399         default:
400                 assert_not_reached("Unknown error type");
401         }
402 }
403
404 static int chown_terminal(int fd, uid_t uid) {
405         struct stat st;
406
407         assert(fd >= 0);
408
409         /* This might fail. What matters are the results. */
410         (void) fchown(fd, uid, -1);
411         (void) fchmod(fd, TTY_MODE);
412
413         if (fstat(fd, &st) < 0)
414                 return -errno;
415
416         if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
417                 return -EPERM;
418
419         return 0;
420 }
421
422 static int setup_confirm_stdio(const ExecContext *context,
423                                int *_saved_stdin,
424                                int *_saved_stdout) {
425         int fd = -1, saved_stdin, saved_stdout = -1, r;
426
427         assert(context);
428         assert(_saved_stdin);
429         assert(_saved_stdout);
430
431         /* This returns positive EXIT_xxx return values instead of
432          * negative errno style values! */
433
434         if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
435                 return EXIT_STDIN;
436
437         if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
438                 r = EXIT_STDOUT;
439                 goto fail;
440         }
441
442         if ((fd = acquire_terminal(
443                              tty_path(context),
444                              context->std_input == EXEC_INPUT_TTY_FAIL,
445                              context->std_input == EXEC_INPUT_TTY_FORCE,
446                              false)) < 0) {
447                 r = EXIT_STDIN;
448                 goto fail;
449         }
450
451         if (chown_terminal(fd, getuid()) < 0) {
452                 r = EXIT_STDIN;
453                 goto fail;
454         }
455
456         if (dup2(fd, STDIN_FILENO) < 0) {
457                 r = EXIT_STDIN;
458                 goto fail;
459         }
460
461         if (dup2(fd, STDOUT_FILENO) < 0) {
462                 r = EXIT_STDOUT;
463                 goto fail;
464         }
465
466         if (fd >= 2)
467                 close_nointr_nofail(fd);
468
469         *_saved_stdin = saved_stdin;
470         *_saved_stdout = saved_stdout;
471
472         return 0;
473
474 fail:
475         if (saved_stdout >= 0)
476                 close_nointr_nofail(saved_stdout);
477
478         if (saved_stdin >= 0)
479                 close_nointr_nofail(saved_stdin);
480
481         if (fd >= 0)
482                 close_nointr_nofail(fd);
483
484         return r;
485 }
486
487 static int restore_confirm_stdio(const ExecContext *context,
488                                  int *saved_stdin,
489                                  int *saved_stdout,
490                                  bool *keep_stdin,
491                                  bool *keep_stdout) {
492
493         assert(context);
494         assert(saved_stdin);
495         assert(*saved_stdin >= 0);
496         assert(saved_stdout);
497         assert(*saved_stdout >= 0);
498
499         /* This returns positive EXIT_xxx return values instead of
500          * negative errno style values! */
501
502         if (is_terminal_input(context->std_input)) {
503
504                 /* The service wants terminal input. */
505
506                 *keep_stdin = true;
507                 *keep_stdout =
508                         context->std_output == EXEC_OUTPUT_INHERIT ||
509                         context->std_output == EXEC_OUTPUT_TTY;
510
511         } else {
512                 /* If the service doesn't want a controlling terminal,
513                  * then we need to get rid entirely of what we have
514                  * already. */
515
516                 if (release_terminal() < 0)
517                         return EXIT_STDIN;
518
519                 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
520                         return EXIT_STDIN;
521
522                 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
523                         return EXIT_STDOUT;
524
525                 *keep_stdout = *keep_stdin = false;
526         }
527
528         return 0;
529 }
530
531 static int get_group_creds(const char *groupname, gid_t *gid) {
532         struct group *g;
533         unsigned long lu;
534
535         assert(groupname);
536         assert(gid);
537
538         /* We enforce some special rules for gid=0: in order to avoid
539          * NSS lookups for root we hardcode its data. */
540
541         if (streq(groupname, "root") || streq(groupname, "0")) {
542                 *gid = 0;
543                 return 0;
544         }
545
546         if (safe_atolu(groupname, &lu) >= 0) {
547                 errno = 0;
548                 g = getgrgid((gid_t) lu);
549         } else {
550                 errno = 0;
551                 g = getgrnam(groupname);
552         }
553
554         if (!g)
555                 return errno != 0 ? -errno : -ESRCH;
556
557         *gid = g->gr_gid;
558         return 0;
559 }
560
561 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
562         struct passwd *p;
563         unsigned long lu;
564
565         assert(username);
566         assert(*username);
567         assert(uid);
568         assert(gid);
569         assert(home);
570
571         /* We enforce some special rules for uid=0: in order to avoid
572          * NSS lookups for root we hardcode its data. */
573
574         if (streq(*username, "root") || streq(*username, "0")) {
575                 *username = "root";
576                 *uid = 0;
577                 *gid = 0;
578                 *home = "/root";
579                 return 0;
580         }
581
582         if (safe_atolu(*username, &lu) >= 0) {
583                 errno = 0;
584                 p = getpwuid((uid_t) lu);
585
586                 /* If there are multiple users with the same id, make
587                  * sure to leave $USER to the configured value instead
588                  * of the first occurence in the database. However if
589                  * the uid was configured by a numeric uid, then let's
590                  * pick the real username from /etc/passwd. */
591                 if (*username && p)
592                         *username = p->pw_name;
593         } else {
594                 errno = 0;
595                 p = getpwnam(*username);
596         }
597
598         if (!p)
599                 return errno != 0 ? -errno : -ESRCH;
600
601         *uid = p->pw_uid;
602         *gid = p->pw_gid;
603         *home = p->pw_dir;
604         return 0;
605 }
606
607 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
608         bool keep_groups = false;
609         int r;
610
611         assert(context);
612
613         /* Lookup and ser GID and supplementary group list. Here too
614          * we avoid NSS lookups for gid=0. */
615
616         if (context->group || username) {
617
618                 if (context->group)
619                         if ((r = get_group_creds(context->group, &gid)) < 0)
620                                 return r;
621
622                 /* First step, initialize groups from /etc/groups */
623                 if (username && gid != 0) {
624                         if (initgroups(username, gid) < 0)
625                                 return -errno;
626
627                         keep_groups = true;
628                 }
629
630                 /* Second step, set our gids */
631                 if (setresgid(gid, gid, gid) < 0)
632                         return -errno;
633         }
634
635         if (context->supplementary_groups) {
636                 int ngroups_max, k;
637                 gid_t *gids;
638                 char **i;
639
640                 /* Final step, initialize any manually set supplementary groups */
641                 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
642
643                 if (!(gids = new(gid_t, ngroups_max)))
644                         return -ENOMEM;
645
646                 if (keep_groups) {
647                         if ((k = getgroups(ngroups_max, gids)) < 0) {
648                                 free(gids);
649                                 return -errno;
650                         }
651                 } else
652                         k = 0;
653
654                 STRV_FOREACH(i, context->supplementary_groups) {
655
656                         if (k >= ngroups_max) {
657                                 free(gids);
658                                 return -E2BIG;
659                         }
660
661                         if ((r = get_group_creds(*i, gids+k)) < 0) {
662                                 free(gids);
663                                 return r;
664                         }
665
666                         k++;
667                 }
668
669                 if (setgroups(k, gids) < 0) {
670                         free(gids);
671                         return -errno;
672                 }
673
674                 free(gids);
675         }
676
677         return 0;
678 }
679
680 static int enforce_user(const ExecContext *context, uid_t uid) {
681         int r;
682         assert(context);
683
684         /* Sets (but doesn't lookup) the uid and make sure we keep the
685          * capabilities while doing so. */
686
687         if (context->capabilities) {
688                 cap_t d;
689                 static const cap_value_t bits[] = {
690                         CAP_SETUID,   /* Necessary so that we can run setresuid() below */
691                         CAP_SETPCAP   /* Necessary so that we can set PR_SET_SECUREBITS later on */
692                 };
693
694                 /* First step: If we need to keep capabilities but
695                  * drop privileges we need to make sure we keep our
696                  * caps, whiel we drop priviliges. */
697                 if (uid != 0) {
698                         int sb = context->secure_bits|SECURE_KEEP_CAPS;
699
700                         if (prctl(PR_GET_SECUREBITS) != sb)
701                                 if (prctl(PR_SET_SECUREBITS, sb) < 0)
702                                         return -errno;
703                 }
704
705                 /* Second step: set the capabilites. This will reduce
706                  * the capabilities to the minimum we need. */
707
708                 if (!(d = cap_dup(context->capabilities)))
709                         return -errno;
710
711                 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
712                     cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
713                         r = -errno;
714                         cap_free(d);
715                         return r;
716                 }
717
718                 if (cap_set_proc(d) < 0) {
719                         r = -errno;
720                         cap_free(d);
721                         return r;
722                 }
723
724                 cap_free(d);
725         }
726
727         /* Third step: actually set the uids */
728         if (setresuid(uid, uid, uid) < 0)
729                 return -errno;
730
731         /* At this point we should have all necessary capabilities but
732            are otherwise a normal user. However, the caps might got
733            corrupted due to the setresuid() so we need clean them up
734            later. This is done outside of this call. */
735
736         return 0;
737 }
738
739 #ifdef HAVE_PAM
740
741 static int null_conv(
742                 int num_msg,
743                 const struct pam_message **msg,
744                 struct pam_response **resp,
745                 void *appdata_ptr) {
746
747         /* We don't support conversations */
748
749         return PAM_CONV_ERR;
750 }
751
752 static int setup_pam(
753                 const char *name,
754                 const char *user,
755                 const char *tty,
756                 char ***pam_env,
757                 int fds[], unsigned n_fds) {
758
759         static const struct pam_conv conv = {
760                 .conv = null_conv,
761                 .appdata_ptr = NULL
762         };
763
764         pam_handle_t *handle = NULL;
765         sigset_t ss, old_ss;
766         int pam_code = PAM_SUCCESS;
767         char **e = NULL;
768         bool close_session = false;
769         pid_t pam_pid = 0, parent_pid;
770
771         assert(name);
772         assert(user);
773         assert(pam_env);
774
775         /* We set up PAM in the parent process, then fork. The child
776          * will then stay around untill killed via PR_GET_PDEATHSIG or
777          * systemd via the cgroup logic. It will then remove the PAM
778          * session again. The parent process will exec() the actual
779          * daemon. We do things this way to ensure that the main PID
780          * of the daemon is the one we initially fork()ed. */
781
782         if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
783                 handle = NULL;
784                 goto fail;
785         }
786
787         if (tty)
788                 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
789                         goto fail;
790
791         if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
792                 goto fail;
793
794         if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
795                 goto fail;
796
797         close_session = true;
798
799         if ((pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | PAM_SILENT)) != PAM_SUCCESS)
800                 goto fail;
801
802         if ((!(e = pam_getenvlist(handle)))) {
803                 pam_code = PAM_BUF_ERR;
804                 goto fail;
805         }
806
807         /* Block SIGTERM, so that we know that it won't get lost in
808          * the child */
809         if (sigemptyset(&ss) < 0 ||
810             sigaddset(&ss, SIGTERM) < 0 ||
811             sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
812                 goto fail;
813
814         parent_pid = getpid();
815
816         if ((pam_pid = fork()) < 0)
817                 goto fail;
818
819         if (pam_pid == 0) {
820                 int sig;
821                 int r = EXIT_PAM;
822
823                 /* The child's job is to reset the PAM session on
824                  * termination */
825
826                 /* This string must fit in 10 chars (i.e. the length
827                  * of "/sbin/init") */
828                 rename_process("sd:pam");
829
830                 /* Make sure we don't keep open the passed fds in this
831                 child. We assume that otherwise only those fds are
832                 open here that have been opened by PAM. */
833                 close_many(fds, n_fds);
834
835                 /* Wait until our parent died. This will most likely
836                  * not work since the kernel does not allow
837                  * unpriviliged paretns kill their priviliged children
838                  * this way. We rely on the control groups kill logic
839                  * to do the rest for us. */
840                 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
841                         goto child_finish;
842
843                 /* Check if our parent process might already have
844                  * died? */
845                 if (getppid() == parent_pid) {
846                         if (sigwait(&ss, &sig) < 0)
847                                 goto child_finish;
848
849                         assert(sig == SIGTERM);
850                 }
851
852                 /* Only if our parent died we'll end the session */
853                 if (getppid() != parent_pid)
854                         if ((pam_code = pam_close_session(handle, PAM_DATA_SILENT)) != PAM_SUCCESS)
855                                 goto child_finish;
856
857                 r = 0;
858
859         child_finish:
860                 pam_end(handle, pam_code | PAM_DATA_SILENT);
861                 _exit(r);
862         }
863
864         /* If the child was forked off successfully it will do all the
865          * cleanups, so forget about the handle here. */
866         handle = NULL;
867
868         /* Unblock SIGSUR1 again in the parent */
869         if (sigprocmask(SIG_SETMASK, &old_ss, NULL) < 0)
870                 goto fail;
871
872         /* We close the log explicitly here, since the PAM modules
873          * might have opened it, but we don't want this fd around. */
874         closelog();
875
876         return 0;
877
878 fail:
879         if (handle) {
880                 if (close_session)
881                         pam_code = pam_close_session(handle, PAM_DATA_SILENT);
882
883                 pam_end(handle, pam_code | PAM_DATA_SILENT);
884         }
885
886         strv_free(e);
887
888         closelog();
889
890         if (pam_pid > 1)
891                 kill(pam_pid, SIGTERM);
892
893         return EXIT_PAM;
894 }
895 #endif
896
897 int exec_spawn(ExecCommand *command,
898                char **argv,
899                const ExecContext *context,
900                int fds[], unsigned n_fds,
901                char **environment,
902                bool apply_permissions,
903                bool apply_chroot,
904                bool apply_tty_stdin,
905                bool confirm_spawn,
906                CGroupBonding *cgroup_bondings,
907                pid_t *ret) {
908
909         pid_t pid;
910         int r;
911         char *line;
912         int socket_fd;
913
914         assert(command);
915         assert(context);
916         assert(ret);
917         assert(fds || n_fds <= 0);
918
919         if (context->std_input == EXEC_INPUT_SOCKET ||
920             context->std_output == EXEC_OUTPUT_SOCKET ||
921             context->std_error == EXEC_OUTPUT_SOCKET) {
922
923                 if (n_fds != 1)
924                         return -EINVAL;
925
926                 socket_fd = fds[0];
927
928                 fds = NULL;
929                 n_fds = 0;
930         } else
931                 socket_fd = -1;
932
933         if (!argv)
934                 argv = command->argv;
935
936         if (!(line = exec_command_line(argv)))
937                 return -ENOMEM;
938
939         log_debug("About to execute: %s", line);
940         free(line);
941
942         if (cgroup_bondings)
943                 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
944                         return r;
945
946         if ((pid = fork()) < 0)
947                 return -errno;
948
949         if (pid == 0) {
950                 int i;
951                 sigset_t ss;
952                 const char *username = NULL, *home = NULL;
953                 uid_t uid = (uid_t) -1;
954                 gid_t gid = (gid_t) -1;
955                 char **our_env = NULL, **pam_env = NULL, **final_env = NULL, **final_argv = NULL;
956                 unsigned n_env = 0;
957                 int saved_stdout = -1, saved_stdin = -1;
958                 bool keep_stdout = false, keep_stdin = false;
959
960                 /* child */
961
962                 /* This string must fit in 10 chars (i.e. the length
963                  * of "/sbin/init") */
964                 rename_process("sd:exec");
965
966                 /* We reset exactly these signals, since they are the
967                  * only ones we set to SIG_IGN in the main daemon. All
968                  * others we leave untouched because we set them to
969                  * SIG_DFL or a valid handler initially, both of which
970                  * will be demoted to SIG_DFL. */
971                 default_signals(SIGNALS_CRASH_HANDLER,
972                                 SIGNALS_IGNORE, -1);
973
974                 if (sigemptyset(&ss) < 0 ||
975                     sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
976                         r = EXIT_SIGNAL_MASK;
977                         goto fail;
978                 }
979
980                 /* Close sockets very early to make sure we don't
981                  * block init reexecution because it cannot bind its
982                  * sockets */
983                 if (close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
984                                   socket_fd >= 0 ? 1 : n_fds) < 0) {
985                         r = EXIT_FDS;
986                         goto fail;
987                 }
988
989                 if (!context->same_pgrp)
990                         if (setsid() < 0) {
991                                 r = EXIT_SETSID;
992                                 goto fail;
993                         }
994
995                 if (context->tcpwrap_name) {
996                         if (socket_fd >= 0)
997                                 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
998                                         r = EXIT_TCPWRAP;
999                                         goto fail;
1000                                 }
1001
1002                         for (i = 0; i < (int) n_fds; i++) {
1003                                 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
1004                                         r = EXIT_TCPWRAP;
1005                                         goto fail;
1006                                 }
1007                         }
1008                 }
1009
1010                 /* We skip the confirmation step if we shall not apply the TTY */
1011                 if (confirm_spawn &&
1012                     (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
1013                         char response;
1014
1015                         /* Set up terminal for the question */
1016                         if ((r = setup_confirm_stdio(context,
1017                                                      &saved_stdin, &saved_stdout)))
1018                                 goto fail;
1019
1020                         /* Now ask the question. */
1021                         if (!(line = exec_command_line(argv))) {
1022                                 r = EXIT_MEMORY;
1023                                 goto fail;
1024                         }
1025
1026                         r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1027                         free(line);
1028
1029                         if (r < 0 || response == 'n') {
1030                                 r = EXIT_CONFIRM;
1031                                 goto fail;
1032                         } else if (response == 's') {
1033                                 r = 0;
1034                                 goto fail;
1035                         }
1036
1037                         /* Release terminal for the question */
1038                         if ((r = restore_confirm_stdio(context,
1039                                                        &saved_stdin, &saved_stdout,
1040                                                        &keep_stdin, &keep_stdout)))
1041                                 goto fail;
1042                 }
1043
1044                 /* If a socket is connected to STDIN/STDOUT/STDERR, we
1045                  * must sure to drop O_NONBLOCK */
1046                 if (socket_fd >= 0)
1047                         fd_nonblock(socket_fd, false);
1048
1049                 if (!keep_stdin)
1050                         if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1051                                 r = EXIT_STDIN;
1052                                 goto fail;
1053                         }
1054
1055                 if (!keep_stdout)
1056                         if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1057                                 r = EXIT_STDOUT;
1058                                 goto fail;
1059                         }
1060
1061                 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1062                         r = EXIT_STDERR;
1063                         goto fail;
1064                 }
1065
1066                 if (cgroup_bondings)
1067                         if (cgroup_bonding_install_list(cgroup_bondings, 0) < 0) {
1068                                 r = EXIT_CGROUP;
1069                                 goto fail;
1070                         }
1071
1072                 if (context->oom_score_adjust_set) {
1073                         char t[16];
1074
1075                         snprintf(t, sizeof(t), "%i", context->oom_score_adjust);
1076                         char_array_0(t);
1077
1078                         if (write_one_line_file("/proc/self/oom_score_adj", t) < 0) {
1079                                 /* Compatibility with Linux <= 2.6.35 */
1080
1081                                 int adj;
1082
1083                                 adj = (context->oom_score_adjust * -OOM_DISABLE) / OOM_SCORE_ADJ_MAX;
1084                                 adj = CLAMP(adj, OOM_DISABLE, OOM_ADJUST_MAX);
1085
1086                                 snprintf(t, sizeof(t), "%i", adj);
1087                                 char_array_0(t);
1088
1089                                 if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1090                                         r = EXIT_OOM_ADJUST;
1091                                         goto fail;
1092                                 }
1093                         }
1094                 }
1095
1096                 if (context->nice_set)
1097                         if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1098                                 r = EXIT_NICE;
1099                                 goto fail;
1100                         }
1101
1102                 if (context->cpu_sched_set) {
1103                         struct sched_param param;
1104
1105                         zero(param);
1106                         param.sched_priority = context->cpu_sched_priority;
1107
1108                         if (sched_setscheduler(0, context->cpu_sched_policy |
1109                                                (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), &param) < 0) {
1110                                 r = EXIT_SETSCHEDULER;
1111                                 goto fail;
1112                         }
1113                 }
1114
1115                 if (context->cpuset)
1116                         if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1117                                 r = EXIT_CPUAFFINITY;
1118                                 goto fail;
1119                         }
1120
1121                 if (context->ioprio_set)
1122                         if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1123                                 r = EXIT_IOPRIO;
1124                                 goto fail;
1125                         }
1126
1127                 if (context->timer_slack_nsec_set)
1128                         if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1129                                 r = EXIT_TIMERSLACK;
1130                                 goto fail;
1131                         }
1132
1133                 if (context->utmp_id)
1134                         utmp_put_init_process(0, context->utmp_id, getpid(), getsid(0), context->tty_path);
1135
1136                 if (context->user) {
1137                         username = context->user;
1138                         if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1139                                 r = EXIT_USER;
1140                                 goto fail;
1141                         }
1142
1143                         if (is_terminal_input(context->std_input))
1144                                 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1145                                         r = EXIT_STDIN;
1146                                         goto fail;
1147                                 }
1148                 }
1149
1150 #ifdef HAVE_PAM
1151                 if (context->pam_name && username) {
1152                         if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1153                                 r = EXIT_PAM;
1154                                 goto fail;
1155                         }
1156                 }
1157 #endif
1158
1159                 if (apply_permissions)
1160                         if (enforce_groups(context, username, uid) < 0) {
1161                                 r = EXIT_GROUP;
1162                                 goto fail;
1163                         }
1164
1165                 umask(context->umask);
1166
1167                 if (strv_length(context->read_write_dirs) > 0 ||
1168                     strv_length(context->read_only_dirs) > 0 ||
1169                     strv_length(context->inaccessible_dirs) > 0 ||
1170                     context->mount_flags != MS_SHARED ||
1171                     context->private_tmp)
1172                         if ((r = setup_namespace(
1173                                              context->read_write_dirs,
1174                                              context->read_only_dirs,
1175                                              context->inaccessible_dirs,
1176                                              context->private_tmp,
1177                                              context->mount_flags)) < 0)
1178                                 goto fail;
1179
1180                 if (apply_chroot) {
1181                         if (context->root_directory)
1182                                 if (chroot(context->root_directory) < 0) {
1183                                         r = EXIT_CHROOT;
1184                                         goto fail;
1185                                 }
1186
1187                         if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1188                                 r = EXIT_CHDIR;
1189                                 goto fail;
1190                         }
1191                 } else {
1192
1193                         char *d;
1194
1195                         if (asprintf(&d, "%s/%s",
1196                                      context->root_directory ? context->root_directory : "",
1197                                      context->working_directory ? context->working_directory : "") < 0) {
1198                                 r = EXIT_MEMORY;
1199                                 goto fail;
1200                         }
1201
1202                         if (chdir(d) < 0) {
1203                                 free(d);
1204                                 r = EXIT_CHDIR;
1205                                 goto fail;
1206                         }
1207
1208                         free(d);
1209                 }
1210
1211                 /* We repeat the fd closing here, to make sure that
1212                  * nothing is leaked from the PAM modules */
1213                 if (close_all_fds(fds, n_fds) < 0 ||
1214                     shift_fds(fds, n_fds) < 0 ||
1215                     flags_fds(fds, n_fds, context->non_blocking) < 0) {
1216                         r = EXIT_FDS;
1217                         goto fail;
1218                 }
1219
1220                 if (apply_permissions) {
1221
1222                         for (i = 0; i < RLIMIT_NLIMITS; i++) {
1223                                 if (!context->rlimit[i])
1224                                         continue;
1225
1226                                 if (setrlimit(i, context->rlimit[i]) < 0) {
1227                                         r = EXIT_LIMITS;
1228                                         goto fail;
1229                                 }
1230                         }
1231
1232                         if (context->user)
1233                                 if (enforce_user(context, uid) < 0) {
1234                                         r = EXIT_USER;
1235                                         goto fail;
1236                                 }
1237
1238                         /* PR_GET_SECUREBITS is not priviliged, while
1239                          * PR_SET_SECUREBITS is. So to suppress
1240                          * potential EPERMs we'll try not to call
1241                          * PR_SET_SECUREBITS unless necessary. */
1242                         if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1243                                 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1244                                         r = EXIT_SECUREBITS;
1245                                         goto fail;
1246                                 }
1247
1248                         if (context->capabilities)
1249                                 if (cap_set_proc(context->capabilities) < 0) {
1250                                         r = EXIT_CAPABILITIES;
1251                                         goto fail;
1252                                 }
1253                 }
1254
1255                 if (!(our_env = new0(char*, 7))) {
1256                         r = EXIT_MEMORY;
1257                         goto fail;
1258                 }
1259
1260                 if (n_fds > 0)
1261                         if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1262                             asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1263                                 r = EXIT_MEMORY;
1264                                 goto fail;
1265                         }
1266
1267                 if (home)
1268                         if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1269                                 r = EXIT_MEMORY;
1270                                 goto fail;
1271                         }
1272
1273                 if (username)
1274                         if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1275                             asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1276                                 r = EXIT_MEMORY;
1277                                 goto fail;
1278                         }
1279
1280                 if (is_terminal_input(context->std_input) ||
1281                     context->std_output == EXEC_OUTPUT_TTY ||
1282                     context->std_error == EXEC_OUTPUT_TTY)
1283                         if (!(our_env[n_env++] = strdup(default_term_for_tty(tty_path(context))))) {
1284                                 r = EXIT_MEMORY;
1285                                 goto fail;
1286                         }
1287
1288                 assert(n_env <= 7);
1289
1290                 if (!(final_env = strv_env_merge(
1291                                       4,
1292                                       environment,
1293                                       our_env,
1294                                       context->environment,
1295                                       pam_env,
1296                                       NULL))) {
1297                         r = EXIT_MEMORY;
1298                         goto fail;
1299                 }
1300
1301                 if (!(final_argv = replace_env_argv(argv, final_env))) {
1302                         r = EXIT_MEMORY;
1303                         goto fail;
1304                 }
1305
1306                 execve(command->path, final_argv, final_env);
1307                 r = EXIT_EXEC;
1308
1309         fail:
1310                 strv_free(our_env);
1311                 strv_free(final_env);
1312                 strv_free(pam_env);
1313                 strv_free(final_argv);
1314
1315                 if (saved_stdin >= 0)
1316                         close_nointr_nofail(saved_stdin);
1317
1318                 if (saved_stdout >= 0)
1319                         close_nointr_nofail(saved_stdout);
1320
1321                 _exit(r);
1322         }
1323
1324         /* We add the new process to the cgroup both in the child (so
1325          * that we can be sure that no user code is ever executed
1326          * outside of the cgroup) and in the parent (so that we can be
1327          * sure that when we kill the cgroup the process will be
1328          * killed too). */
1329         if (cgroup_bondings)
1330                 cgroup_bonding_install_list(cgroup_bondings, pid);
1331
1332         log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1333
1334         exec_status_start(&command->exec_status, pid);
1335
1336         *ret = pid;
1337         return 0;
1338 }
1339
1340 void exec_context_init(ExecContext *c) {
1341         assert(c);
1342
1343         c->umask = 0002;
1344         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1345         c->cpu_sched_policy = SCHED_OTHER;
1346         c->syslog_priority = LOG_DAEMON|LOG_INFO;
1347         c->syslog_level_prefix = true;
1348         c->mount_flags = MS_SHARED;
1349         c->kill_signal = SIGTERM;
1350 }
1351
1352 void exec_context_done(ExecContext *c) {
1353         unsigned l;
1354
1355         assert(c);
1356
1357         strv_free(c->environment);
1358         c->environment = NULL;
1359
1360         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1361                 free(c->rlimit[l]);
1362                 c->rlimit[l] = NULL;
1363         }
1364
1365         free(c->working_directory);
1366         c->working_directory = NULL;
1367         free(c->root_directory);
1368         c->root_directory = NULL;
1369
1370         free(c->tty_path);
1371         c->tty_path = NULL;
1372
1373         free(c->tcpwrap_name);
1374         c->tcpwrap_name = NULL;
1375
1376         free(c->syslog_identifier);
1377         c->syslog_identifier = NULL;
1378
1379         free(c->user);
1380         c->user = NULL;
1381
1382         free(c->group);
1383         c->group = NULL;
1384
1385         strv_free(c->supplementary_groups);
1386         c->supplementary_groups = NULL;
1387
1388         free(c->pam_name);
1389         c->pam_name = NULL;
1390
1391         if (c->capabilities) {
1392                 cap_free(c->capabilities);
1393                 c->capabilities = NULL;
1394         }
1395
1396         strv_free(c->read_only_dirs);
1397         c->read_only_dirs = NULL;
1398
1399         strv_free(c->read_write_dirs);
1400         c->read_write_dirs = NULL;
1401
1402         strv_free(c->inaccessible_dirs);
1403         c->inaccessible_dirs = NULL;
1404
1405         if (c->cpuset)
1406                 CPU_FREE(c->cpuset);
1407 }
1408
1409 void exec_command_done(ExecCommand *c) {
1410         assert(c);
1411
1412         free(c->path);
1413         c->path = NULL;
1414
1415         strv_free(c->argv);
1416         c->argv = NULL;
1417 }
1418
1419 void exec_command_done_array(ExecCommand *c, unsigned n) {
1420         unsigned i;
1421
1422         for (i = 0; i < n; i++)
1423                 exec_command_done(c+i);
1424 }
1425
1426 void exec_command_free_list(ExecCommand *c) {
1427         ExecCommand *i;
1428
1429         while ((i = c)) {
1430                 LIST_REMOVE(ExecCommand, command, c, i);
1431                 exec_command_done(i);
1432                 free(i);
1433         }
1434 }
1435
1436 void exec_command_free_array(ExecCommand **c, unsigned n) {
1437         unsigned i;
1438
1439         for (i = 0; i < n; i++) {
1440                 exec_command_free_list(c[i]);
1441                 c[i] = NULL;
1442         }
1443 }
1444
1445 static void strv_fprintf(FILE *f, char **l) {
1446         char **g;
1447
1448         assert(f);
1449
1450         STRV_FOREACH(g, l)
1451                 fprintf(f, " %s", *g);
1452 }
1453
1454 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1455         char ** e;
1456         unsigned i;
1457
1458         assert(c);
1459         assert(f);
1460
1461         if (!prefix)
1462                 prefix = "";
1463
1464         fprintf(f,
1465                 "%sUMask: %04o\n"
1466                 "%sWorkingDirectory: %s\n"
1467                 "%sRootDirectory: %s\n"
1468                 "%sNonBlocking: %s\n"
1469                 "%sPrivateTmp: %s\n",
1470                 prefix, c->umask,
1471                 prefix, c->working_directory ? c->working_directory : "/",
1472                 prefix, c->root_directory ? c->root_directory : "/",
1473                 prefix, yes_no(c->non_blocking),
1474                 prefix, yes_no(c->private_tmp));
1475
1476         if (c->environment)
1477                 for (e = c->environment; *e; e++)
1478                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1479
1480         if (c->tcpwrap_name)
1481                 fprintf(f,
1482                         "%sTCPWrapName: %s\n",
1483                         prefix, c->tcpwrap_name);
1484
1485         if (c->nice_set)
1486                 fprintf(f,
1487                         "%sNice: %i\n",
1488                         prefix, c->nice);
1489
1490         if (c->oom_score_adjust_set)
1491                 fprintf(f,
1492                         "%sOOMScoreAdjust: %i\n",
1493                         prefix, c->oom_score_adjust);
1494
1495         for (i = 0; i < RLIM_NLIMITS; i++)
1496                 if (c->rlimit[i])
1497                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1498
1499         if (c->ioprio_set)
1500                 fprintf(f,
1501                         "%sIOSchedulingClass: %s\n"
1502                         "%sIOPriority: %i\n",
1503                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1504                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1505
1506         if (c->cpu_sched_set)
1507                 fprintf(f,
1508                         "%sCPUSchedulingPolicy: %s\n"
1509                         "%sCPUSchedulingPriority: %i\n"
1510                         "%sCPUSchedulingResetOnFork: %s\n",
1511                         prefix, sched_policy_to_string(c->cpu_sched_policy),
1512                         prefix, c->cpu_sched_priority,
1513                         prefix, yes_no(c->cpu_sched_reset_on_fork));
1514
1515         if (c->cpuset) {
1516                 fprintf(f, "%sCPUAffinity:", prefix);
1517                 for (i = 0; i < c->cpuset_ncpus; i++)
1518                         if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1519                                 fprintf(f, " %i", i);
1520                 fputs("\n", f);
1521         }
1522
1523         if (c->timer_slack_nsec_set)
1524                 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1525
1526         fprintf(f,
1527                 "%sStandardInput: %s\n"
1528                 "%sStandardOutput: %s\n"
1529                 "%sStandardError: %s\n",
1530                 prefix, exec_input_to_string(c->std_input),
1531                 prefix, exec_output_to_string(c->std_output),
1532                 prefix, exec_output_to_string(c->std_error));
1533
1534         if (c->tty_path)
1535                 fprintf(f,
1536                         "%sTTYPath: %s\n",
1537                         prefix, c->tty_path);
1538
1539         if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1540             c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1541                 fprintf(f,
1542                         "%sSyslogFacility: %s\n"
1543                         "%sSyslogLevel: %s\n",
1544                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1545                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1546
1547         if (c->capabilities) {
1548                 char *t;
1549                 if ((t = cap_to_text(c->capabilities, NULL))) {
1550                         fprintf(f, "%sCapabilities: %s\n",
1551                                 prefix, t);
1552                         cap_free(t);
1553                 }
1554         }
1555
1556         if (c->secure_bits)
1557                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1558                         prefix,
1559                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1560                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1561                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1562                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1563                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1564                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1565
1566         if (c->capability_bounding_set_drop) {
1567                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1568
1569                 for (i = 0; i <= CAP_LAST_CAP; i++)
1570                         if (c->capability_bounding_set_drop & (1 << i)) {
1571                                 char *t;
1572
1573                                 if ((t = cap_to_name(i))) {
1574                                         fprintf(f, " %s", t);
1575                                         free(t);
1576                                 }
1577                         }
1578
1579                 fputs("\n", f);
1580         }
1581
1582         if (c->user)
1583                 fprintf(f, "%sUser: %s\n", prefix, c->user);
1584         if (c->group)
1585                 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1586
1587         if (strv_length(c->supplementary_groups) > 0) {
1588                 fprintf(f, "%sSupplementaryGroups:", prefix);
1589                 strv_fprintf(f, c->supplementary_groups);
1590                 fputs("\n", f);
1591         }
1592
1593         if (c->pam_name)
1594                 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1595
1596         if (strv_length(c->read_write_dirs) > 0) {
1597                 fprintf(f, "%sReadWriteDirs:", prefix);
1598                 strv_fprintf(f, c->read_write_dirs);
1599                 fputs("\n", f);
1600         }
1601
1602         if (strv_length(c->read_only_dirs) > 0) {
1603                 fprintf(f, "%sReadOnlyDirs:", prefix);
1604                 strv_fprintf(f, c->read_only_dirs);
1605                 fputs("\n", f);
1606         }
1607
1608         if (strv_length(c->inaccessible_dirs) > 0) {
1609                 fprintf(f, "%sInaccessibleDirs:", prefix);
1610                 strv_fprintf(f, c->inaccessible_dirs);
1611                 fputs("\n", f);
1612         }
1613
1614         fprintf(f,
1615                 "%sKillMode: %s\n"
1616                 "%sKillSignal: SIG%s\n",
1617                 prefix, kill_mode_to_string(c->kill_mode),
1618                 prefix, signal_to_string(c->kill_signal));
1619
1620         if (c->utmp_id)
1621                 fprintf(f,
1622                         "%sUtmpIdentifier: %s\n",
1623                         prefix, c->utmp_id);
1624 }
1625
1626 void exec_status_start(ExecStatus *s, pid_t pid) {
1627         assert(s);
1628
1629         zero(*s);
1630         s->pid = pid;
1631         dual_timestamp_get(&s->start_timestamp);
1632 }
1633
1634 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status, const char *utmp_id) {
1635         assert(s);
1636
1637         if ((s->pid && s->pid != pid) ||
1638             !s->start_timestamp.realtime <= 0)
1639                 zero(*s);
1640
1641         s->pid = pid;
1642         dual_timestamp_get(&s->exit_timestamp);
1643
1644         s->code = code;
1645         s->status = status;
1646
1647         if (utmp_id)
1648                 utmp_put_dead_process(utmp_id, pid, code, status);
1649 }
1650
1651 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1652         char buf[FORMAT_TIMESTAMP_MAX];
1653
1654         assert(s);
1655         assert(f);
1656
1657         if (!prefix)
1658                 prefix = "";
1659
1660         if (s->pid <= 0)
1661                 return;
1662
1663         fprintf(f,
1664                 "%sPID: %lu\n",
1665                 prefix, (unsigned long) s->pid);
1666
1667         if (s->start_timestamp.realtime > 0)
1668                 fprintf(f,
1669                         "%sStart Timestamp: %s\n",
1670                         prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1671
1672         if (s->exit_timestamp.realtime > 0)
1673                 fprintf(f,
1674                         "%sExit Timestamp: %s\n"
1675                         "%sExit Code: %s\n"
1676                         "%sExit Status: %i\n",
1677                         prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1678                         prefix, sigchld_code_to_string(s->code),
1679                         prefix, s->status);
1680 }
1681
1682 char *exec_command_line(char **argv) {
1683         size_t k;
1684         char *n, *p, **a;
1685         bool first = true;
1686
1687         assert(argv);
1688
1689         k = 1;
1690         STRV_FOREACH(a, argv)
1691                 k += strlen(*a)+3;
1692
1693         if (!(n = new(char, k)))
1694                 return NULL;
1695
1696         p = n;
1697         STRV_FOREACH(a, argv) {
1698
1699                 if (!first)
1700                         *(p++) = ' ';
1701                 else
1702                         first = false;
1703
1704                 if (strpbrk(*a, WHITESPACE)) {
1705                         *(p++) = '\'';
1706                         p = stpcpy(p, *a);
1707                         *(p++) = '\'';
1708                 } else
1709                         p = stpcpy(p, *a);
1710
1711         }
1712
1713         *p = 0;
1714
1715         /* FIXME: this doesn't really handle arguments that have
1716          * spaces and ticks in them */
1717
1718         return n;
1719 }
1720
1721 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1722         char *p2;
1723         const char *prefix2;
1724
1725         char *cmd;
1726
1727         assert(c);
1728         assert(f);
1729
1730         if (!prefix)
1731                 prefix = "";
1732         p2 = strappend(prefix, "\t");
1733         prefix2 = p2 ? p2 : prefix;
1734
1735         cmd = exec_command_line(c->argv);
1736
1737         fprintf(f,
1738                 "%sCommand Line: %s\n",
1739                 prefix, cmd ? cmd : strerror(ENOMEM));
1740
1741         free(cmd);
1742
1743         exec_status_dump(&c->exec_status, f, prefix2);
1744
1745         free(p2);
1746 }
1747
1748 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1749         assert(f);
1750
1751         if (!prefix)
1752                 prefix = "";
1753
1754         LIST_FOREACH(command, c, c)
1755                 exec_command_dump(c, f, prefix);
1756 }
1757
1758 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1759         ExecCommand *end;
1760
1761         assert(l);
1762         assert(e);
1763
1764         if (*l) {
1765                 /* It's kinda important that we keep the order here */
1766                 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1767                 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1768         } else
1769               *l = e;
1770 }
1771
1772 int exec_command_set(ExecCommand *c, const char *path, ...) {
1773         va_list ap;
1774         char **l, *p;
1775
1776         assert(c);
1777         assert(path);
1778
1779         va_start(ap, path);
1780         l = strv_new_ap(path, ap);
1781         va_end(ap);
1782
1783         if (!l)
1784                 return -ENOMEM;
1785
1786         if (!(p = strdup(path))) {
1787                 strv_free(l);
1788                 return -ENOMEM;
1789         }
1790
1791         free(c->path);
1792         c->path = p;
1793
1794         strv_free(c->argv);
1795         c->argv = l;
1796
1797         return 0;
1798 }
1799
1800 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1801         [EXEC_INPUT_NULL] = "null",
1802         [EXEC_INPUT_TTY] = "tty",
1803         [EXEC_INPUT_TTY_FORCE] = "tty-force",
1804         [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1805         [EXEC_INPUT_SOCKET] = "socket"
1806 };
1807
1808 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
1809
1810 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1811         [EXEC_OUTPUT_INHERIT] = "inherit",
1812         [EXEC_OUTPUT_NULL] = "null",
1813         [EXEC_OUTPUT_TTY] = "tty",
1814         [EXEC_OUTPUT_SYSLOG] = "syslog",
1815         [EXEC_OUTPUT_KMSG] = "kmsg",
1816         [EXEC_OUTPUT_SOCKET] = "socket"
1817 };
1818
1819 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1820
1821 static const char* const kill_mode_table[_KILL_MODE_MAX] = {
1822         [KILL_CONTROL_GROUP] = "control-group",
1823         [KILL_PROCESS_GROUP] = "process-group",
1824         [KILL_PROCESS] = "process",
1825         [KILL_NONE] = "none"
1826 };
1827
1828 DEFINE_STRING_TABLE_LOOKUP(kill_mode, KillMode);
1829
1830 static const char* const kill_who_table[_KILL_WHO_MAX] = {
1831         [KILL_MAIN] = "main",
1832         [KILL_CONTROL] = "control",
1833         [KILL_ALL] = "all"
1834 };
1835
1836 DEFINE_STRING_TABLE_LOOKUP(kill_who, KillWho);