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