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