chiark / gitweb /
install: various improvements
[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)) < 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                 if (!context->same_pgrp)
972                         if (setsid() < 0) {
973                                 r = EXIT_SETSID;
974                                 goto fail;
975                         }
976
977                 if (context->tcpwrap_name) {
978                         if (socket_fd >= 0)
979                                 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
980                                         r = EXIT_TCPWRAP;
981                                         goto fail;
982                                 }
983
984                         for (i = 0; i < (int) n_fds; i++) {
985                                 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
986                                         r = EXIT_TCPWRAP;
987                                         goto fail;
988                                 }
989                         }
990                 }
991
992                 /* We skip the confirmation step if we shall not apply the TTY */
993                 if (confirm_spawn &&
994                     (!is_terminal_input(context->std_input) || apply_tty_stdin)) {
995                         char response;
996
997                         /* Set up terminal for the question */
998                         if ((r = setup_confirm_stdio(context,
999                                                      &saved_stdin, &saved_stdout)))
1000                                 goto fail;
1001
1002                         /* Now ask the question. */
1003                         if (!(line = exec_command_line(argv))) {
1004                                 r = EXIT_MEMORY;
1005                                 goto fail;
1006                         }
1007
1008                         r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
1009                         free(line);
1010
1011                         if (r < 0 || response == 'n') {
1012                                 r = EXIT_CONFIRM;
1013                                 goto fail;
1014                         } else if (response == 's') {
1015                                 r = 0;
1016                                 goto fail;
1017                         }
1018
1019                         /* Release terminal for the question */
1020                         if ((r = restore_confirm_stdio(context,
1021                                                        &saved_stdin, &saved_stdout,
1022                                                        &keep_stdin, &keep_stdout)))
1023                                 goto fail;
1024                 }
1025
1026                 if (!keep_stdin)
1027                         if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1028                                 r = EXIT_STDIN;
1029                                 goto fail;
1030                         }
1031
1032                 if (!keep_stdout)
1033                         if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1034                                 r = EXIT_STDOUT;
1035                                 goto fail;
1036                         }
1037
1038                 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1039                         r = EXIT_STDERR;
1040                         goto fail;
1041                 }
1042
1043                 if (cgroup_bondings)
1044                         if ((r = cgroup_bonding_install_list(cgroup_bondings, 0)) < 0) {
1045                                 r = EXIT_CGROUP;
1046                                 goto fail;
1047                         }
1048
1049                 if (context->oom_adjust_set) {
1050                         char t[16];
1051
1052                         snprintf(t, sizeof(t), "%i", context->oom_adjust);
1053                         char_array_0(t);
1054
1055                         if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1056                                 r = EXIT_OOM_ADJUST;
1057                                 goto fail;
1058                         }
1059                 }
1060
1061                 if (context->nice_set)
1062                         if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1063                                 r = EXIT_NICE;
1064                                 goto fail;
1065                         }
1066
1067                 if (context->cpu_sched_set) {
1068                         struct sched_param param;
1069
1070                         zero(param);
1071                         param.sched_priority = context->cpu_sched_priority;
1072
1073                         if (sched_setscheduler(0, context->cpu_sched_policy |
1074                                                (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), &param) < 0) {
1075                                 r = EXIT_SETSCHEDULER;
1076                                 goto fail;
1077                         }
1078                 }
1079
1080                 if (context->cpuset)
1081                         if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1082                                 r = EXIT_CPUAFFINITY;
1083                                 goto fail;
1084                         }
1085
1086                 if (context->ioprio_set)
1087                         if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1088                                 r = EXIT_IOPRIO;
1089                                 goto fail;
1090                         }
1091
1092                 if (context->timer_slack_nsec_set)
1093                         if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1094                                 r = EXIT_TIMERSLACK;
1095                                 goto fail;
1096                         }
1097
1098                 if (context->user) {
1099                         username = context->user;
1100                         if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1101                                 r = EXIT_USER;
1102                                 goto fail;
1103                         }
1104
1105                         if (is_terminal_input(context->std_input))
1106                                 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1107                                         r = EXIT_STDIN;
1108                                         goto fail;
1109                                 }
1110                 }
1111
1112 #ifdef HAVE_PAM
1113                 if (context->pam_name && username) {
1114                         /* Make sure no fds leak into the PAM
1115                          * supervisor process. We will call this later
1116                          * on again to make sure that any fds leaked
1117                          * by the PAM modules get closed before our
1118                          * exec(). */
1119                         if (close_all_fds(fds, n_fds) < 0) {
1120                                 r = EXIT_FDS;
1121                                 goto fail;
1122                         }
1123
1124                         if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1125                                 r = EXIT_PAM;
1126                                 goto fail;
1127                         }
1128                 }
1129 #endif
1130
1131                 if (apply_permissions)
1132                         if (enforce_groups(context, username, uid) < 0) {
1133                                 r = EXIT_GROUP;
1134                                 goto fail;
1135                         }
1136
1137                 umask(context->umask);
1138
1139                 if (strv_length(context->read_write_dirs) > 0 ||
1140                     strv_length(context->read_only_dirs) > 0 ||
1141                     strv_length(context->inaccessible_dirs) > 0 ||
1142                     context->mount_flags != MS_SHARED ||
1143                     context->private_tmp)
1144                         if ((r = setup_namespace(
1145                                              context->read_write_dirs,
1146                                              context->read_only_dirs,
1147                                              context->inaccessible_dirs,
1148                                              context->private_tmp,
1149                                              context->mount_flags)) < 0)
1150                                 goto fail;
1151
1152                 if (apply_chroot) {
1153                         if (context->root_directory)
1154                                 if (chroot(context->root_directory) < 0) {
1155                                         r = EXIT_CHROOT;
1156                                         goto fail;
1157                                 }
1158
1159                         if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1160                                 r = EXIT_CHDIR;
1161                                 goto fail;
1162                         }
1163                 } else {
1164
1165                         char *d;
1166
1167                         if (asprintf(&d, "%s/%s",
1168                                      context->root_directory ? context->root_directory : "",
1169                                      context->working_directory ? context->working_directory : "") < 0) {
1170                                 r = EXIT_MEMORY;
1171                                 goto fail;
1172                         }
1173
1174                         if (chdir(d) < 0) {
1175                                 free(d);
1176                                 r = EXIT_CHDIR;
1177                                 goto fail;
1178                         }
1179
1180                         free(d);
1181                 }
1182
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 }
1312
1313 void exec_context_done(ExecContext *c) {
1314         unsigned l;
1315
1316         assert(c);
1317
1318         strv_free(c->environment);
1319         c->environment = NULL;
1320
1321         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1322                 free(c->rlimit[l]);
1323                 c->rlimit[l] = NULL;
1324         }
1325
1326         free(c->working_directory);
1327         c->working_directory = NULL;
1328         free(c->root_directory);
1329         c->root_directory = NULL;
1330
1331         free(c->tty_path);
1332         c->tty_path = NULL;
1333
1334         free(c->tcpwrap_name);
1335         c->tcpwrap_name = NULL;
1336
1337         free(c->syslog_identifier);
1338         c->syslog_identifier = NULL;
1339
1340         free(c->user);
1341         c->user = NULL;
1342
1343         free(c->group);
1344         c->group = NULL;
1345
1346         strv_free(c->supplementary_groups);
1347         c->supplementary_groups = NULL;
1348
1349         free(c->pam_name);
1350         c->pam_name = NULL;
1351
1352         if (c->capabilities) {
1353                 cap_free(c->capabilities);
1354                 c->capabilities = NULL;
1355         }
1356
1357         strv_free(c->read_only_dirs);
1358         c->read_only_dirs = NULL;
1359
1360         strv_free(c->read_write_dirs);
1361         c->read_write_dirs = NULL;
1362
1363         strv_free(c->inaccessible_dirs);
1364         c->inaccessible_dirs = NULL;
1365
1366         if (c->cpuset)
1367                 CPU_FREE(c->cpuset);
1368 }
1369
1370 void exec_command_done(ExecCommand *c) {
1371         assert(c);
1372
1373         free(c->path);
1374         c->path = NULL;
1375
1376         strv_free(c->argv);
1377         c->argv = NULL;
1378 }
1379
1380 void exec_command_done_array(ExecCommand *c, unsigned n) {
1381         unsigned i;
1382
1383         for (i = 0; i < n; i++)
1384                 exec_command_done(c+i);
1385 }
1386
1387 void exec_command_free_list(ExecCommand *c) {
1388         ExecCommand *i;
1389
1390         while ((i = c)) {
1391                 LIST_REMOVE(ExecCommand, command, c, i);
1392                 exec_command_done(i);
1393                 free(i);
1394         }
1395 }
1396
1397 void exec_command_free_array(ExecCommand **c, unsigned n) {
1398         unsigned i;
1399
1400         for (i = 0; i < n; i++) {
1401                 exec_command_free_list(c[i]);
1402                 c[i] = NULL;
1403         }
1404 }
1405
1406 static void strv_fprintf(FILE *f, char **l) {
1407         char **g;
1408
1409         assert(f);
1410
1411         STRV_FOREACH(g, l)
1412                 fprintf(f, " %s", *g);
1413 }
1414
1415 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1416         char ** e;
1417         unsigned i;
1418
1419         assert(c);
1420         assert(f);
1421
1422         if (!prefix)
1423                 prefix = "";
1424
1425         fprintf(f,
1426                 "%sUMask: %04o\n"
1427                 "%sWorkingDirectory: %s\n"
1428                 "%sRootDirectory: %s\n"
1429                 "%sNonBlocking: %s\n"
1430                 "%sPrivateTmp: %s\n",
1431                 prefix, c->umask,
1432                 prefix, c->working_directory ? c->working_directory : "/",
1433                 prefix, c->root_directory ? c->root_directory : "/",
1434                 prefix, yes_no(c->non_blocking),
1435                 prefix, yes_no(c->private_tmp));
1436
1437         if (c->environment)
1438                 for (e = c->environment; *e; e++)
1439                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1440
1441         if (c->tcpwrap_name)
1442                 fprintf(f,
1443                         "%sTCPWrapName: %s\n",
1444                         prefix, c->tcpwrap_name);
1445
1446         if (c->nice_set)
1447                 fprintf(f,
1448                         "%sNice: %i\n",
1449                         prefix, c->nice);
1450
1451         if (c->oom_adjust_set)
1452                 fprintf(f,
1453                         "%sOOMAdjust: %i\n",
1454                         prefix, c->oom_adjust);
1455
1456         for (i = 0; i < RLIM_NLIMITS; i++)
1457                 if (c->rlimit[i])
1458                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1459
1460         if (c->ioprio_set)
1461                 fprintf(f,
1462                         "%sIOSchedulingClass: %s\n"
1463                         "%sIOPriority: %i\n",
1464                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1465                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1466
1467         if (c->cpu_sched_set)
1468                 fprintf(f,
1469                         "%sCPUSchedulingPolicy: %s\n"
1470                         "%sCPUSchedulingPriority: %i\n"
1471                         "%sCPUSchedulingResetOnFork: %s\n",
1472                         prefix, sched_policy_to_string(c->cpu_sched_policy),
1473                         prefix, c->cpu_sched_priority,
1474                         prefix, yes_no(c->cpu_sched_reset_on_fork));
1475
1476         if (c->cpuset) {
1477                 fprintf(f, "%sCPUAffinity:", prefix);
1478                 for (i = 0; i < c->cpuset_ncpus; i++)
1479                         if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1480                                 fprintf(f, " %i", i);
1481                 fputs("\n", f);
1482         }
1483
1484         if (c->timer_slack_nsec_set)
1485                 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1486
1487         fprintf(f,
1488                 "%sStandardInput: %s\n"
1489                 "%sStandardOutput: %s\n"
1490                 "%sStandardError: %s\n",
1491                 prefix, exec_input_to_string(c->std_input),
1492                 prefix, exec_output_to_string(c->std_output),
1493                 prefix, exec_output_to_string(c->std_error));
1494
1495         if (c->tty_path)
1496                 fprintf(f,
1497                         "%sTTYPath: %s\n",
1498                         prefix, c->tty_path);
1499
1500         if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1501             c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1502                 fprintf(f,
1503                         "%sSyslogFacility: %s\n"
1504                         "%sSyslogLevel: %s\n",
1505                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1506                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1507
1508         if (c->capabilities) {
1509                 char *t;
1510                 if ((t = cap_to_text(c->capabilities, NULL))) {
1511                         fprintf(f, "%sCapabilities: %s\n",
1512                                 prefix, t);
1513                         cap_free(t);
1514                 }
1515         }
1516
1517         if (c->secure_bits)
1518                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1519                         prefix,
1520                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1521                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1522                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1523                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1524                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1525                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1526
1527         if (c->capability_bounding_set_drop) {
1528                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1529
1530                 for (i = 0; i <= CAP_LAST_CAP; i++)
1531                         if (c->capability_bounding_set_drop & (1 << i)) {
1532                                 char *t;
1533
1534                                 if ((t = cap_to_name(i))) {
1535                                         fprintf(f, " %s", t);
1536                                         free(t);
1537                                 }
1538                         }
1539
1540                 fputs("\n", f);
1541         }
1542
1543         if (c->user)
1544                 fprintf(f, "%sUser: %s\n", prefix, c->user);
1545         if (c->group)
1546                 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1547
1548         if (strv_length(c->supplementary_groups) > 0) {
1549                 fprintf(f, "%sSupplementaryGroups:", prefix);
1550                 strv_fprintf(f, c->supplementary_groups);
1551                 fputs("\n", f);
1552         }
1553
1554         if (c->pam_name)
1555                 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1556
1557         if (strv_length(c->read_write_dirs) > 0) {
1558                 fprintf(f, "%sReadWriteDirs:", prefix);
1559                 strv_fprintf(f, c->read_write_dirs);
1560                 fputs("\n", f);
1561         }
1562
1563         if (strv_length(c->read_only_dirs) > 0) {
1564                 fprintf(f, "%sReadOnlyDirs:", prefix);
1565                 strv_fprintf(f, c->read_only_dirs);
1566                 fputs("\n", f);
1567         }
1568
1569         if (strv_length(c->inaccessible_dirs) > 0) {
1570                 fprintf(f, "%sInaccessibleDirs:", prefix);
1571                 strv_fprintf(f, c->inaccessible_dirs);
1572                 fputs("\n", f);
1573         }
1574 }
1575
1576 void exec_status_start(ExecStatus *s, pid_t pid) {
1577         assert(s);
1578
1579         zero(*s);
1580         s->pid = pid;
1581         dual_timestamp_get(&s->start_timestamp);
1582 }
1583
1584 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status) {
1585         assert(s);
1586
1587         if ((s->pid && s->pid != pid) ||
1588             !s->start_timestamp.realtime <= 0)
1589                 zero(*s);
1590
1591         s->pid = pid;
1592         dual_timestamp_get(&s->exit_timestamp);
1593
1594         s->code = code;
1595         s->status = status;
1596 }
1597
1598 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1599         char buf[FORMAT_TIMESTAMP_MAX];
1600
1601         assert(s);
1602         assert(f);
1603
1604         if (!prefix)
1605                 prefix = "";
1606
1607         if (s->pid <= 0)
1608                 return;
1609
1610         fprintf(f,
1611                 "%sPID: %lu\n",
1612                 prefix, (unsigned long) s->pid);
1613
1614         if (s->start_timestamp.realtime > 0)
1615                 fprintf(f,
1616                         "%sStart Timestamp: %s\n",
1617                         prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1618
1619         if (s->exit_timestamp.realtime > 0)
1620                 fprintf(f,
1621                         "%sExit Timestamp: %s\n"
1622                         "%sExit Code: %s\n"
1623                         "%sExit Status: %i\n",
1624                         prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1625                         prefix, sigchld_code_to_string(s->code),
1626                         prefix, s->status);
1627 }
1628
1629 char *exec_command_line(char **argv) {
1630         size_t k;
1631         char *n, *p, **a;
1632         bool first = true;
1633
1634         assert(argv);
1635
1636         k = 1;
1637         STRV_FOREACH(a, argv)
1638                 k += strlen(*a)+3;
1639
1640         if (!(n = new(char, k)))
1641                 return NULL;
1642
1643         p = n;
1644         STRV_FOREACH(a, argv) {
1645
1646                 if (!first)
1647                         *(p++) = ' ';
1648                 else
1649                         first = false;
1650
1651                 if (strpbrk(*a, WHITESPACE)) {
1652                         *(p++) = '\'';
1653                         p = stpcpy(p, *a);
1654                         *(p++) = '\'';
1655                 } else
1656                         p = stpcpy(p, *a);
1657
1658         }
1659
1660         *p = 0;
1661
1662         /* FIXME: this doesn't really handle arguments that have
1663          * spaces and ticks in them */
1664
1665         return n;
1666 }
1667
1668 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1669         char *p2;
1670         const char *prefix2;
1671
1672         char *cmd;
1673
1674         assert(c);
1675         assert(f);
1676
1677         if (!prefix)
1678                 prefix = "";
1679         p2 = strappend(prefix, "\t");
1680         prefix2 = p2 ? p2 : prefix;
1681
1682         cmd = exec_command_line(c->argv);
1683
1684         fprintf(f,
1685                 "%sCommand Line: %s\n",
1686                 prefix, cmd ? cmd : strerror(ENOMEM));
1687
1688         free(cmd);
1689
1690         exec_status_dump(&c->exec_status, f, prefix2);
1691
1692         free(p2);
1693 }
1694
1695 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1696         assert(f);
1697
1698         if (!prefix)
1699                 prefix = "";
1700
1701         LIST_FOREACH(command, c, c)
1702                 exec_command_dump(c, f, prefix);
1703 }
1704
1705 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1706         ExecCommand *end;
1707
1708         assert(l);
1709         assert(e);
1710
1711         if (*l) {
1712                 /* It's kinda important that we keep the order here */
1713                 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1714                 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1715         } else
1716               *l = e;
1717 }
1718
1719 int exec_command_set(ExecCommand *c, const char *path, ...) {
1720         va_list ap;
1721         char **l, *p;
1722
1723         assert(c);
1724         assert(path);
1725
1726         va_start(ap, path);
1727         l = strv_new_ap(path, ap);
1728         va_end(ap);
1729
1730         if (!l)
1731                 return -ENOMEM;
1732
1733         if (!(p = strdup(path))) {
1734                 strv_free(l);
1735                 return -ENOMEM;
1736         }
1737
1738         free(c->path);
1739         c->path = p;
1740
1741         strv_free(c->argv);
1742         c->argv = l;
1743
1744         return 0;
1745 }
1746
1747 const char* exit_status_to_string(ExitStatus status) {
1748
1749         /* We cast to int here, so that -Wenum doesn't complain that
1750          * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
1751
1752         switch ((int) status) {
1753
1754         case EXIT_SUCCESS:
1755                 return "SUCCESS";
1756
1757         case EXIT_FAILURE:
1758                 return "FAILURE";
1759
1760         case EXIT_INVALIDARGUMENT:
1761                 return "INVALIDARGUMENT";
1762
1763         case EXIT_NOTIMPLEMENTED:
1764                 return "NOTIMPLEMENTED";
1765
1766         case EXIT_NOPERMISSION:
1767                 return "NOPERMISSION";
1768
1769         case EXIT_NOTINSTALLED:
1770                 return "NOTINSSTALLED";
1771
1772         case EXIT_NOTCONFIGURED:
1773                 return "NOTCONFIGURED";
1774
1775         case EXIT_NOTRUNNING:
1776                 return "NOTRUNNING";
1777
1778         case EXIT_CHDIR:
1779                 return "CHDIR";
1780
1781         case EXIT_NICE:
1782                 return "NICE";
1783
1784         case EXIT_FDS:
1785                 return "FDS";
1786
1787         case EXIT_EXEC:
1788                 return "EXEC";
1789
1790         case EXIT_MEMORY:
1791                 return "MEMORY";
1792
1793         case EXIT_LIMITS:
1794                 return "LIMITS";
1795
1796         case EXIT_OOM_ADJUST:
1797                 return "OOM_ADJUST";
1798
1799         case EXIT_SIGNAL_MASK:
1800                 return "SIGNAL_MASK";
1801
1802         case EXIT_STDIN:
1803                 return "STDIN";
1804
1805         case EXIT_STDOUT:
1806                 return "STDOUT";
1807
1808         case EXIT_CHROOT:
1809                 return "CHROOT";
1810
1811         case EXIT_IOPRIO:
1812                 return "IOPRIO";
1813
1814         case EXIT_TIMERSLACK:
1815                 return "TIMERSLACK";
1816
1817         case EXIT_SECUREBITS:
1818                 return "SECUREBITS";
1819
1820         case EXIT_SETSCHEDULER:
1821                 return "SETSCHEDULER";
1822
1823         case EXIT_CPUAFFINITY:
1824                 return "CPUAFFINITY";
1825
1826         case EXIT_GROUP:
1827                 return "GROUP";
1828
1829         case EXIT_USER:
1830                 return "USER";
1831
1832         case EXIT_CAPABILITIES:
1833                 return "CAPABILITIES";
1834
1835         case EXIT_CGROUP:
1836                 return "CGROUP";
1837
1838         case EXIT_SETSID:
1839                 return "SETSID";
1840
1841         case EXIT_CONFIRM:
1842                 return "CONFIRM";
1843
1844         case EXIT_STDERR:
1845                 return "STDERR";
1846
1847         case EXIT_TCPWRAP:
1848                 return "TCPWRAP";
1849
1850         case EXIT_PAM:
1851                 return "PAM";
1852
1853         default:
1854                 return NULL;
1855         }
1856 }
1857
1858 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1859         [EXEC_INPUT_NULL] = "null",
1860         [EXEC_INPUT_TTY] = "tty",
1861         [EXEC_INPUT_TTY_FORCE] = "tty-force",
1862         [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1863         [EXEC_INPUT_SOCKET] = "socket"
1864 };
1865
1866 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1867         [EXEC_OUTPUT_INHERIT] = "inherit",
1868         [EXEC_OUTPUT_NULL] = "null",
1869         [EXEC_OUTPUT_TTY] = "tty",
1870         [EXEC_OUTPUT_SYSLOG] = "syslog",
1871         [EXEC_OUTPUT_KMSG] = "kmsg",
1872         [EXEC_OUTPUT_SOCKET] = "socket"
1873 };
1874
1875 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1876
1877 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);