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