chiark / gitweb /
2443d9c74d08e65c543ebed36350bed31593d5d6
[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 a socket is connected to STDIN/STDOUT/STDERR, we
1042                  * must sure to drop O_NONBLOCK */
1043                 if (socket_fd >= 0)
1044                         fd_nonblock(socket_fd, false);
1045
1046                 if (!keep_stdin)
1047                         if (setup_input(context, socket_fd, apply_tty_stdin) < 0) {
1048                                 r = EXIT_STDIN;
1049                                 goto fail;
1050                         }
1051
1052                 if (!keep_stdout)
1053                         if (setup_output(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1054                                 r = EXIT_STDOUT;
1055                                 goto fail;
1056                         }
1057
1058                 if (setup_error(context, socket_fd, file_name_from_path(command->path), apply_tty_stdin) < 0) {
1059                         r = EXIT_STDERR;
1060                         goto fail;
1061                 }
1062
1063                 if (cgroup_bondings)
1064                         if (cgroup_bonding_install_list(cgroup_bondings, 0) < 0) {
1065                                 r = EXIT_CGROUP;
1066                                 goto fail;
1067                         }
1068
1069                 if (context->oom_adjust_set) {
1070                         char t[16];
1071
1072                         snprintf(t, sizeof(t), "%i", context->oom_adjust);
1073                         char_array_0(t);
1074
1075                         if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
1076                                 r = EXIT_OOM_ADJUST;
1077                                 goto fail;
1078                         }
1079                 }
1080
1081                 if (context->nice_set)
1082                         if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
1083                                 r = EXIT_NICE;
1084                                 goto fail;
1085                         }
1086
1087                 if (context->cpu_sched_set) {
1088                         struct sched_param param;
1089
1090                         zero(param);
1091                         param.sched_priority = context->cpu_sched_priority;
1092
1093                         if (sched_setscheduler(0, context->cpu_sched_policy |
1094                                                (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), &param) < 0) {
1095                                 r = EXIT_SETSCHEDULER;
1096                                 goto fail;
1097                         }
1098                 }
1099
1100                 if (context->cpuset)
1101                         if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
1102                                 r = EXIT_CPUAFFINITY;
1103                                 goto fail;
1104                         }
1105
1106                 if (context->ioprio_set)
1107                         if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
1108                                 r = EXIT_IOPRIO;
1109                                 goto fail;
1110                         }
1111
1112                 if (context->timer_slack_nsec_set)
1113                         if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
1114                                 r = EXIT_TIMERSLACK;
1115                                 goto fail;
1116                         }
1117
1118                 if (context->user) {
1119                         username = context->user;
1120                         if (get_user_creds(&username, &uid, &gid, &home) < 0) {
1121                                 r = EXIT_USER;
1122                                 goto fail;
1123                         }
1124
1125                         if (is_terminal_input(context->std_input))
1126                                 if (chown_terminal(STDIN_FILENO, uid) < 0) {
1127                                         r = EXIT_STDIN;
1128                                         goto fail;
1129                                 }
1130                 }
1131
1132 #ifdef HAVE_PAM
1133                 if (context->pam_name && username) {
1134                         if (setup_pam(context->pam_name, username, context->tty_path, &pam_env, fds, n_fds) < 0) {
1135                                 r = EXIT_PAM;
1136                                 goto fail;
1137                         }
1138                 }
1139 #endif
1140
1141                 if (apply_permissions)
1142                         if (enforce_groups(context, username, uid) < 0) {
1143                                 r = EXIT_GROUP;
1144                                 goto fail;
1145                         }
1146
1147                 umask(context->umask);
1148
1149                 if (strv_length(context->read_write_dirs) > 0 ||
1150                     strv_length(context->read_only_dirs) > 0 ||
1151                     strv_length(context->inaccessible_dirs) > 0 ||
1152                     context->mount_flags != MS_SHARED ||
1153                     context->private_tmp)
1154                         if ((r = setup_namespace(
1155                                              context->read_write_dirs,
1156                                              context->read_only_dirs,
1157                                              context->inaccessible_dirs,
1158                                              context->private_tmp,
1159                                              context->mount_flags)) < 0)
1160                                 goto fail;
1161
1162                 if (apply_chroot) {
1163                         if (context->root_directory)
1164                                 if (chroot(context->root_directory) < 0) {
1165                                         r = EXIT_CHROOT;
1166                                         goto fail;
1167                                 }
1168
1169                         if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
1170                                 r = EXIT_CHDIR;
1171                                 goto fail;
1172                         }
1173                 } else {
1174
1175                         char *d;
1176
1177                         if (asprintf(&d, "%s/%s",
1178                                      context->root_directory ? context->root_directory : "",
1179                                      context->working_directory ? context->working_directory : "") < 0) {
1180                                 r = EXIT_MEMORY;
1181                                 goto fail;
1182                         }
1183
1184                         if (chdir(d) < 0) {
1185                                 free(d);
1186                                 r = EXIT_CHDIR;
1187                                 goto fail;
1188                         }
1189
1190                         free(d);
1191                 }
1192
1193                 /* We repeat the fd closing here, to make sure that
1194                  * nothing is leaked from the PAM modules */
1195                 if (close_all_fds(fds, n_fds) < 0 ||
1196                     shift_fds(fds, n_fds) < 0 ||
1197                     flags_fds(fds, n_fds, context->non_blocking) < 0) {
1198                         r = EXIT_FDS;
1199                         goto fail;
1200                 }
1201
1202                 if (apply_permissions) {
1203
1204                         for (i = 0; i < RLIMIT_NLIMITS; i++) {
1205                                 if (!context->rlimit[i])
1206                                         continue;
1207
1208                                 if (setrlimit(i, context->rlimit[i]) < 0) {
1209                                         r = EXIT_LIMITS;
1210                                         goto fail;
1211                                 }
1212                         }
1213
1214                         if (context->user)
1215                                 if (enforce_user(context, uid) < 0) {
1216                                         r = EXIT_USER;
1217                                         goto fail;
1218                                 }
1219
1220                         /* PR_GET_SECUREBITS is not priviliged, while
1221                          * PR_SET_SECUREBITS is. So to suppress
1222                          * potential EPERMs we'll try not to call
1223                          * PR_SET_SECUREBITS unless necessary. */
1224                         if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1225                                 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
1226                                         r = EXIT_SECUREBITS;
1227                                         goto fail;
1228                                 }
1229
1230                         if (context->capabilities)
1231                                 if (cap_set_proc(context->capabilities) < 0) {
1232                                         r = EXIT_CAPABILITIES;
1233                                         goto fail;
1234                                 }
1235                 }
1236
1237                 if (!(our_env = new0(char*, 6))) {
1238                         r = EXIT_MEMORY;
1239                         goto fail;
1240                 }
1241
1242                 if (n_fds > 0)
1243                         if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
1244                             asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
1245                                 r = EXIT_MEMORY;
1246                                 goto fail;
1247                         }
1248
1249                 if (home)
1250                         if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
1251                                 r = EXIT_MEMORY;
1252                                 goto fail;
1253                         }
1254
1255                 if (username)
1256                         if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1257                             asprintf(our_env + n_env++, "USER=%s", username) < 0) {
1258                                 r = EXIT_MEMORY;
1259                                 goto fail;
1260                         }
1261
1262                 assert(n_env <= 6);
1263
1264                 if (!(final_env = strv_env_merge(
1265                                       4,
1266                                       environment,
1267                                       our_env,
1268                                       context->environment,
1269                                       pam_env,
1270                                       NULL))) {
1271                         r = EXIT_MEMORY;
1272                         goto fail;
1273                 }
1274
1275                 if (!(final_argv = replace_env_argv(argv, final_env))) {
1276                         r = EXIT_MEMORY;
1277                         goto fail;
1278                 }
1279
1280                 execve(command->path, final_argv, final_env);
1281                 r = EXIT_EXEC;
1282
1283         fail:
1284                 strv_free(our_env);
1285                 strv_free(final_env);
1286                 strv_free(pam_env);
1287                 strv_free(final_argv);
1288
1289                 if (saved_stdin >= 0)
1290                         close_nointr_nofail(saved_stdin);
1291
1292                 if (saved_stdout >= 0)
1293                         close_nointr_nofail(saved_stdout);
1294
1295                 _exit(r);
1296         }
1297
1298         /* We add the new process to the cgroup both in the child (so
1299          * that we can be sure that no user code is ever executed
1300          * outside of the cgroup) and in the parent (so that we can be
1301          * sure that when we kill the cgroup the process will be
1302          * killed too). */
1303         if (cgroup_bondings)
1304                 cgroup_bonding_install_list(cgroup_bondings, pid);
1305
1306         log_debug("Forked %s as %lu", command->path, (unsigned long) pid);
1307
1308         exec_status_start(&command->exec_status, pid);
1309
1310         *ret = pid;
1311         return 0;
1312 }
1313
1314 void exec_context_init(ExecContext *c) {
1315         assert(c);
1316
1317         c->umask = 0002;
1318         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1319         c->cpu_sched_policy = SCHED_OTHER;
1320         c->syslog_priority = LOG_DAEMON|LOG_INFO;
1321         c->syslog_level_prefix = true;
1322         c->mount_flags = MS_SHARED;
1323         c->kill_signal = SIGTERM;
1324 }
1325
1326 void exec_context_done(ExecContext *c) {
1327         unsigned l;
1328
1329         assert(c);
1330
1331         strv_free(c->environment);
1332         c->environment = NULL;
1333
1334         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1335                 free(c->rlimit[l]);
1336                 c->rlimit[l] = NULL;
1337         }
1338
1339         free(c->working_directory);
1340         c->working_directory = NULL;
1341         free(c->root_directory);
1342         c->root_directory = NULL;
1343
1344         free(c->tty_path);
1345         c->tty_path = NULL;
1346
1347         free(c->tcpwrap_name);
1348         c->tcpwrap_name = NULL;
1349
1350         free(c->syslog_identifier);
1351         c->syslog_identifier = NULL;
1352
1353         free(c->user);
1354         c->user = NULL;
1355
1356         free(c->group);
1357         c->group = NULL;
1358
1359         strv_free(c->supplementary_groups);
1360         c->supplementary_groups = NULL;
1361
1362         free(c->pam_name);
1363         c->pam_name = NULL;
1364
1365         if (c->capabilities) {
1366                 cap_free(c->capabilities);
1367                 c->capabilities = NULL;
1368         }
1369
1370         strv_free(c->read_only_dirs);
1371         c->read_only_dirs = NULL;
1372
1373         strv_free(c->read_write_dirs);
1374         c->read_write_dirs = NULL;
1375
1376         strv_free(c->inaccessible_dirs);
1377         c->inaccessible_dirs = NULL;
1378
1379         if (c->cpuset)
1380                 CPU_FREE(c->cpuset);
1381 }
1382
1383 void exec_command_done(ExecCommand *c) {
1384         assert(c);
1385
1386         free(c->path);
1387         c->path = NULL;
1388
1389         strv_free(c->argv);
1390         c->argv = NULL;
1391 }
1392
1393 void exec_command_done_array(ExecCommand *c, unsigned n) {
1394         unsigned i;
1395
1396         for (i = 0; i < n; i++)
1397                 exec_command_done(c+i);
1398 }
1399
1400 void exec_command_free_list(ExecCommand *c) {
1401         ExecCommand *i;
1402
1403         while ((i = c)) {
1404                 LIST_REMOVE(ExecCommand, command, c, i);
1405                 exec_command_done(i);
1406                 free(i);
1407         }
1408 }
1409
1410 void exec_command_free_array(ExecCommand **c, unsigned n) {
1411         unsigned i;
1412
1413         for (i = 0; i < n; i++) {
1414                 exec_command_free_list(c[i]);
1415                 c[i] = NULL;
1416         }
1417 }
1418
1419 static void strv_fprintf(FILE *f, char **l) {
1420         char **g;
1421
1422         assert(f);
1423
1424         STRV_FOREACH(g, l)
1425                 fprintf(f, " %s", *g);
1426 }
1427
1428 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1429         char ** e;
1430         unsigned i;
1431
1432         assert(c);
1433         assert(f);
1434
1435         if (!prefix)
1436                 prefix = "";
1437
1438         fprintf(f,
1439                 "%sUMask: %04o\n"
1440                 "%sWorkingDirectory: %s\n"
1441                 "%sRootDirectory: %s\n"
1442                 "%sNonBlocking: %s\n"
1443                 "%sPrivateTmp: %s\n",
1444                 prefix, c->umask,
1445                 prefix, c->working_directory ? c->working_directory : "/",
1446                 prefix, c->root_directory ? c->root_directory : "/",
1447                 prefix, yes_no(c->non_blocking),
1448                 prefix, yes_no(c->private_tmp));
1449
1450         if (c->environment)
1451                 for (e = c->environment; *e; e++)
1452                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1453
1454         if (c->tcpwrap_name)
1455                 fprintf(f,
1456                         "%sTCPWrapName: %s\n",
1457                         prefix, c->tcpwrap_name);
1458
1459         if (c->nice_set)
1460                 fprintf(f,
1461                         "%sNice: %i\n",
1462                         prefix, c->nice);
1463
1464         if (c->oom_adjust_set)
1465                 fprintf(f,
1466                         "%sOOMAdjust: %i\n",
1467                         prefix, c->oom_adjust);
1468
1469         for (i = 0; i < RLIM_NLIMITS; i++)
1470                 if (c->rlimit[i])
1471                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1472
1473         if (c->ioprio_set)
1474                 fprintf(f,
1475                         "%sIOSchedulingClass: %s\n"
1476                         "%sIOPriority: %i\n",
1477                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1478                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1479
1480         if (c->cpu_sched_set)
1481                 fprintf(f,
1482                         "%sCPUSchedulingPolicy: %s\n"
1483                         "%sCPUSchedulingPriority: %i\n"
1484                         "%sCPUSchedulingResetOnFork: %s\n",
1485                         prefix, sched_policy_to_string(c->cpu_sched_policy),
1486                         prefix, c->cpu_sched_priority,
1487                         prefix, yes_no(c->cpu_sched_reset_on_fork));
1488
1489         if (c->cpuset) {
1490                 fprintf(f, "%sCPUAffinity:", prefix);
1491                 for (i = 0; i < c->cpuset_ncpus; i++)
1492                         if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
1493                                 fprintf(f, " %i", i);
1494                 fputs("\n", f);
1495         }
1496
1497         if (c->timer_slack_nsec_set)
1498                 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, c->timer_slack_nsec);
1499
1500         fprintf(f,
1501                 "%sStandardInput: %s\n"
1502                 "%sStandardOutput: %s\n"
1503                 "%sStandardError: %s\n",
1504                 prefix, exec_input_to_string(c->std_input),
1505                 prefix, exec_output_to_string(c->std_output),
1506                 prefix, exec_output_to_string(c->std_error));
1507
1508         if (c->tty_path)
1509                 fprintf(f,
1510                         "%sTTYPath: %s\n",
1511                         prefix, c->tty_path);
1512
1513         if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG ||
1514             c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG)
1515                 fprintf(f,
1516                         "%sSyslogFacility: %s\n"
1517                         "%sSyslogLevel: %s\n",
1518                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1519                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1520
1521         if (c->capabilities) {
1522                 char *t;
1523                 if ((t = cap_to_text(c->capabilities, NULL))) {
1524                         fprintf(f, "%sCapabilities: %s\n",
1525                                 prefix, t);
1526                         cap_free(t);
1527                 }
1528         }
1529
1530         if (c->secure_bits)
1531                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1532                         prefix,
1533                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1534                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1535                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1536                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1537                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1538                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1539
1540         if (c->capability_bounding_set_drop) {
1541                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1542
1543                 for (i = 0; i <= CAP_LAST_CAP; i++)
1544                         if (c->capability_bounding_set_drop & (1 << i)) {
1545                                 char *t;
1546
1547                                 if ((t = cap_to_name(i))) {
1548                                         fprintf(f, " %s", t);
1549                                         free(t);
1550                                 }
1551                         }
1552
1553                 fputs("\n", f);
1554         }
1555
1556         if (c->user)
1557                 fprintf(f, "%sUser: %s\n", prefix, c->user);
1558         if (c->group)
1559                 fprintf(f, "%sGroup: %s\n", prefix, c->group);
1560
1561         if (strv_length(c->supplementary_groups) > 0) {
1562                 fprintf(f, "%sSupplementaryGroups:", prefix);
1563                 strv_fprintf(f, c->supplementary_groups);
1564                 fputs("\n", f);
1565         }
1566
1567         if (c->pam_name)
1568                 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
1569
1570         if (strv_length(c->read_write_dirs) > 0) {
1571                 fprintf(f, "%sReadWriteDirs:", prefix);
1572                 strv_fprintf(f, c->read_write_dirs);
1573                 fputs("\n", f);
1574         }
1575
1576         if (strv_length(c->read_only_dirs) > 0) {
1577                 fprintf(f, "%sReadOnlyDirs:", prefix);
1578                 strv_fprintf(f, c->read_only_dirs);
1579                 fputs("\n", f);
1580         }
1581
1582         if (strv_length(c->inaccessible_dirs) > 0) {
1583                 fprintf(f, "%sInaccessibleDirs:", prefix);
1584                 strv_fprintf(f, c->inaccessible_dirs);
1585                 fputs("\n", f);
1586         }
1587
1588         fprintf(f,
1589                 "%sKillMode: %s\n"
1590                 "%sKillSignal: SIG%s\n",
1591                 prefix, kill_mode_to_string(c->kill_mode),
1592                 prefix, signal_to_string(c->kill_signal));
1593 }
1594
1595 void exec_status_start(ExecStatus *s, pid_t pid) {
1596         assert(s);
1597
1598         zero(*s);
1599         s->pid = pid;
1600         dual_timestamp_get(&s->start_timestamp);
1601 }
1602
1603 void exec_status_exit(ExecStatus *s, pid_t pid, int code, int status) {
1604         assert(s);
1605
1606         if ((s->pid && s->pid != pid) ||
1607             !s->start_timestamp.realtime <= 0)
1608                 zero(*s);
1609
1610         s->pid = pid;
1611         dual_timestamp_get(&s->exit_timestamp);
1612
1613         s->code = code;
1614         s->status = status;
1615 }
1616
1617 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1618         char buf[FORMAT_TIMESTAMP_MAX];
1619
1620         assert(s);
1621         assert(f);
1622
1623         if (!prefix)
1624                 prefix = "";
1625
1626         if (s->pid <= 0)
1627                 return;
1628
1629         fprintf(f,
1630                 "%sPID: %lu\n",
1631                 prefix, (unsigned long) s->pid);
1632
1633         if (s->start_timestamp.realtime > 0)
1634                 fprintf(f,
1635                         "%sStart Timestamp: %s\n",
1636                         prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
1637
1638         if (s->exit_timestamp.realtime > 0)
1639                 fprintf(f,
1640                         "%sExit Timestamp: %s\n"
1641                         "%sExit Code: %s\n"
1642                         "%sExit Status: %i\n",
1643                         prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
1644                         prefix, sigchld_code_to_string(s->code),
1645                         prefix, s->status);
1646 }
1647
1648 char *exec_command_line(char **argv) {
1649         size_t k;
1650         char *n, *p, **a;
1651         bool first = true;
1652
1653         assert(argv);
1654
1655         k = 1;
1656         STRV_FOREACH(a, argv)
1657                 k += strlen(*a)+3;
1658
1659         if (!(n = new(char, k)))
1660                 return NULL;
1661
1662         p = n;
1663         STRV_FOREACH(a, argv) {
1664
1665                 if (!first)
1666                         *(p++) = ' ';
1667                 else
1668                         first = false;
1669
1670                 if (strpbrk(*a, WHITESPACE)) {
1671                         *(p++) = '\'';
1672                         p = stpcpy(p, *a);
1673                         *(p++) = '\'';
1674                 } else
1675                         p = stpcpy(p, *a);
1676
1677         }
1678
1679         *p = 0;
1680
1681         /* FIXME: this doesn't really handle arguments that have
1682          * spaces and ticks in them */
1683
1684         return n;
1685 }
1686
1687 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1688         char *p2;
1689         const char *prefix2;
1690
1691         char *cmd;
1692
1693         assert(c);
1694         assert(f);
1695
1696         if (!prefix)
1697                 prefix = "";
1698         p2 = strappend(prefix, "\t");
1699         prefix2 = p2 ? p2 : prefix;
1700
1701         cmd = exec_command_line(c->argv);
1702
1703         fprintf(f,
1704                 "%sCommand Line: %s\n",
1705                 prefix, cmd ? cmd : strerror(ENOMEM));
1706
1707         free(cmd);
1708
1709         exec_status_dump(&c->exec_status, f, prefix2);
1710
1711         free(p2);
1712 }
1713
1714 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1715         assert(f);
1716
1717         if (!prefix)
1718                 prefix = "";
1719
1720         LIST_FOREACH(command, c, c)
1721                 exec_command_dump(c, f, prefix);
1722 }
1723
1724 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1725         ExecCommand *end;
1726
1727         assert(l);
1728         assert(e);
1729
1730         if (*l) {
1731                 /* It's kinda important that we keep the order here */
1732                 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1733                 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1734         } else
1735               *l = e;
1736 }
1737
1738 int exec_command_set(ExecCommand *c, const char *path, ...) {
1739         va_list ap;
1740         char **l, *p;
1741
1742         assert(c);
1743         assert(path);
1744
1745         va_start(ap, path);
1746         l = strv_new_ap(path, ap);
1747         va_end(ap);
1748
1749         if (!l)
1750                 return -ENOMEM;
1751
1752         if (!(p = strdup(path))) {
1753                 strv_free(l);
1754                 return -ENOMEM;
1755         }
1756
1757         free(c->path);
1758         c->path = p;
1759
1760         strv_free(c->argv);
1761         c->argv = l;
1762
1763         return 0;
1764 }
1765
1766 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1767         [EXEC_INPUT_NULL] = "null",
1768         [EXEC_INPUT_TTY] = "tty",
1769         [EXEC_INPUT_TTY_FORCE] = "tty-force",
1770         [EXEC_INPUT_TTY_FAIL] = "tty-fail",
1771         [EXEC_INPUT_SOCKET] = "socket"
1772 };
1773
1774 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1775         [EXEC_OUTPUT_INHERIT] = "inherit",
1776         [EXEC_OUTPUT_NULL] = "null",
1777         [EXEC_OUTPUT_TTY] = "tty",
1778         [EXEC_OUTPUT_SYSLOG] = "syslog",
1779         [EXEC_OUTPUT_KMSG] = "kmsg",
1780         [EXEC_OUTPUT_SOCKET] = "socket"
1781 };
1782
1783 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1784
1785 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);