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