chiark / gitweb /
9b407258ff20f00307af6c2a00832aa0c7a1e688
[elogind.git] / execute.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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
38 #include "execute.h"
39 #include "strv.h"
40 #include "macro.h"
41 #include "util.h"
42 #include "log.h"
43 #include "ioprio.h"
44 #include "securebits.h"
45 #include "cgroup.h"
46
47 /* This assumes there is a 'tty' group */
48 #define TTY_MODE 0620
49
50 static int shift_fds(int fds[], unsigned n_fds) {
51         int start, restart_from;
52
53         if (n_fds <= 0)
54                 return 0;
55
56         /* Modifies the fds array! (sorts it) */
57
58         assert(fds);
59
60         start = 0;
61         for (;;) {
62                 int i;
63
64                 restart_from = -1;
65
66                 for (i = start; i < (int) n_fds; i++) {
67                         int nfd;
68
69                         /* Already at right index? */
70                         if (fds[i] == i+3)
71                                 continue;
72
73                         if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
74                                 return -errno;
75
76                         close_nointr_nofail(fds[i]);
77                         fds[i] = nfd;
78
79                         /* Hmm, the fd we wanted isn't free? Then
80                          * let's remember that and try again from here*/
81                         if (nfd != i+3 && restart_from < 0)
82                                 restart_from = i;
83                 }
84
85                 if (restart_from < 0)
86                         break;
87
88                 start = restart_from;
89         }
90
91         return 0;
92 }
93
94 static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
95         unsigned i;
96         int r;
97
98         if (n_fds <= 0)
99                 return 0;
100
101         assert(fds);
102
103         /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
104
105         for (i = 0; i < n_fds; i++) {
106
107                 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
108                         return r;
109
110                 /* We unconditionally drop FD_CLOEXEC from the fds,
111                  * since after all we want to pass these fds to our
112                  * children */
113
114                 if ((r = fd_cloexec(fds[i], false)) < 0)
115                         return r;
116         }
117
118         return 0;
119 }
120
121 static const char *tty_path(const ExecContext *context) {
122         assert(context);
123
124         if (context->tty_path)
125                 return context->tty_path;
126
127         return "/dev/console";
128 }
129
130 static int open_null_as(int flags, int nfd) {
131         int fd, r;
132
133         assert(nfd >= 0);
134
135         if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
136                 return -errno;
137
138         if (fd != nfd) {
139                 r = dup2(fd, nfd) < 0 ? -errno : nfd;
140                 close_nointr_nofail(fd);
141         } else
142                 r = nfd;
143
144         return r;
145 }
146
147 static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, int nfd) {
148         int fd, r;
149         union {
150                 struct sockaddr sa;
151                 struct sockaddr_un un;
152         } sa;
153
154         assert(context);
155         assert(output < _EXEC_OUTPUT_MAX);
156         assert(ident);
157         assert(nfd >= 0);
158
159         if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
160                 return -errno;
161
162         zero(sa);
163         sa.sa.sa_family = AF_UNIX;
164         strncpy(sa.un.sun_path+1, LOGGER_SOCKET, sizeof(sa.un.sun_path)-1);
165
166         if (connect(fd, &sa.sa, sizeof(sa)) < 0) {
167                 close_nointr_nofail(fd);
168                 return -errno;
169         }
170
171         if (shutdown(fd, SHUT_RD) < 0) {
172                 close_nointr_nofail(fd);
173                 return -errno;
174         }
175
176         /* We speak a very simple protocol between log server
177          * and client: one line for the log destination (kmsg
178          * or syslog), followed by the priority field,
179          * followed by the process name. Since we replaced
180          * stdin/stderr we simple use stdio to write to
181          * it. Note that we use stderr, to minimize buffer
182          * flushing issues. */
183
184         dprintf(fd,
185                 "%s\n"
186                 "%i\n"
187                 "%s\n",
188                 output == EXEC_OUTPUT_KERNEL ? "kmsg" : "syslog",
189                 context->syslog_priority,
190                 context->syslog_identifier ? context->syslog_identifier : ident);
191
192         if (fd != nfd) {
193                 r = dup2(fd, nfd) < 0 ? -errno : nfd;
194                 close_nointr_nofail(fd);
195         } else
196                 r = nfd;
197
198         return r;
199 }
200 static int open_terminal_as(const char *path, mode_t mode, int nfd) {
201         int fd, r;
202
203         assert(path);
204         assert(nfd >= 0);
205
206         if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
207                 return fd;
208
209         if (fd != nfd) {
210                 r = dup2(fd, nfd) < 0 ? -errno : nfd;
211                 close_nointr_nofail(fd);
212         } else
213                 r = nfd;
214
215         return r;
216 }
217
218 static bool is_terminal_input(ExecInput i) {
219         return
220                 i == EXEC_INPUT_TTY ||
221                 i == EXEC_INPUT_TTY_FORCE ||
222                 i == EXEC_INPUT_TTY_FAIL;
223 }
224
225 static int setup_input(const ExecContext *context) {
226         assert(context);
227
228         switch (context->std_input) {
229
230         case EXEC_INPUT_NULL:
231                 return open_null_as(O_RDONLY, STDIN_FILENO);
232
233         case EXEC_INPUT_TTY:
234         case EXEC_INPUT_TTY_FORCE:
235         case EXEC_INPUT_TTY_FAIL: {
236                 int fd, r;
237
238                 if ((fd = acquire_terminal(
239                                      tty_path(context),
240                                      context->std_input == EXEC_INPUT_TTY_FAIL,
241                                      context->std_input == EXEC_INPUT_TTY_FORCE)) < 0)
242                         return fd;
243
244                 if (fd != STDIN_FILENO) {
245                         r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
246                         close_nointr_nofail(fd);
247                 } else
248                         r = STDIN_FILENO;
249
250                 return r;
251         }
252
253         default:
254                 assert_not_reached("Unknown input type");
255         }
256 }
257
258 static int setup_output(const ExecContext *context, const char *ident) {
259         assert(context);
260         assert(ident);
261
262         /* This expects the input is already set up */
263
264         switch (context->std_output) {
265
266         case EXEC_OUTPUT_INHERIT:
267
268                 /* If the input is connected to a terminal, inherit that... */
269                 if (is_terminal_input(context->std_input))
270                         return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
271
272                 return 0;
273
274         case EXEC_OUTPUT_NULL:
275                 return open_null_as(O_WRONLY, STDOUT_FILENO);
276
277         case EXEC_OUTPUT_TTY: {
278                 if (is_terminal_input(context->std_input))
279                         return dup2(STDIN_FILENO, STDOUT_FILENO) < 0 ? -errno : STDOUT_FILENO;
280
281                 /* We don't reset the terminal if this is just about output */
282                 return open_terminal_as(tty_path(context), O_WRONLY, STDOUT_FILENO);
283         }
284
285         case EXEC_OUTPUT_SYSLOG:
286         case EXEC_OUTPUT_KERNEL:
287                 return connect_logger_as(context, context->std_output, ident, STDOUT_FILENO);
288
289         default:
290                 assert_not_reached("Unknown output type");
291         }
292 }
293
294 static int setup_error(const ExecContext *context, const char *ident) {
295         assert(context);
296         assert(ident);
297
298         /* This expects the input and output are already set up */
299
300         /* Don't change the stderr file descriptor if we inherit all
301          * the way and are not on a tty */
302         if (context->std_error == EXEC_OUTPUT_INHERIT &&
303             context->std_output == EXEC_OUTPUT_INHERIT &&
304             !is_terminal_input(context->std_input))
305                 return STDERR_FILENO;
306
307         /* Duplicate form stdout if possible */
308         if (context->std_error == context->std_output ||
309             context->std_error == EXEC_OUTPUT_INHERIT)
310                 return dup2(STDOUT_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
311
312         switch (context->std_error) {
313
314         case EXEC_OUTPUT_NULL:
315                 return open_null_as(O_WRONLY, STDERR_FILENO);
316
317         case EXEC_OUTPUT_TTY:
318                 if (is_terminal_input(context->std_input))
319                         return dup2(STDIN_FILENO, STDERR_FILENO) < 0 ? -errno : STDERR_FILENO;
320
321                 /* We don't reset the terminal if this is just about output */
322                 return open_terminal_as(tty_path(context), O_WRONLY, STDERR_FILENO);
323
324         case EXEC_OUTPUT_SYSLOG:
325         case EXEC_OUTPUT_KERNEL:
326                 return connect_logger_as(context, context->std_error, ident, STDERR_FILENO);
327
328         default:
329                 assert_not_reached("Unknown error type");
330         }
331 }
332
333 static int chown_terminal(int fd, uid_t uid) {
334         struct stat st;
335
336         assert(fd >= 0);
337
338         /* This might fail. What matters are the results. */
339         fchown(fd, uid, -1);
340         fchmod(fd, TTY_MODE);
341
342         if (fstat(fd, &st) < 0)
343                 return -errno;
344
345         if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
346                 return -EPERM;
347
348         return 0;
349 }
350
351 static int setup_confirm_stdio(const ExecContext *context,
352                                int *_saved_stdin,
353                                int *_saved_stdout) {
354         int fd = -1, saved_stdin, saved_stdout = -1, r;
355
356         assert(context);
357         assert(_saved_stdin);
358         assert(_saved_stdout);
359
360         /* This returns positive EXIT_xxx return values instead of
361          * negative errno style values! */
362
363         if ((saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3)) < 0)
364                 return EXIT_STDIN;
365
366         if ((saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3)) < 0) {
367                 r = EXIT_STDOUT;
368                 goto fail;
369         }
370
371         if ((fd = acquire_terminal(
372                              tty_path(context),
373                              context->std_input == EXEC_INPUT_TTY_FAIL,
374                              context->std_input == EXEC_INPUT_TTY_FORCE)) < 0) {
375                 r = EXIT_STDIN;
376                 goto fail;
377         }
378
379         if (chown_terminal(fd, getuid()) < 0) {
380                 r = EXIT_STDIN;
381                 goto fail;
382         }
383
384         if (dup2(fd, STDIN_FILENO) < 0) {
385                 r = EXIT_STDIN;
386                 goto fail;
387         }
388
389         if (dup2(fd, STDOUT_FILENO) < 0) {
390                 r = EXIT_STDOUT;
391                 goto fail;
392         }
393
394         if (fd >= 2)
395                 close_nointr_nofail(fd);
396
397         *_saved_stdin = saved_stdin;
398         *_saved_stdout = saved_stdout;
399
400         return 0;
401
402 fail:
403         if (saved_stdout >= 0)
404                 close_nointr_nofail(saved_stdout);
405
406         if (saved_stdin >= 0)
407                 close_nointr_nofail(saved_stdin);
408
409         if (fd >= 0)
410                 close_nointr_nofail(fd);
411
412         return r;
413 }
414
415 static int restore_conform_stdio(const ExecContext *context,
416                                  int *saved_stdin,
417                                  int *saved_stdout,
418                                  bool *keep_stdin,
419                                  bool *keep_stdout) {
420
421         assert(context);
422         assert(saved_stdin);
423         assert(*saved_stdin >= 0);
424         assert(saved_stdout);
425         assert(*saved_stdout >= 0);
426
427         /* This returns positive EXIT_xxx return values instead of
428          * negative errno style values! */
429
430         if (is_terminal_input(context->std_input)) {
431
432                 /* The service wants terminal input. */
433
434                 *keep_stdin = true;
435                 *keep_stdout =
436                         context->std_output == EXEC_OUTPUT_INHERIT ||
437                         context->std_output == EXEC_OUTPUT_TTY;
438
439         } else {
440                 /* If the service doesn't want a controlling terminal,
441                  * then we need to get rid entirely of what we have
442                  * already. */
443
444                 if (release_terminal() < 0)
445                         return EXIT_STDIN;
446
447                 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
448                         return EXIT_STDIN;
449
450                 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
451                         return EXIT_STDOUT;
452
453                 *keep_stdout = *keep_stdin = false;
454         }
455
456         return 0;
457 }
458
459 static int get_group_creds(const char *groupname, gid_t *gid) {
460         struct group *g;
461         unsigned long lu;
462
463         assert(groupname);
464         assert(gid);
465
466         /* We enforce some special rules for gid=0: in order to avoid
467          * NSS lookups for root we hardcode its data. */
468
469         if (streq(groupname, "root") || streq(groupname, "0")) {
470                 *gid = 0;
471                 return 0;
472         }
473
474         if (safe_atolu(groupname, &lu) >= 0) {
475                 errno = 0;
476                 g = getgrgid((gid_t) lu);
477         } else {
478                 errno = 0;
479                 g = getgrnam(groupname);
480         }
481
482         if (!g)
483                 return errno != 0 ? -errno : -ESRCH;
484
485         *gid = g->gr_gid;
486         return 0;
487 }
488
489 static int get_user_creds(const char **username, uid_t *uid, gid_t *gid, const char **home) {
490         struct passwd *p;
491         unsigned long lu;
492
493         assert(username);
494         assert(*username);
495         assert(uid);
496         assert(gid);
497         assert(home);
498
499         /* We enforce some special rules for uid=0: in order to avoid
500          * NSS lookups for root we hardcode its data. */
501
502         if (streq(*username, "root") || streq(*username, "0")) {
503                 *username = "root";
504                 *uid = 0;
505                 *gid = 0;
506                 *home = "/root";
507                 return 0;
508         }
509
510         if (safe_atolu(*username, &lu) >= 0) {
511                 errno = 0;
512                 p = getpwuid((uid_t) lu);
513
514                 /* If there are multiple users with the same id, make
515                  * sure to leave $USER to the configured value instead
516                  * of the first occurence in the database. However if
517                  * the uid was configured by a numeric uid, then let's
518                  * pick the real username from /etc/passwd. */
519                 if (*username && p)
520                         *username = p->pw_name;
521         } else {
522                 errno = 0;
523                 p = getpwnam(*username);
524         }
525
526         if (!p)
527                 return errno != 0 ? -errno : -ESRCH;
528
529         *uid = p->pw_uid;
530         *gid = p->pw_gid;
531         *home = p->pw_dir;
532         return 0;
533 }
534
535 static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
536         bool keep_groups = false;
537         int r;
538
539         assert(context);
540
541         /* Lookup and ser GID and supplementary group list. Here too
542          * we avoid NSS lookups for gid=0. */
543
544         if (context->group || username) {
545
546                 if (context->group)
547                         if ((r = get_group_creds(context->group, &gid)) < 0)
548                                 return r;
549
550                 /* First step, initialize groups from /etc/groups */
551                 if (username && gid != 0) {
552                         if (initgroups(username, gid) < 0)
553                                 return -errno;
554
555                         keep_groups = true;
556                 }
557
558                 /* Second step, set our gids */
559                 if (setresgid(gid, gid, gid) < 0)
560                         return -errno;
561         }
562
563         if (context->supplementary_groups) {
564                 int ngroups_max, k;
565                 gid_t *gids;
566                 char **i;
567
568                 /* Final step, initialize any manually set supplementary groups */
569                 ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
570
571                 if (!(gids = new(gid_t, ngroups_max)))
572                         return -ENOMEM;
573
574                 if (keep_groups) {
575                         if ((k = getgroups(ngroups_max, gids)) < 0) {
576                                 free(gids);
577                                 return -errno;
578                         }
579                 } else
580                         k = 0;
581
582                 STRV_FOREACH(i, context->supplementary_groups) {
583
584                         if (k >= ngroups_max) {
585                                 free(gids);
586                                 return -E2BIG;
587                         }
588
589                         if ((r = get_group_creds(*i, gids+k)) < 0) {
590                                 free(gids);
591                                 return r;
592                         }
593
594                         k++;
595                 }
596
597                 if (setgroups(k, gids) < 0) {
598                         free(gids);
599                         return -errno;
600                 }
601
602                 free(gids);
603         }
604
605         return 0;
606 }
607
608 static int enforce_user(const ExecContext *context, uid_t uid) {
609         int r;
610         assert(context);
611
612         /* Sets (but doesn't lookup) the uid and make sure we keep the
613          * capabilities while doing so. */
614
615         if (context->capabilities) {
616                 cap_t d;
617                 static const cap_value_t bits[] = {
618                         CAP_SETUID,   /* Necessary so that we can run setresuid() below */
619                         CAP_SETPCAP   /* Necessary so that we can set PR_SET_SECUREBITS later on */
620                 };
621
622                 /* First step: If we need to keep capabilities but
623                  * drop privileges we need to make sure we keep our
624                  * caps, whiel we drop priviliges. */
625                 if (uid != 0) {
626                         int sb = context->secure_bits|SECURE_KEEP_CAPS;
627
628                         if (prctl(PR_GET_SECUREBITS) != sb)
629                                 if (prctl(PR_SET_SECUREBITS, sb) < 0)
630                                         return -errno;
631                 }
632
633                 /* Second step: set the capabilites. This will reduce
634                  * the capabilities to the minimum we need. */
635
636                 if (!(d = cap_dup(context->capabilities)))
637                         return -errno;
638
639                 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
640                     cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
641                         r = -errno;
642                         cap_free(d);
643                         return r;
644                 }
645
646                 if (cap_set_proc(d) < 0) {
647                         r = -errno;
648                         cap_free(d);
649                         return r;
650                 }
651
652                 cap_free(d);
653         }
654
655         /* Third step: actually set the uids */
656         if (setresuid(uid, uid, uid) < 0)
657                 return -errno;
658
659         /* At this point we should have all necessary capabilities but
660            are otherwise a normal user. However, the caps might got
661            corrupted due to the setresuid() so we need clean them up
662            later. This is done outside of this call. */
663
664         return 0;
665 }
666
667 int exec_spawn(ExecCommand *command,
668                char **argv,
669                const ExecContext *context,
670                int fds[], unsigned n_fds,
671                bool apply_permissions,
672                bool apply_chroot,
673                bool confirm_spawn,
674                CGroupBonding *cgroup_bondings,
675                pid_t *ret) {
676
677         pid_t pid;
678         int r;
679         char *line;
680
681         assert(command);
682         assert(context);
683         assert(ret);
684         assert(fds || n_fds <= 0);
685
686         if (!argv)
687                 argv = command->argv;
688
689         if (!(line = exec_command_line(argv)))
690                 return -ENOMEM;
691
692         log_debug("About to execute: %s", line);
693         free(line);
694
695         if (cgroup_bondings)
696                 if ((r = cgroup_bonding_realize_list(cgroup_bondings)))
697                         return r;
698
699         if ((pid = fork()) < 0)
700                 return -errno;
701
702         if (pid == 0) {
703                 int i;
704                 sigset_t ss;
705                 const char *username = NULL, *home = NULL;
706                 uid_t uid = (uid_t) -1;
707                 gid_t gid = (gid_t) -1;
708                 char **our_env = NULL, **final_env = NULL;
709                 unsigned n_env = 0;
710                 int saved_stdout = -1, saved_stdin = -1;
711                 bool keep_stdout = false, keep_stdin = false;
712
713                 /* child */
714
715                 reset_all_signal_handlers();
716
717                 if (sigemptyset(&ss) < 0 ||
718                     sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
719                         r = EXIT_SIGNAL_MASK;
720                         goto fail;
721                 }
722
723                 if (setsid() < 0) {
724                         r = EXIT_SETSID;
725                         goto fail;
726                 }
727
728                 umask(context->umask);
729
730                 if (confirm_spawn) {
731                         char response;
732
733                         /* Set up terminal for the question */
734                         if ((r = setup_confirm_stdio(context,
735                                                      &saved_stdin, &saved_stdout)))
736                                 goto fail;
737
738                         /* Now ask the question. */
739                         if (!(line = exec_command_line(argv))) {
740                                 r = EXIT_MEMORY;
741                                 goto fail;
742                         }
743
744                         r = ask(&response, "yns", "Execute %s? [Yes, No, Skip] ", line);
745                         free(line);
746
747                         if (r < 0 || response == 'n') {
748                                 r = EXIT_CONFIRM;
749                                 goto fail;
750                         } else if (response == 's') {
751                                 r = 0;
752                                 goto fail;
753                         }
754
755                         /* Release terminal for the question */
756                         if ((r = restore_conform_stdio(context,
757                                                        &saved_stdin, &saved_stdout,
758                                                        &keep_stdin, &keep_stdout)))
759                                 goto fail;
760                 }
761
762                 if (!keep_stdin)
763                         if (setup_input(context) < 0) {
764                                 r = EXIT_STDIN;
765                                 goto fail;
766                         }
767
768                 if (!keep_stdout)
769                         if (setup_output(context, file_name_from_path(command->path)) < 0) {
770                                 r = EXIT_STDOUT;
771                                 goto fail;
772                         }
773
774                 if (setup_error(context, file_name_from_path(command->path)) < 0) {
775                         r = EXIT_STDERR;
776                         goto fail;
777                 }
778
779                 if (cgroup_bondings)
780                         if ((r = cgroup_bonding_install_list(cgroup_bondings, 0)) < 0) {
781                                 r = EXIT_CGROUP;
782                                 goto fail;
783                         }
784
785                 if (context->oom_adjust_set) {
786                         char t[16];
787
788                         snprintf(t, sizeof(t), "%i", context->oom_adjust);
789                         char_array_0(t);
790
791                         if (write_one_line_file("/proc/self/oom_adj", t) < 0) {
792                                 r = EXIT_OOM_ADJUST;
793                                 goto fail;
794                         }
795                 }
796
797                 if (context->nice_set)
798                         if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
799                                 r = EXIT_NICE;
800                                 goto fail;
801                         }
802
803                 if (context->cpu_sched_set) {
804                         struct sched_param param;
805
806                         zero(param);
807                         param.sched_priority = context->cpu_sched_priority;
808
809                         if (sched_setscheduler(0, context->cpu_sched_policy |
810                                                (context->cpu_sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0), &param) < 0) {
811                                 r = EXIT_SETSCHEDULER;
812                                 goto fail;
813                         }
814                 }
815
816                 if (context->cpu_affinity_set)
817                         if (sched_setaffinity(0, sizeof(context->cpu_affinity), &context->cpu_affinity) < 0) {
818                                 r = EXIT_CPUAFFINITY;
819                                 goto fail;
820                         }
821
822                 if (context->ioprio_set)
823                         if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
824                                 r = EXIT_IOPRIO;
825                                 goto fail;
826                         }
827
828                 if (context->timer_slack_ns_set)
829                         if (prctl(PR_SET_TIMERSLACK, context->timer_slack_ns_set) < 0) {
830                                 r = EXIT_TIMERSLACK;
831                                 goto fail;
832                         }
833
834                 if (context->user) {
835                         username = context->user;
836                         if (get_user_creds(&username, &uid, &gid, &home) < 0) {
837                                 r = EXIT_USER;
838                                 goto fail;
839                         }
840
841                         if (is_terminal_input(context->std_input))
842                                 if (chown_terminal(STDIN_FILENO, uid) < 0) {
843                                         r = EXIT_STDIN;
844                                         goto fail;
845                                 }
846                 }
847
848                 if (apply_permissions)
849                         if (enforce_groups(context, username, uid) < 0) {
850                                 r = EXIT_GROUP;
851                                 goto fail;
852                         }
853
854                 if (apply_chroot) {
855                         if (context->root_directory)
856                                 if (chroot(context->root_directory) < 0) {
857                                         r = EXIT_CHROOT;
858                                         goto fail;
859                                 }
860
861                         if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
862                                 r = EXIT_CHDIR;
863                                 goto fail;
864                         }
865                 } else {
866
867                         char *d;
868
869                         if (asprintf(&d, "%s/%s",
870                                      context->root_directory ? context->root_directory : "",
871                                      context->working_directory ? context->working_directory : "") < 0) {
872                                 r = EXIT_MEMORY;
873                                 goto fail;
874                         }
875
876                         if (chdir(d) < 0) {
877                                 free(d);
878                                 r = EXIT_CHDIR;
879                                 goto fail;
880                         }
881
882                         free(d);
883                 }
884
885                 if (close_all_fds(fds, n_fds) < 0 ||
886                     shift_fds(fds, n_fds) < 0 ||
887                     flags_fds(fds, n_fds, context->non_blocking) < 0) {
888                         r = EXIT_FDS;
889                         goto fail;
890                 }
891
892                 if (apply_permissions) {
893
894                         for (i = 0; i < RLIMIT_NLIMITS; i++) {
895                                 if (!context->rlimit[i])
896                                         continue;
897
898                                 if (setrlimit(i, context->rlimit[i]) < 0) {
899                                         r = EXIT_LIMITS;
900                                         goto fail;
901                                 }
902                         }
903
904                         if (context->user)
905                                 if (enforce_user(context, uid) < 0) {
906                                         r = EXIT_USER;
907                                         goto fail;
908                                 }
909
910                         /* PR_GET_SECUREBITS is not priviliged, while
911                          * PR_SET_SECUREBITS is. So to suppress
912                          * potential EPERMs we'll try not to call
913                          * PR_SET_SECUREBITS unless necessary. */
914                         if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
915                                 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
916                                         r = EXIT_SECUREBITS;
917                                         goto fail;
918                                 }
919
920                         if (context->capabilities)
921                                 if (cap_set_proc(context->capabilities) < 0) {
922                                         r = EXIT_CAPABILITIES;
923                                         goto fail;
924                                 }
925                 }
926
927                 if (!(our_env = new0(char*, 6))) {
928                         r = EXIT_MEMORY;
929                         goto fail;
930                 }
931
932                 if (n_fds > 0)
933                         if (asprintf(our_env + n_env++, "LISTEN_PID=%llu", (unsigned long long) getpid()) < 0 ||
934                             asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
935                                 r = EXIT_MEMORY;
936                                 goto fail;
937                         }
938
939                 if (home)
940                         if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
941                                 r = EXIT_MEMORY;
942                                 goto fail;
943                         }
944
945                 if (username)
946                         if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
947                             asprintf(our_env + n_env++, "USER=%s", username) < 0) {
948                                 r = EXIT_MEMORY;
949                                 goto fail;
950                         }
951
952                 if (!(final_env = strv_env_merge(environ, our_env, context->environment, NULL))) {
953                         r = EXIT_MEMORY;
954                         goto fail;
955                 }
956
957                 execve(command->path, argv, final_env);
958                 r = EXIT_EXEC;
959
960         fail:
961                 strv_free(our_env);
962                 strv_free(final_env);
963
964                 if (saved_stdin >= 0)
965                         close_nointr_nofail(saved_stdin);
966
967                 if (saved_stdout >= 0)
968                         close_nointr_nofail(saved_stdout);
969
970                 _exit(r);
971         }
972
973         /* We add the new process to the cgroup both in the child (so
974          * that we can be sure that no user code is ever executed
975          * outside of the cgroup) and in the parent (so that we can be
976          * sure that when we kill the cgroup the process will be
977          * killed too). */
978         if (cgroup_bondings)
979                 if ((r = cgroup_bonding_install_list(cgroup_bondings, pid)) < 0) {
980                         r = EXIT_CGROUP;
981                         goto fail;
982                 }
983
984         log_debug("Forked %s as %llu", command->path, (unsigned long long) pid);
985
986         command->exec_status.pid = pid;
987         command->exec_status.start_timestamp = now(CLOCK_REALTIME);
988
989         *ret = pid;
990         return 0;
991 }
992
993 void exec_context_init(ExecContext *c) {
994         assert(c);
995
996         c->umask = 0002;
997         c->oom_adjust = 0;
998         c->oom_adjust_set = false;
999         c->nice = 0;
1000         c->nice_set = false;
1001         c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
1002         c->ioprio_set = false;
1003         c->cpu_sched_policy = SCHED_OTHER;
1004         c->cpu_sched_priority = 0;
1005         c->cpu_sched_set = false;
1006         CPU_ZERO(&c->cpu_affinity);
1007         c->cpu_affinity_set = false;
1008         c->timer_slack_ns = 0;
1009         c->timer_slack_ns_set = false;
1010
1011         c->cpu_sched_reset_on_fork = false;
1012         c->non_blocking = false;
1013
1014         c->std_input = 0;
1015         c->std_output = 0;
1016         c->std_error = 0;
1017         c->syslog_priority = LOG_DAEMON|LOG_INFO;
1018
1019         c->secure_bits = 0;
1020         c->capability_bounding_set_drop = 0;
1021 }
1022
1023 void exec_context_done(ExecContext *c) {
1024         unsigned l;
1025
1026         assert(c);
1027
1028         strv_free(c->environment);
1029         c->environment = NULL;
1030
1031         for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
1032                 free(c->rlimit[l]);
1033                 c->rlimit[l] = NULL;
1034         }
1035
1036         free(c->working_directory);
1037         c->working_directory = NULL;
1038         free(c->root_directory);
1039         c->root_directory = NULL;
1040
1041         free(c->tty_path);
1042         c->tty_path = NULL;
1043
1044         free(c->syslog_identifier);
1045         c->syslog_identifier = NULL;
1046
1047         free(c->user);
1048         c->user = NULL;
1049
1050         free(c->group);
1051         c->group = NULL;
1052
1053         strv_free(c->supplementary_groups);
1054         c->supplementary_groups = NULL;
1055
1056         if (c->capabilities) {
1057                 cap_free(c->capabilities);
1058                 c->capabilities = NULL;
1059         }
1060 }
1061
1062 void exec_command_done(ExecCommand *c) {
1063         assert(c);
1064
1065         free(c->path);
1066         c->path = NULL;
1067
1068         strv_free(c->argv);
1069         c->argv = NULL;
1070 }
1071
1072 void exec_command_done_array(ExecCommand *c, unsigned n) {
1073         unsigned i;
1074
1075         for (i = 0; i < n; i++)
1076                 exec_command_done(c+i);
1077 }
1078
1079 void exec_command_free_list(ExecCommand *c) {
1080         ExecCommand *i;
1081
1082         while ((i = c)) {
1083                 LIST_REMOVE(ExecCommand, command, c, i);
1084                 exec_command_done(i);
1085                 free(i);
1086         }
1087 }
1088
1089 void exec_command_free_array(ExecCommand **c, unsigned n) {
1090         unsigned i;
1091
1092         for (i = 0; i < n; i++) {
1093                 exec_command_free_list(c[i]);
1094                 c[i] = NULL;
1095         }
1096 }
1097
1098 void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
1099         char ** e;
1100         unsigned i;
1101
1102         assert(c);
1103         assert(f);
1104
1105         if (!prefix)
1106                 prefix = "";
1107
1108         fprintf(f,
1109                 "%sUMask: %04o\n"
1110                 "%sWorkingDirectory: %s\n"
1111                 "%sRootDirectory: %s\n"
1112                 "%sNonBlocking: %s\n",
1113                 prefix, c->umask,
1114                 prefix, c->working_directory ? c->working_directory : "/",
1115                 prefix, c->root_directory ? c->root_directory : "/",
1116                 prefix, yes_no(c->non_blocking));
1117
1118         if (c->environment)
1119                 for (e = c->environment; *e; e++)
1120                         fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1121
1122         if (c->nice_set)
1123                 fprintf(f,
1124                         "%sNice: %i\n",
1125                         prefix, c->nice);
1126
1127         if (c->oom_adjust_set)
1128                 fprintf(f,
1129                         "%sOOMAdjust: %i\n",
1130                         prefix, c->oom_adjust);
1131
1132         for (i = 0; i < RLIM_NLIMITS; i++)
1133                 if (c->rlimit[i])
1134                         fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
1135
1136         if (c->ioprio_set)
1137                 fprintf(f,
1138                         "%sIOSchedulingClass: %s\n"
1139                         "%sIOPriority: %i\n",
1140                         prefix, ioprio_class_to_string(IOPRIO_PRIO_CLASS(c->ioprio)),
1141                         prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
1142
1143         if (c->cpu_sched_set)
1144                 fprintf(f,
1145                         "%sCPUSchedulingPolicy: %s\n"
1146                         "%sCPUSchedulingPriority: %i\n"
1147                         "%sCPUSchedulingResetOnFork: %s\n",
1148                         prefix, sched_policy_to_string(c->cpu_sched_policy),
1149                         prefix, c->cpu_sched_priority,
1150                         prefix, yes_no(c->cpu_sched_reset_on_fork));
1151
1152         if (c->cpu_affinity_set) {
1153                 fprintf(f, "%sCPUAffinity:", prefix);
1154                 for (i = 0; i < CPU_SETSIZE; i++)
1155                         if (CPU_ISSET(i, &c->cpu_affinity))
1156                                 fprintf(f, " %i", i);
1157                 fputs("\n", f);
1158         }
1159
1160         if (c->timer_slack_ns_set)
1161                 fprintf(f, "%sTimerSlackNS: %lu\n", prefix, c->timer_slack_ns);
1162
1163         fprintf(f,
1164                 "%sStandardInput: %s\n"
1165                 "%sStandardOutput: %s\n"
1166                 "%sStandardError: %s\n",
1167                 prefix, exec_input_to_string(c->std_input),
1168                 prefix, exec_output_to_string(c->std_output),
1169                 prefix, exec_output_to_string(c->std_error));
1170
1171         if (c->tty_path)
1172                 fprintf(f,
1173                         "%sTTYPath: %s\n",
1174                         prefix, c->tty_path);
1175
1176         if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KERNEL ||
1177             c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KERNEL)
1178                 fprintf(f,
1179                         "%sSyslogFacility: %s\n"
1180                         "%sSyslogLevel: %s\n",
1181                         prefix, log_facility_to_string(LOG_FAC(c->syslog_priority)),
1182                         prefix, log_level_to_string(LOG_PRI(c->syslog_priority)));
1183
1184         if (c->capabilities) {
1185                 char *t;
1186                 if ((t = cap_to_text(c->capabilities, NULL))) {
1187                         fprintf(f, "%sCapabilities: %s\n",
1188                                 prefix, t);
1189                         cap_free(t);
1190                 }
1191         }
1192
1193         if (c->secure_bits)
1194                 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1195                         prefix,
1196                         (c->secure_bits & SECURE_KEEP_CAPS) ? " keep-caps" : "",
1197                         (c->secure_bits & SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1198                         (c->secure_bits & SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1199                         (c->secure_bits & SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1200                         (c->secure_bits & SECURE_NOROOT) ? " noroot" : "",
1201                         (c->secure_bits & SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
1202
1203         if (c->capability_bounding_set_drop) {
1204                 fprintf(f, "%sCapabilityBoundingSetDrop:", prefix);
1205
1206                 for (i = 0; i <= CAP_LAST_CAP; i++)
1207                         if (c->capability_bounding_set_drop & (1 << i)) {
1208                                 char *t;
1209
1210                                 if ((t = cap_to_name(i))) {
1211                                         fprintf(f, " %s", t);
1212                                         free(t);
1213                                 }
1214                         }
1215
1216                 fputs("\n", f);
1217         }
1218
1219         if (c->user)
1220                 fprintf(f, "%sUser: %s", prefix, c->user);
1221         if (c->group)
1222                 fprintf(f, "%sGroup: %s", prefix, c->group);
1223
1224         if (c->supplementary_groups) {
1225                 char **g;
1226
1227                 fprintf(f, "%sSupplementaryGroups:", prefix);
1228
1229                 STRV_FOREACH(g, c->supplementary_groups)
1230                         fprintf(f, " %s", *g);
1231
1232                 fputs("\n", f);
1233         }
1234 }
1235
1236 void exec_status_fill(ExecStatus *s, pid_t pid, int code, int status) {
1237         assert(s);
1238
1239         s->pid = pid;
1240         s->exit_timestamp = now(CLOCK_REALTIME);
1241
1242         s->code = code;
1243         s->status = status;
1244 }
1245
1246 void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
1247         char buf[FORMAT_TIMESTAMP_MAX];
1248
1249         assert(s);
1250         assert(f);
1251
1252         if (!prefix)
1253                 prefix = "";
1254
1255         if (s->pid <= 0)
1256                 return;
1257
1258         fprintf(f,
1259                 "%sPID: %llu\n",
1260                 prefix, (unsigned long long) s->pid);
1261
1262         if (s->start_timestamp > 0)
1263                 fprintf(f,
1264                         "%sStart Timestamp: %s\n",
1265                         prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp));
1266
1267         if (s->exit_timestamp > 0)
1268                 fprintf(f,
1269                         "%sExit Timestamp: %s\n"
1270                         "%sExit Code: %s\n"
1271                         "%sExit Status: %i\n",
1272                         prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp),
1273                         prefix, sigchld_code_to_string(s->code),
1274                         prefix, s->status);
1275 }
1276
1277 char *exec_command_line(char **argv) {
1278         size_t k;
1279         char *n, *p, **a;
1280         bool first = true;
1281
1282         assert(argv);
1283
1284         k = 1;
1285         STRV_FOREACH(a, argv)
1286                 k += strlen(*a)+3;
1287
1288         if (!(n = new(char, k)))
1289                 return NULL;
1290
1291         p = n;
1292         STRV_FOREACH(a, argv) {
1293
1294                 if (!first)
1295                         *(p++) = ' ';
1296                 else
1297                         first = false;
1298
1299                 if (strpbrk(*a, WHITESPACE)) {
1300                         *(p++) = '\'';
1301                         p = stpcpy(p, *a);
1302                         *(p++) = '\'';
1303                 } else
1304                         p = stpcpy(p, *a);
1305
1306         }
1307
1308         *p = 0;
1309
1310         /* FIXME: this doesn't really handle arguments that have
1311          * spaces and ticks in them */
1312
1313         return n;
1314 }
1315
1316 void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
1317         char *p2;
1318         const char *prefix2;
1319
1320         char *cmd;
1321
1322         assert(c);
1323         assert(f);
1324
1325         if (!prefix)
1326                 prefix = "";
1327         p2 = strappend(prefix, "\t");
1328         prefix2 = p2 ? p2 : prefix;
1329
1330         cmd = exec_command_line(c->argv);
1331
1332         fprintf(f,
1333                 "%sCommand Line: %s\n",
1334                 prefix, cmd ? cmd : strerror(ENOMEM));
1335
1336         free(cmd);
1337
1338         exec_status_dump(&c->exec_status, f, prefix2);
1339
1340         free(p2);
1341 }
1342
1343 void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
1344         assert(f);
1345
1346         if (!prefix)
1347                 prefix = "";
1348
1349         LIST_FOREACH(command, c, c)
1350                 exec_command_dump(c, f, prefix);
1351 }
1352
1353 void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
1354         ExecCommand *end;
1355
1356         assert(l);
1357         assert(e);
1358
1359         if (*l) {
1360                 /* It's kinda important that we keep the order here */
1361                 LIST_FIND_TAIL(ExecCommand, command, *l, end);
1362                 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
1363         } else
1364               *l = e;
1365 }
1366
1367 int exec_command_set(ExecCommand *c, const char *path, ...) {
1368         va_list ap;
1369         char **l, *p;
1370
1371         assert(c);
1372         assert(path);
1373
1374         va_start(ap, path);
1375         l = strv_new_ap(path, ap);
1376         va_end(ap);
1377
1378         if (!l)
1379                 return -ENOMEM;
1380
1381         if (!(p = strdup(path))) {
1382                 strv_free(l);
1383                 return -ENOMEM;
1384         }
1385
1386         free(c->path);
1387         c->path = p;
1388
1389         strv_free(c->argv);
1390         c->argv = l;
1391
1392         return 0;
1393 }
1394
1395 const char* exit_status_to_string(ExitStatus status) {
1396
1397         /* We cast to int here, so that -Wenum doesn't complain that
1398          * EXIT_SUCCESS/EXIT_FAILURE aren't in the enum */
1399
1400         switch ((int) status) {
1401
1402         case EXIT_SUCCESS:
1403                 return "SUCCESS";
1404
1405         case EXIT_FAILURE:
1406                 return "FAILURE";
1407
1408         case EXIT_INVALIDARGUMENT:
1409                 return "INVALIDARGUMENT";
1410
1411         case EXIT_NOTIMPLEMENTED:
1412                 return "NOTIMPLEMENTED";
1413
1414         case EXIT_NOPERMISSION:
1415                 return "NOPERMISSION";
1416
1417         case EXIT_NOTINSTALLED:
1418                 return "NOTINSSTALLED";
1419
1420         case EXIT_NOTCONFIGURED:
1421                 return "NOTCONFIGURED";
1422
1423         case EXIT_NOTRUNNING:
1424                 return "NOTRUNNING";
1425
1426         case EXIT_CHDIR:
1427                 return "CHDIR";
1428
1429         case EXIT_NICE:
1430                 return "NICE";
1431
1432         case EXIT_FDS:
1433                 return "FDS";
1434
1435         case EXIT_EXEC:
1436                 return "EXEC";
1437
1438         case EXIT_MEMORY:
1439                 return "MEMORY";
1440
1441         case EXIT_LIMITS:
1442                 return "LIMITS";
1443
1444         case EXIT_OOM_ADJUST:
1445                 return "OOM_ADJUST";
1446
1447         case EXIT_SIGNAL_MASK:
1448                 return "SIGNAL_MASK";
1449
1450         case EXIT_STDIN:
1451                 return "STDIN";
1452
1453         case EXIT_STDOUT:
1454                 return "STDOUT";
1455
1456         case EXIT_CHROOT:
1457                 return "CHROOT";
1458
1459         case EXIT_IOPRIO:
1460                 return "IOPRIO";
1461
1462         case EXIT_TIMERSLACK:
1463                 return "TIMERSLACK";
1464
1465         case EXIT_SECUREBITS:
1466                 return "SECUREBITS";
1467
1468         case EXIT_SETSCHEDULER:
1469                 return "SETSCHEDULER";
1470
1471         case EXIT_CPUAFFINITY:
1472                 return "CPUAFFINITY";
1473
1474         case EXIT_GROUP:
1475                 return "GROUP";
1476
1477         case EXIT_USER:
1478                 return "USER";
1479
1480         case EXIT_CAPABILITIES:
1481                 return "CAPABILITIES";
1482
1483         case EXIT_CGROUP:
1484                 return "CGROUP";
1485
1486         case EXIT_SETSID:
1487                 return "SETSID";
1488
1489         case EXIT_CONFIRM:
1490                 return "CONFIRM";
1491
1492         case EXIT_STDERR:
1493                 return "STDERR";
1494
1495         default:
1496                 return NULL;
1497         }
1498 }
1499
1500 static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
1501         [EXEC_INPUT_NULL] = "null",
1502         [EXEC_INPUT_TTY] = "tty",
1503         [EXEC_INPUT_TTY_FORCE] = "tty-force",
1504         [EXEC_INPUT_TTY_FAIL] = "tty-fail"
1505 };
1506
1507 static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
1508         [EXEC_OUTPUT_INHERIT] = "inherit",
1509         [EXEC_OUTPUT_NULL] = "null",
1510         [EXEC_OUTPUT_TTY] = "tty",
1511         [EXEC_OUTPUT_SYSLOG] = "syslog",
1512         [EXEC_OUTPUT_KERNEL] = "kernel"
1513 };
1514
1515 DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
1516
1517 DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);