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