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