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