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