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