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