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