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