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