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