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