chiark / gitweb /
man: properly refer to $MAINPID instead of $(MAINPID) which doesnt work anymore
[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*, 6))) {
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                 assert(n_env <= 6);
1281
1282                 if (!(final_env = strv_env_merge(
1283                                       4,
1284                                       environment,
1285                                       our_env,
1286                                       context->environment,
1287                                       pam_env,
1288                                       NULL))) {
1289                         r = EXIT_MEMORY;
1290                         goto fail;
1291                 }
1292
1293                 if (!(final_argv = replace_env_argv(argv, final_env))) {
1294                         r = EXIT_MEMORY;
1295                         goto fail;
1296                 }
1297
1298                 execve(command->path, final_argv, final_env);
1299                 r = EXIT_EXEC;
1300
1301         fail:
1302                 strv_free(our_env);
1303                 strv_free(final_env);
1304                 strv_free(pam_env);
1305                 strv_free(final_argv);
1306
1307                 if (saved_stdin >= 0)
1308                         close_nointr_nofail(saved_stdin);
1309
1310                 if (saved_stdout >= 0)
1311                         close_nointr_nofail(saved_stdout);
1312
1313                 _exit(r);
1314         }
1315
1316         /* We add the new process to the cgroup both in the child (so
1317          * that we can be sure that no user code is ever executed
1318          * outside of the cgroup) and in the parent (so that we can be
1319          * sure that when we kill the cgroup the process will be
1320          * killed too). */
1321         if (cgroup_bondings)
1322                 cgroup_bonding_install_list(cgroup_bondings, pid);
1323
1324         log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1325
1326         exec_status_start(&command->exec_status, pid);
1327
1328         *ret = pid;
1329         return 0;
1330 }
1331
1332 void exec_context_init(ExecContext *c) {
1333         assert(c);
1334
1335         c->umask = 0002;
1336         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1337         c->cpu_sched_policy = SCHED_OTHER;
1338         c->syslog_priority = LOG_DAEMON|LOG_INFO;
1339         c->syslog_level_prefix = true;
1340         c->mount_flags = MS_SHARED;
1341         c->kill_signal = SIGTERM;
1342 }
1343
1344 void exec_context_done(ExecContext *c) {
1345         unsigned l;
1346
1347         assert(c);
1348
1349         strv_free(c->environment);
1350         c->environment = NULL;
1351
1352         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1353                 free(c->rlimit[l]);
1354                 c->rlimit[l] = NULL;
1355         }
1356
1357         free(c->working_directory);
1358         c->working_directory = NULL;
1359         free(c->root_directory);
1360         c->root_directory = NULL;
1361
1362         free(c->tty_path);
1363         c->tty_path = NULL;
1364
1365         free(c->tcpwrap_name);
1366         c->tcpwrap_name = NULL;
1367
1368         free(c->syslog_identifier);
1369         c->syslog_identifier = NULL;
1370
1371         free(c->user);
1372         c->user = NULL;
1373
1374         free(c->group);
1375         c->group = NULL;
1376
1377         strv_free(c->supplementary_groups);
1378         c->supplementary_groups = NULL;
1379
1380         free(c->pam_name);
1381         c->pam_name = NULL;
1382
1383         if (c->capabilities) {
1384                 cap_free(c->capabilities);
1385                 c->capabilities = NULL;
1386         }
1387
1388         strv_free(c->read_only_dirs);
1389         c->read_only_dirs = NULL;
1390
1391         strv_free(c->read_write_dirs);
1392         c->read_write_dirs = NULL;
1393
1394         strv_free(c->inaccessible_dirs);
1395         c->inaccessible_dirs = NULL;
1396
1397         if (c->cpuset)
1398                 CPU_FREE(c->cpuset);
1399 }
1400
1401 void exec_command_done(ExecCommand *c) {
1402         assert(c);
1403
1404         free(c->path);
1405         c->path = NULL;
1406
1407         strv_free(c->argv);
1408         c->argv = NULL;
1409 }
1410
1411 void exec_command_done_array(ExecCommand *c, unsigned n) {
1412         unsigned i;
1413
1414         for (i = 0; i < n; i++)
1415                 exec_command_done(c+i);
1416 }
1417
1418 void exec_command_free_list(ExecCommand *c) {
1419         ExecCommand *i;
1420
1421         while ((i = c)) {
1422                 LIST_REMOVE(ExecCommand, command, c, i);
1423                 exec_command_done(i);
1424                 free(i);
1425         }
1426 }
1427
1428 void exec_command_free_array(ExecCommand **c, unsigned n) {
1429         unsigned i;
1430
1431         for (i = 0; i < n; i++) {
1432                 exec_command_free_list(c[i]);
1433                 c[i] = NULL;
1434         }
1435 }
1436
1437 static void strv_fprintf(FILE *f, char **l) {
1438         char **g;
1439
1440         assert(f);
1441
1442         STRV_FOREACH(g, l)
1443                 fprintf(f, " %s", *g);
1444 }
1445
1446 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1447         char ** e;
1448         unsigned i;
1449
1450         assert(c);
1451         assert(f);
1452
1453         if (!prefix)
1454                 prefix = "";
1455
1456         fprintf(f,
1457                 "%sUMask: %04o\n"
1458                 "%sWorkingDirectory: %s\n"
1459                 "%sRootDirectory: %s\n"
1460                 "%sNonBlocking: %s\n"
1461                 "%sPrivateTmp: %s\n",
1462                 prefix, c->umask,
1463                 prefix, c->working_directory ? c->working_directory : "/",
1464                 prefix, c->root_directory ? c->root_directory : "/",
1465                 prefix, yes_no(c->non_blocking),
1466                 prefix, yes_no(c->private_tmp));
1467
1468         if (c->environment)
1469                 for (e = c->environment; *e; e++)
1470                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1471
1472         if (c->tcpwrap_name)
1473                 fprintf(f,
1474                         "%sTCPWrapName: %s\n",
1475                         prefix, c->tcpwrap_name);
1476
1477         if (c->nice_set)
1478                 fprintf(f,
1479                         "%sNice: %i\n",
1480                         prefix, c->nice);
1481
1482         if (c->oom_score_adjust_set)
1483                 fprintf(f,
1484                         "%sOOMScoreAdjust: %i\n",
1485                         prefix, c->oom_score_adjust);
1486
1487         for (i = 0; i < RLIM_NLIMITS; i++)
1488                 if (c->rlimit[i])
1489                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1490
1491         if (c->ioprio_set)
1492                 fprintf(f,
1493                         "%sIOSchedulingClass: %s\n"
1494                         "%sIOPriority: %i\n",
1495                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1496                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1497
1498         if (c->cpu_sched_set)
1499                 fprintf(f,
1500                         "%sCPUSchedulingPolicy: %s\n"
1501                         "%sCPUSchedulingPriority: %i\n"
1502                         "%sCPUSchedulingResetOnFork: %s\n",
1503                         prefix, sched_policy_to_string(c->cpu_sched_policy),
1504                         prefix, c->cpu_sched_priority,
1505                         prefix, yes_no(c->cpu_sched_reset_on_fork));
1506
1507         if (c->cpuset) {
1508                 fprintf(f, "%sCPUAffinity:", prefix);
1509                 for (i = 0; i < c->cpuset_ncpus; i++)
1510                         if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1511                                 fprintf(f, " %i", i);
1512                 fputs("\n", f);
1513         }
1514
1515         if (c->timer_slack_nsec_set)
1516                 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1517
1518         fprintf(f,
1519                 "%sStandardInput: %s\n"
1520                 "%sStandardOutput: %s\n"
1521                 "%sStandardError: %s\n",
1522                 prefix, exec_input_to_string(c->std_input),
1523                 prefix, exec_output_to_string(c->std_output),
1524                 prefix, exec_output_to_string(c->std_error));
1525
1526         if (c->tty_path)
1527                 fprintf(f,
1528                         "%sTTYPath: %s\n",
1529                         prefix, c->tty_path);
1530
1531         if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1532             c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1533                 fprintf(f,
1534                         "%sSyslogFacility: %s\n"
1535                         "%sSyslogLevel: %s\n",
1536                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1537                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1538
1539         if (c->capabilities) {
1540                 char *t;
1541                 if ((t = cap_to_text(c->capabilities, NULL))) {
1542                         fprintf(f, "%sCapabilities: %s\n",
1543                                 prefix, t);
1544                         cap_free(t);
1545                 }
1546         }
1547
1548         if (c->secure_bits)
1549                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1550                         prefix,
1551                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1552                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1553                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1554                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1555                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1556                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1557
1558         if (c->capability_bounding_set_drop) {
1559                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1560
1561                 for (i = 0; i <= CAP_LAST_CAP; i++)
1562                         if (c->capability_bounding_set_drop & (1 << i)) {
1563                                 char *t;
1564
1565                                 if ((t = cap_to_name(i))) {
1566                                         fprintf(f, " %s", t);
1567                                         free(t);
1568                                 }
1569                         }
1570
1571                 fputs("\n", f);
1572         }
1573
1574         if (c->user)
1575                 fprintf(f, "%sUser: %s\n", prefix, c->user);
1576         if (c->group)
1577                 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1578
1579         if (strv_length(c->supplementary_groups) > 0) {
1580                 fprintf(f, "%sSupplementaryGroups:", prefix);
1581                 strv_fprintf(f, c->supplementary_groups);
1582                 fputs("\n", f);
1583         }
1584
1585         if (c->pam_name)
1586                 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1587
1588         if (strv_length(c->read_write_dirs) > 0) {
1589                 fprintf(f, "%sReadWriteDirs:", prefix);
1590                 strv_fprintf(f, c->read_write_dirs);
1591                 fputs("\n", f);
1592         }
1593
1594         if (strv_length(c->read_only_dirs) > 0) {
1595                 fprintf(f, "%sReadOnlyDirs:", prefix);
1596                 strv_fprintf(f, c->read_only_dirs);
1597                 fputs("\n", f);
1598         }
1599
1600         if (strv_length(c->inaccessible_dirs) > 0) {
1601                 fprintf(f, "%sInaccessibleDirs:", prefix);
1602                 strv_fprintf(f, c->inaccessible_dirs);
1603                 fputs("\n", f);
1604         }
1605
1606         fprintf(f,
1607                 "%sKillMode: %s\n"
1608                 "%sKillSignal: SIG%s\n",
1609                 prefix, kill_mode_to_string(c->kill_mode),
1610                 prefix, signal_to_string(c->kill_signal));
1611
1612         if (c->utmp_id)
1613                 fprintf(f,
1614                         "%sUtmpIdentifier: %s\n",
1615                         prefix, c->utmp_id);
1616 }
1617
1618 void exec_status_start(ExecStatus *s, pid_t pid) {
1619         assert(s);
1620
1621         zero(*s);
1622         s->pid = pid;
1623         dual_timestamp_get(&s->start_timestamp);
1624 }
1625
1626 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status, const char *utmp_id) {
1627         assert(s);
1628
1629         if ((s->pid && s->pid != pid) ||
1630             !s->start_timestamp.realtime <= 0)
1631                 zero(*s);
1632
1633         s->pid = pid;
1634         dual_timestamp_get(&s->exit_timestamp);
1635
1636         s->code = code;
1637         s->status = status;
1638
1639         if (utmp_id)
1640                 utmp_put_dead_process(utmp_id, pid, code, status);
1641 }
1642
1643 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1644         char buf[FORMAT_TIMESTAMP_MAX];
1645
1646         assert(s);
1647         assert(f);
1648
1649         if (!prefix)
1650                 prefix = "";
1651
1652         if (s->pid <= 0)
1653                 return;
1654
1655         fprintf(f,
1656                 "%sPID: %lu\n",
1657                 prefix, (unsigned long) s->pid);
1658
1659         if (s->start_timestamp.realtime > 0)
1660                 fprintf(f,
1661                         "%sStart Timestamp: %s\n",
1662                         prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1663
1664         if (s->exit_timestamp.realtime > 0)
1665                 fprintf(f,
1666                         "%sExit Timestamp: %s\n"
1667                         "%sExit Code: %s\n"
1668                         "%sExit Status: %i\n",
1669                         prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1670                         prefix, sigchld_code_to_string(s->code),
1671                         prefix, s->status);
1672 }
1673
1674 char *exec_command_line(char **argv) {
1675         size_t k;
1676         char *n, *p, **a;
1677         bool first = true;
1678
1679         assert(argv);
1680
1681         k = 1;
1682         STRV_FOREACH(a, argv)
1683                 k += strlen(*a)+3;
1684
1685         if (!(n = new(char, k)))
1686                 return NULL;
1687
1688         p = n;
1689         STRV_FOREACH(a, argv) {
1690
1691                 if (!first)
1692                         *(p++) = ' ';
1693                 else
1694                         first = false;
1695
1696                 if (strpbrk(*a, WHITESPACE)) {
1697                         *(p++) = '\'';
1698                         p = stpcpy(p, *a);
1699                         *(p++) = '\'';
1700                 } else
1701                         p = stpcpy(p, *a);
1702
1703         }
1704
1705         *p = 0;
1706
1707         /* FIXME: this doesn't really handle arguments that have
1708          * spaces and ticks in them */
1709
1710         return n;
1711 }
1712
1713 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1714         char *p2;
1715         const char *prefix2;
1716
1717         char *cmd;
1718
1719         assert(c);
1720         assert(f);
1721
1722         if (!prefix)
1723                 prefix = "";
1724         p2 = strappend(prefix, "\t");
1725         prefix2 = p2 ? p2 : prefix;
1726
1727         cmd = exec_command_line(c->argv);
1728
1729         fprintf(f,
1730                 "%sCommand Line: %s\n",
1731                 prefix, cmd ? cmd : strerror(ENOMEM));
1732
1733         free(cmd);
1734
1735         exec_status_dump(&c->exec_status, f, prefix2);
1736
1737         free(p2);
1738 }
1739
1740 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1741         assert(f);
1742
1743         if (!prefix)
1744                 prefix = "";
1745
1746         LIST_FOREACH(command, c, c)
1747                 exec_command_dump(c, f, prefix);
1748 }
1749
1750 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1751         ExecCommand *end;
1752
1753         assert(l);
1754         assert(e);
1755
1756         if (*l) {
1757                 /* It's kinda important that we keep the order here */
1758                 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1759                 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1760         } else
1761               *l = e;
1762 }
1763
1764 int exec_command_set(ExecCommand *c, const char *path, ...) {
1765         va_list ap;
1766         char **l, *p;
1767
1768         assert(c);
1769         assert(path);
1770
1771         va_start(ap, path);
1772         l = strv_new_ap(path, ap);
1773         va_end(ap);
1774
1775         if (!l)
1776                 return -ENOMEM;
1777
1778         if (!(p = strdup(path))) {
1779                 strv_free(l);
1780                 return -ENOMEM;
1781         }
1782
1783         free(c->path);
1784         c->path = p;
1785
1786         strv_free(c->argv);
1787         c->argv = l;
1788
1789         return 0;
1790 }
1791
1792 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1793         [EXEC_INPUT_NULL] = "null",
1794         [EXEC_INPUT_TTY] = "tty",
1795         [EXEC_INPUT_TTY_FORCE] = "tty-force",
1796         [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1797         [EXEC_INPUT_SOCKET] = "socket"
1798 };
1799
1800 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1801         [EXEC_OUTPUT_INHERIT] = "inherit",
1802         [EXEC_OUTPUT_NULL] = "null",
1803         [EXEC_OUTPUT_TTY] = "tty",
1804         [EXEC_OUTPUT_SYSLOG] = "syslog",
1805         [EXEC_OUTPUT_KMSG] = "kmsg",
1806         [EXEC_OUTPUT_SOCKET] = "socket"
1807 };
1808
1809 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1810
1811 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);