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