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