]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
man: add not to not use -x in bug reports
[thirdparty/systemd.git] / src / core / execute.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
5cb5a6ff 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
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
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
5430f7f2 16 Lesser General Public License for more details.
a7334b09 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
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>
dd6c17b1 39#include <linux/oom.h>
f2b68789 40#include <sys/poll.h>
8351ceae 41#include <linux/seccomp-bpf.h>
2bef10ab 42#include <glob.h>
d34cd374 43#include <libgen.h>
5cb5a6ff 44
5b6319dc
LP
45#ifdef HAVE_PAM
46#include <security/pam_appl.h>
47#endif
48
5cb5a6ff
LP
49#include "execute.h"
50#include "strv.h"
51#include "macro.h"
d7832d2c 52#include "capability.h"
5cb5a6ff 53#include "util.h"
acbb0225 54#include "log.h"
20ad4cfd 55#include "sd-messages.h"
9eba9da4 56#include "ioprio.h"
94f04347 57#include "securebits.h"
15ae422b 58#include "namespace.h"
df1f0afe 59#include "tcpwrap.h"
d06dacd0 60#include "exit-status.h"
dd6c17b1 61#include "missing.h"
169c1bda 62#include "utmp-wtmp.h"
f6a6225e 63#include "def.h"
ff01d048 64#include "loopback-setup.h"
9eb977db 65#include "path-util.h"
8351ceae 66#include "syscall-list.h"
4d1a6904 67#include "env-util.h"
a5c32cff 68#include "fileio.h"
4ad49000 69#include "unit.h"
5cb5a6ff 70
e056b01d 71#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
31a7eb86 72#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
e6a26745 73
02a51aba
LP
74/* This assumes there is a 'tty' group */
75#define TTY_MODE 0620
76
034c6ed7
LP
77static int shift_fds(int fds[], unsigned n_fds) {
78 int start, restart_from;
79
80 if (n_fds <= 0)
81 return 0;
82
a0d40ac5
LP
83 /* Modifies the fds array! (sorts it) */
84
034c6ed7
LP
85 assert(fds);
86
87 start = 0;
88 for (;;) {
89 int i;
90
91 restart_from = -1;
92
93 for (i = start; i < (int) n_fds; i++) {
94 int nfd;
95
96 /* Already at right index? */
97 if (fds[i] == i+3)
98 continue;
99
100 if ((nfd = fcntl(fds[i], F_DUPFD, i+3)) < 0)
101 return -errno;
102
e1f5e051 103 close_nointr_nofail(fds[i]);
034c6ed7
LP
104 fds[i] = nfd;
105
106 /* Hmm, the fd we wanted isn't free? Then
107 * let's remember that and try again from here*/
108 if (nfd != i+3 && restart_from < 0)
109 restart_from = i;
110 }
111
112 if (restart_from < 0)
113 break;
114
115 start = restart_from;
116 }
117
118 return 0;
119}
120
c2748801 121static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
47a71eed 122 unsigned i;
e2c76839 123 int r;
47a71eed
LP
124
125 if (n_fds <= 0)
126 return 0;
127
128 assert(fds);
129
451a074f 130 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
47a71eed
LP
131
132 for (i = 0; i < n_fds; i++) {
47a71eed 133
e2c76839
LP
134 if ((r = fd_nonblock(fds[i], nonblock)) < 0)
135 return r;
47a71eed 136
451a074f
LP
137 /* We unconditionally drop FD_CLOEXEC from the fds,
138 * since after all we want to pass these fds to our
139 * children */
47a71eed 140
e2c76839
LP
141 if ((r = fd_cloexec(fds[i], false)) < 0)
142 return r;
47a71eed
LP
143 }
144
145 return 0;
146}
147
44a6b1b6 148_pure_ static const char *tty_path(const ExecContext *context) {
80876c20
LP
149 assert(context);
150
151 if (context->tty_path)
152 return context->tty_path;
153
154 return "/dev/console";
155}
156
6ea832a2
LP
157void exec_context_tty_reset(const ExecContext *context) {
158 assert(context);
159
160 if (context->tty_vhangup)
161 terminal_vhangup(tty_path(context));
162
163 if (context->tty_reset)
164 reset_terminal(tty_path(context));
165
166 if (context->tty_vt_disallocate && context->tty_path)
167 vt_disallocate(context->tty_path);
168}
169
3a1286b6
MS
170static bool is_terminal_output(ExecOutput o) {
171 return
172 o == EXEC_OUTPUT_TTY ||
173 o == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
174 o == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
175 o == EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
176}
177
c17ec25e
MS
178void exec_context_serialize(const ExecContext *context, Unit *u, FILE *f) {
179 assert(context);
180 assert(u);
181 assert(f);
182
183 if (context->tmp_dir)
184 unit_serialize_item(u, f, "tmp-dir", context->tmp_dir);
185
186 if (context->var_tmp_dir)
187 unit_serialize_item(u, f, "var-tmp-dir", context->var_tmp_dir);
188}
189
80876c20
LP
190static int open_null_as(int flags, int nfd) {
191 int fd, r;
071830ff 192
80876c20 193 assert(nfd >= 0);
071830ff 194
80876c20 195 if ((fd = open("/dev/null", flags|O_NOCTTY)) < 0)
071830ff
LP
196 return -errno;
197
80876c20
LP
198 if (fd != nfd) {
199 r = dup2(fd, nfd) < 0 ? -errno : nfd;
e1f5e051 200 close_nointr_nofail(fd);
80876c20
LP
201 } else
202 r = nfd;
071830ff 203
80876c20 204 return r;
071830ff
LP
205}
206
62bca2c6 207static int connect_logger_as(const ExecContext *context, ExecOutput output, const char *ident, const char *unit_id, int nfd) {
80876c20 208 int fd, r;
b92bea5d
ZJS
209 union sockaddr_union sa = {
210 .un.sun_family = AF_UNIX,
211 .un.sun_path = "/run/systemd/journal/stdout",
212 };
071830ff
LP
213
214 assert(context);
80876c20
LP
215 assert(output < _EXEC_OUTPUT_MAX);
216 assert(ident);
217 assert(nfd >= 0);
071830ff 218
54fe0cdb
LP
219 fd = socket(AF_UNIX, SOCK_STREAM, 0);
220 if (fd < 0)
80876c20 221 return -errno;
071830ff 222
54fe0cdb
LP
223 r = connect(fd, &sa.sa, offsetof(struct sockaddr_un, sun_path) + strlen(sa.un.sun_path));
224 if (r < 0) {
80876c20
LP
225 close_nointr_nofail(fd);
226 return -errno;
227 }
071830ff 228
80876c20
LP
229 if (shutdown(fd, SHUT_RD) < 0) {
230 close_nointr_nofail(fd);
231 return -errno;
232 }
071830ff 233
80876c20 234 dprintf(fd,
62bca2c6 235 "%s\n"
80876c20
LP
236 "%s\n"
237 "%i\n"
54fe0cdb
LP
238 "%i\n"
239 "%i\n"
240 "%i\n"
4f4a1dbf 241 "%i\n",
4f4a1dbf 242 context->syslog_identifier ? context->syslog_identifier : ident,
62bca2c6 243 unit_id,
54fe0cdb
LP
244 context->syslog_priority,
245 !!context->syslog_level_prefix,
246 output == EXEC_OUTPUT_SYSLOG || output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
247 output == EXEC_OUTPUT_KMSG || output == EXEC_OUTPUT_KMSG_AND_CONSOLE,
3a1286b6 248 is_terminal_output(output));
80876c20
LP
249
250 if (fd != nfd) {
251 r = dup2(fd, nfd) < 0 ? -errno : nfd;
e1f5e051 252 close_nointr_nofail(fd);
80876c20
LP
253 } else
254 r = nfd;
071830ff 255
80876c20
LP
256 return r;
257}
258static int open_terminal_as(const char *path, mode_t mode, int nfd) {
259 int fd, r;
071830ff 260
80876c20
LP
261 assert(path);
262 assert(nfd >= 0);
071830ff 263
80876c20
LP
264 if ((fd = open_terminal(path, mode | O_NOCTTY)) < 0)
265 return fd;
071830ff 266
80876c20
LP
267 if (fd != nfd) {
268 r = dup2(fd, nfd) < 0 ? -errno : nfd;
269 close_nointr_nofail(fd);
270 } else
271 r = nfd;
071830ff 272
80876c20
LP
273 return r;
274}
071830ff 275
80876c20
LP
276static bool is_terminal_input(ExecInput i) {
277 return
278 i == EXEC_INPUT_TTY ||
279 i == EXEC_INPUT_TTY_FORCE ||
280 i == EXEC_INPUT_TTY_FAIL;
281}
071830ff 282
1e3ad081
LP
283static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
284
285 if (is_terminal_input(std_input) && !apply_tty_stdin)
286 return EXEC_INPUT_NULL;
071830ff 287
03fd9c49 288 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
289 return EXEC_INPUT_NULL;
290
03fd9c49 291 return std_input;
4f2d528d
LP
292}
293
03fd9c49 294static int fixup_output(ExecOutput std_output, int socket_fd) {
4f2d528d 295
03fd9c49 296 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
297 return EXEC_OUTPUT_INHERIT;
298
03fd9c49 299 return std_output;
4f2d528d
LP
300}
301
1e3ad081 302static int setup_input(const ExecContext *context, int socket_fd, bool apply_tty_stdin) {
4f2d528d
LP
303 ExecInput i;
304
305 assert(context);
306
1e3ad081 307 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
4f2d528d
LP
308
309 switch (i) {
071830ff 310
80876c20
LP
311 case EXEC_INPUT_NULL:
312 return open_null_as(O_RDONLY, STDIN_FILENO);
313
314 case EXEC_INPUT_TTY:
315 case EXEC_INPUT_TTY_FORCE:
316 case EXEC_INPUT_TTY_FAIL: {
317 int fd, r;
071830ff 318
80876c20
LP
319 if ((fd = acquire_terminal(
320 tty_path(context),
4f2d528d 321 i == EXEC_INPUT_TTY_FAIL,
21de3988 322 i == EXEC_INPUT_TTY_FORCE,
af6da548
LP
323 false,
324 (usec_t) -1)) < 0)
80876c20
LP
325 return fd;
326
327 if (fd != STDIN_FILENO) {
328 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
071830ff 329 close_nointr_nofail(fd);
80876c20
LP
330 } else
331 r = STDIN_FILENO;
332
333 return r;
334 }
335
4f2d528d
LP
336 case EXEC_INPUT_SOCKET:
337 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
338
80876c20
LP
339 default:
340 assert_not_reached("Unknown input type");
341 }
342}
343
eb17e935 344static int setup_output(const ExecContext *context, int fileno, int socket_fd, const char *ident, const char *unit_id, bool apply_tty_stdin) {
4f2d528d
LP
345 ExecOutput o;
346 ExecInput i;
47c1d80d 347 int r;
4f2d528d 348
80876c20
LP
349 assert(context);
350 assert(ident);
351
1e3ad081 352 i = fixup_input(context->std_input, socket_fd, apply_tty_stdin);
03fd9c49 353 o = fixup_output(context->std_output, socket_fd);
4f2d528d 354
eb17e935
MS
355 if (fileno == STDERR_FILENO) {
356 ExecOutput e;
357 e = fixup_output(context->std_error, socket_fd);
80876c20 358
eb17e935
MS
359 /* This expects the input and output are already set up */
360
361 /* Don't change the stderr file descriptor if we inherit all
362 * the way and are not on a tty */
363 if (e == EXEC_OUTPUT_INHERIT &&
364 o == EXEC_OUTPUT_INHERIT &&
365 i == EXEC_INPUT_NULL &&
366 !is_terminal_input(context->std_input) &&
367 getppid () != 1)
368 return fileno;
369
370 /* Duplicate from stdout if possible */
371 if (e == o || e == EXEC_OUTPUT_INHERIT)
372 return dup2(STDOUT_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 373
eb17e935 374 o = e;
80876c20 375
eb17e935 376 } else if (o == EXEC_OUTPUT_INHERIT) {
21d21ea4
LP
377 /* If input got downgraded, inherit the original value */
378 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
eb17e935 379 return open_terminal_as(tty_path(context), O_WRONLY, fileno);
21d21ea4 380
acb591e4 381 /* If the input is connected to anything that's not a /dev/null, inherit that... */
ff876e28 382 if (i != EXEC_INPUT_NULL)
eb17e935 383 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 384
acb591e4
LP
385 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
386 if (getppid() != 1)
eb17e935 387 return fileno;
94f04347 388
eb17e935
MS
389 /* We need to open /dev/null here anew, to get the right access mode. */
390 return open_null_as(O_WRONLY, fileno);
071830ff 391 }
94f04347 392
eb17e935 393 switch (o) {
80876c20
LP
394
395 case EXEC_OUTPUT_NULL:
eb17e935 396 return open_null_as(O_WRONLY, fileno);
80876c20
LP
397
398 case EXEC_OUTPUT_TTY:
4f2d528d 399 if (is_terminal_input(i))
eb17e935 400 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
80876c20
LP
401
402 /* We don't reset the terminal if this is just about output */
eb17e935 403 return open_terminal_as(tty_path(context), O_WRONLY, fileno);
80876c20
LP
404
405 case EXEC_OUTPUT_SYSLOG:
28dbc1e8 406 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE:
9a6bca7a 407 case EXEC_OUTPUT_KMSG:
28dbc1e8 408 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
706343f4
LP
409 case EXEC_OUTPUT_JOURNAL:
410 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
eb17e935 411 r = connect_logger_as(context, o, ident, unit_id, fileno);
47c1d80d 412 if (r < 0) {
80cbda35
MS
413 log_struct_unit(LOG_CRIT, unit_id,
414 "MESSAGE=Failed to connect std%s of %s to the journal socket: %s",
eb17e935 415 fileno == STDOUT_FILENO ? "out" : "err",
80cbda35
MS
416 unit_id, strerror(-r),
417 "ERRNO=%d", -r,
418 NULL);
eb17e935 419 r = open_null_as(O_WRONLY, fileno);
47c1d80d
MS
420 }
421 return r;
4f2d528d
LP
422
423 case EXEC_OUTPUT_SOCKET:
424 assert(socket_fd >= 0);
eb17e935 425 return dup2(socket_fd, fileno) < 0 ? -errno : fileno;
94f04347
LP
426
427 default:
80876c20 428 assert_not_reached("Unknown error type");
94f04347 429 }
071830ff
LP
430}
431
02a51aba
LP
432static int chown_terminal(int fd, uid_t uid) {
433 struct stat st;
434
435 assert(fd >= 0);
02a51aba
LP
436
437 /* This might fail. What matters are the results. */
bab45044
LP
438 (void) fchown(fd, uid, -1);
439 (void) fchmod(fd, TTY_MODE);
02a51aba
LP
440
441 if (fstat(fd, &st) < 0)
442 return -errno;
443
d8b4e2e9 444 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
02a51aba
LP
445 return -EPERM;
446
447 return 0;
448}
449
af6da548 450static int setup_confirm_stdio(int *_saved_stdin,
80876c20
LP
451 int *_saved_stdout) {
452 int fd = -1, saved_stdin, saved_stdout = -1, r;
453
80876c20
LP
454 assert(_saved_stdin);
455 assert(_saved_stdout);
456
af6da548
LP
457 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
458 if (saved_stdin < 0)
459 return -errno;
80876c20 460
af6da548
LP
461 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
462 if (saved_stdout < 0) {
463 r = errno;
80876c20
LP
464 goto fail;
465 }
466
af6da548
LP
467 fd = acquire_terminal(
468 "/dev/console",
469 false,
470 false,
471 false,
472 DEFAULT_CONFIRM_USEC);
473 if (fd < 0) {
474 r = fd;
80876c20
LP
475 goto fail;
476 }
477
af6da548
LP
478 r = chown_terminal(fd, getuid());
479 if (r < 0)
02a51aba 480 goto fail;
02a51aba 481
80876c20 482 if (dup2(fd, STDIN_FILENO) < 0) {
af6da548 483 r = -errno;
80876c20
LP
484 goto fail;
485 }
486
487 if (dup2(fd, STDOUT_FILENO) < 0) {
af6da548 488 r = -errno;
80876c20
LP
489 goto fail;
490 }
491
492 if (fd >= 2)
493 close_nointr_nofail(fd);
494
495 *_saved_stdin = saved_stdin;
496 *_saved_stdout = saved_stdout;
497
498 return 0;
499
500fail:
501 if (saved_stdout >= 0)
502 close_nointr_nofail(saved_stdout);
503
504 if (saved_stdin >= 0)
505 close_nointr_nofail(saved_stdin);
506
507 if (fd >= 0)
508 close_nointr_nofail(fd);
509
510 return r;
511}
512
44a6b1b6 513_printf_attr_(1, 2) static int write_confirm_message(const char *format, ...) {
af6da548
LP
514 int fd;
515 va_list ap;
80876c20 516
af6da548 517 assert(format);
80876c20 518
af6da548
LP
519 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
520 if (fd < 0)
521 return fd;
80876c20 522
af6da548
LP
523 va_start(ap, format);
524 vdprintf(fd, format, ap);
525 va_end(ap);
80876c20 526
af6da548 527 close_nointr_nofail(fd);
80876c20 528
af6da548
LP
529 return 0;
530}
80876c20 531
af6da548
LP
532static int restore_confirm_stdio(int *saved_stdin,
533 int *saved_stdout) {
80876c20 534
af6da548 535 int r = 0;
80876c20 536
af6da548
LP
537 assert(saved_stdin);
538 assert(saved_stdout);
539
540 release_terminal();
541
542 if (*saved_stdin >= 0)
80876c20 543 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
af6da548 544 r = -errno;
80876c20 545
af6da548 546 if (*saved_stdout >= 0)
80876c20 547 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
af6da548 548 r = -errno;
80876c20 549
af6da548
LP
550 if (*saved_stdin >= 0)
551 close_nointr_nofail(*saved_stdin);
80876c20 552
af6da548
LP
553 if (*saved_stdout >= 0)
554 close_nointr_nofail(*saved_stdout);
555
556 return r;
557}
558
559static int ask_for_confirmation(char *response, char **argv) {
560 int saved_stdout = -1, saved_stdin = -1, r;
561 char *line;
562
563 r = setup_confirm_stdio(&saved_stdin, &saved_stdout);
564 if (r < 0)
565 return r;
566
567 line = exec_command_line(argv);
568 if (!line)
569 return -ENOMEM;
570
571 r = ask(response, "yns", "Execute %s? [Yes, No, Skip] ", line);
572 free(line);
573
574 restore_confirm_stdio(&saved_stdin, &saved_stdout);
575
576 return r;
80876c20
LP
577}
578
81a2b7ce
LP
579static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
580 bool keep_groups = false;
581 int r;
582
583 assert(context);
584
35b8ca3a 585 /* Lookup and set GID and supplementary group list. Here too
81a2b7ce
LP
586 * we avoid NSS lookups for gid=0. */
587
588 if (context->group || username) {
589
4b67834e
LP
590 if (context->group) {
591 const char *g = context->group;
592
593 if ((r = get_group_creds(&g, &gid)) < 0)
81a2b7ce 594 return r;
4b67834e 595 }
81a2b7ce
LP
596
597 /* First step, initialize groups from /etc/groups */
598 if (username && gid != 0) {
599 if (initgroups(username, gid) < 0)
600 return -errno;
601
602 keep_groups = true;
603 }
604
605 /* Second step, set our gids */
606 if (setresgid(gid, gid, gid) < 0)
607 return -errno;
608 }
609
610 if (context->supplementary_groups) {
611 int ngroups_max, k;
612 gid_t *gids;
613 char **i;
614
615 /* Final step, initialize any manually set supplementary groups */
da19d5c1 616 assert_se((ngroups_max = (int) sysconf(_SC_NGROUPS_MAX)) > 0);
81a2b7ce
LP
617
618 if (!(gids = new(gid_t, ngroups_max)))
619 return -ENOMEM;
620
621 if (keep_groups) {
622 if ((k = getgroups(ngroups_max, gids)) < 0) {
623 free(gids);
624 return -errno;
625 }
626 } else
627 k = 0;
628
629 STRV_FOREACH(i, context->supplementary_groups) {
4b67834e 630 const char *g;
81a2b7ce
LP
631
632 if (k >= ngroups_max) {
633 free(gids);
634 return -E2BIG;
635 }
636
4b67834e
LP
637 g = *i;
638 r = get_group_creds(&g, gids+k);
639 if (r < 0) {
81a2b7ce
LP
640 free(gids);
641 return r;
642 }
643
644 k++;
645 }
646
647 if (setgroups(k, gids) < 0) {
648 free(gids);
649 return -errno;
650 }
651
652 free(gids);
653 }
654
655 return 0;
656}
657
658static int enforce_user(const ExecContext *context, uid_t uid) {
659 int r;
660 assert(context);
661
662 /* Sets (but doesn't lookup) the uid and make sure we keep the
663 * capabilities while doing so. */
664
665 if (context->capabilities) {
666 cap_t d;
667 static const cap_value_t bits[] = {
668 CAP_SETUID, /* Necessary so that we can run setresuid() below */
669 CAP_SETPCAP /* Necessary so that we can set PR_SET_SECUREBITS later on */
670 };
671
672 /* First step: If we need to keep capabilities but
673 * drop privileges we need to make sure we keep our
cbb21cca 674 * caps, while we drop privileges. */
693ced48 675 if (uid != 0) {
cbb21cca 676 int sb = context->secure_bits | 1<<SECURE_KEEP_CAPS;
693ced48
LP
677
678 if (prctl(PR_GET_SECUREBITS) != sb)
679 if (prctl(PR_SET_SECUREBITS, sb) < 0)
680 return -errno;
681 }
81a2b7ce 682
35b8ca3a 683 /* Second step: set the capabilities. This will reduce
81a2b7ce
LP
684 * the capabilities to the minimum we need. */
685
686 if (!(d = cap_dup(context->capabilities)))
687 return -errno;
688
689 if (cap_set_flag(d, CAP_EFFECTIVE, ELEMENTSOF(bits), bits, CAP_SET) < 0 ||
690 cap_set_flag(d, CAP_PERMITTED, ELEMENTSOF(bits), bits, CAP_SET) < 0) {
691 r = -errno;
692 cap_free(d);
693 return r;
694 }
695
696 if (cap_set_proc(d) < 0) {
697 r = -errno;
698 cap_free(d);
699 return r;
700 }
701
702 cap_free(d);
703 }
704
705 /* Third step: actually set the uids */
706 if (setresuid(uid, uid, uid) < 0)
707 return -errno;
708
709 /* At this point we should have all necessary capabilities but
710 are otherwise a normal user. However, the caps might got
711 corrupted due to the setresuid() so we need clean them up
712 later. This is done outside of this call. */
713
714 return 0;
715}
716
5b6319dc
LP
717#ifdef HAVE_PAM
718
719static int null_conv(
720 int num_msg,
721 const struct pam_message **msg,
722 struct pam_response **resp,
723 void *appdata_ptr) {
724
725 /* We don't support conversations */
726
727 return PAM_CONV_ERR;
728}
729
730static int setup_pam(
731 const char *name,
732 const char *user,
940c5210 733 uid_t uid,
5b6319dc
LP
734 const char *tty,
735 char ***pam_env,
736 int fds[], unsigned n_fds) {
737
738 static const struct pam_conv conv = {
739 .conv = null_conv,
740 .appdata_ptr = NULL
741 };
742
743 pam_handle_t *handle = NULL;
744 sigset_t ss, old_ss;
745 int pam_code = PAM_SUCCESS;
9ba35398 746 int err;
5b6319dc
LP
747 char **e = NULL;
748 bool close_session = false;
749 pid_t pam_pid = 0, parent_pid;
750
751 assert(name);
752 assert(user);
753 assert(pam_env);
754
755 /* We set up PAM in the parent process, then fork. The child
35b8ca3a 756 * will then stay around until killed via PR_GET_PDEATHSIG or
5b6319dc
LP
757 * systemd via the cgroup logic. It will then remove the PAM
758 * session again. The parent process will exec() the actual
759 * daemon. We do things this way to ensure that the main PID
760 * of the daemon is the one we initially fork()ed. */
761
762 if ((pam_code = pam_start(name, user, &conv, &handle)) != PAM_SUCCESS) {
763 handle = NULL;
764 goto fail;
765 }
766
767 if (tty)
768 if ((pam_code = pam_set_item(handle, PAM_TTY, tty)) != PAM_SUCCESS)
769 goto fail;
770
771 if ((pam_code = pam_acct_mgmt(handle, PAM_SILENT)) != PAM_SUCCESS)
772 goto fail;
773
774 if ((pam_code = pam_open_session(handle, PAM_SILENT)) != PAM_SUCCESS)
775 goto fail;
776
777 close_session = true;
778
5b6319dc
LP
779 if ((!(e = pam_getenvlist(handle)))) {
780 pam_code = PAM_BUF_ERR;
781 goto fail;
782 }
783
784 /* Block SIGTERM, so that we know that it won't get lost in
785 * the child */
786 if (sigemptyset(&ss) < 0 ||
787 sigaddset(&ss, SIGTERM) < 0 ||
788 sigprocmask(SIG_BLOCK, &ss, &old_ss) < 0)
789 goto fail;
790
791 parent_pid = getpid();
792
793 if ((pam_pid = fork()) < 0)
794 goto fail;
795
796 if (pam_pid == 0) {
797 int sig;
798 int r = EXIT_PAM;
799
800 /* The child's job is to reset the PAM session on
801 * termination */
802
803 /* This string must fit in 10 chars (i.e. the length
5d6b1584
LP
804 * of "/sbin/init"), to look pretty in /bin/ps */
805 rename_process("(sd-pam)");
5b6319dc
LP
806
807 /* Make sure we don't keep open the passed fds in this
808 child. We assume that otherwise only those fds are
809 open here that have been opened by PAM. */
810 close_many(fds, n_fds);
811
940c5210
AK
812 /* Drop privileges - we don't need any to pam_close_session
813 * and this will make PR_SET_PDEATHSIG work in most cases.
814 * If this fails, ignore the error - but expect sd-pam threads
815 * to fail to exit normally */
816 if (setresuid(uid, uid, uid) < 0)
817 log_error("Error: Failed to setresuid() in sd-pam: %s", strerror(-r));
818
819 /* Wait until our parent died. This will only work if
820 * the above setresuid() succeeds, otherwise the kernel
821 * will not allow unprivileged parents kill their privileged
822 * children this way. We rely on the control groups kill logic
5b6319dc
LP
823 * to do the rest for us. */
824 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
825 goto child_finish;
826
827 /* Check if our parent process might already have
828 * died? */
829 if (getppid() == parent_pid) {
3dead8d9
LP
830 for (;;) {
831 if (sigwait(&ss, &sig) < 0) {
832 if (errno == EINTR)
833 continue;
834
835 goto child_finish;
836 }
5b6319dc 837
3dead8d9
LP
838 assert(sig == SIGTERM);
839 break;
840 }
5b6319dc
LP
841 }
842
3dead8d9 843 /* If our parent died we'll end the session */
5b6319dc
LP
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
3b8bddde 859 /* Unblock SIGTERM again in the parent */
5b6319dc
LP
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
aa87e624
LP
867 *pam_env = e;
868 e = NULL;
869
5b6319dc
LP
870 return 0;
871
872fail:
9ba35398
MS
873 if (pam_code != PAM_SUCCESS)
874 err = -EPERM; /* PAM errors do not map to errno */
875 else
876 err = -errno;
877
5b6319dc
LP
878 if (handle) {
879 if (close_session)
880 pam_code = pam_close_session(handle, PAM_DATA_SILENT);
881
882 pam_end(handle, pam_code | PAM_DATA_SILENT);
883 }
884
885 strv_free(e);
886
887 closelog();
888
430c18ed 889 if (pam_pid > 1) {
5b6319dc 890 kill(pam_pid, SIGTERM);
430c18ed
LP
891 kill(pam_pid, SIGCONT);
892 }
5b6319dc 893
9ba35398 894 return err;
5b6319dc
LP
895}
896#endif
897
5d6b1584
LP
898static void rename_process_from_path(const char *path) {
899 char process_name[11];
900 const char *p;
901 size_t l;
902
903 /* This resulting string must fit in 10 chars (i.e. the length
904 * of "/sbin/init") to look pretty in /bin/ps */
905
9eb977db 906 p = path_get_file_name(path);
5d6b1584
LP
907 if (isempty(p)) {
908 rename_process("(...)");
909 return;
910 }
911
912 l = strlen(p);
913 if (l > 8) {
914 /* The end of the process name is usually more
915 * interesting, since the first bit might just be
916 * "systemd-" */
917 p = p + l - 8;
918 l = 8;
919 }
920
921 process_name[0] = '(';
922 memcpy(process_name+1, p, l);
923 process_name[1+l] = ')';
924 process_name[1+l+1] = 0;
925
926 rename_process(process_name);
927}
928
8351ceae
LP
929static int apply_seccomp(uint32_t *syscall_filter) {
930 static const struct sock_filter header[] = {
931 VALIDATE_ARCHITECTURE,
932 EXAMINE_SYSCALL
933 };
934 static const struct sock_filter footer[] = {
935 _KILL_PROCESS
936 };
937
938 int i;
939 unsigned n;
940 struct sock_filter *f;
b92bea5d 941 struct sock_fprog prog = {};
8351ceae
LP
942
943 assert(syscall_filter);
944
945 /* First: count the syscalls to check for */
946 for (i = 0, n = 0; i < syscall_max(); i++)
947 if (syscall_filter[i >> 4] & (1 << (i & 31)))
948 n++;
949
950 /* Second: build the filter program from a header the syscall
951 * matches and the footer */
952 f = alloca(sizeof(struct sock_filter) * (ELEMENTSOF(header) + 2*n + ELEMENTSOF(footer)));
953 memcpy(f, header, sizeof(header));
954
955 for (i = 0, n = 0; i < syscall_max(); i++)
956 if (syscall_filter[i >> 4] & (1 << (i & 31))) {
957 struct sock_filter item[] = {
843fc7f7 958 BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, INDEX_TO_SYSCALL(i), 0, 1),
8351ceae
LP
959 BPF_STMT(BPF_RET+BPF_K, SECCOMP_RET_ALLOW)
960 };
961
962 assert_cc(ELEMENTSOF(item) == 2);
963
964 f[ELEMENTSOF(header) + 2*n] = item[0];
965 f[ELEMENTSOF(header) + 2*n+1] = item[1];
966
967 n++;
968 }
969
970 memcpy(f + (ELEMENTSOF(header) + 2*n), footer, sizeof(footer));
971
972 /* Third: install the filter */
8351ceae
LP
973 prog.len = ELEMENTSOF(header) + ELEMENTSOF(footer) + 2*n;
974 prog.filter = f;
975 if (prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog) < 0)
976 return -errno;
977
978 return 0;
979}
980
31a7eb86
ZJS
981static void do_idle_pipe_dance(int idle_pipe[4]) {
982 assert(idle_pipe);
983
984 if (idle_pipe[1] >= 0)
985 close_nointr_nofail(idle_pipe[1]);
986 if (idle_pipe[2] >= 0)
987 close_nointr_nofail(idle_pipe[2]);
988
989 if (idle_pipe[0] >= 0) {
990 int r;
991
992 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
993
994 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
995 /* Signal systemd that we are bored and want to continue. */
996 write(idle_pipe[3], "x", 1);
997
998 /* Wait for systemd to react to the signal above. */
999 fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
1000 }
1001
1002 close_nointr_nofail(idle_pipe[0]);
1003
1004 }
1005
1006 if (idle_pipe[3] >= 0)
1007 close_nointr_nofail(idle_pipe[3]);
1008}
1009
9fb86720 1010int exec_spawn(ExecCommand *command,
9e2f7c11 1011 char **argv,
c17ec25e 1012 ExecContext *context,
c2748801 1013 int fds[], unsigned n_fds,
1137a57c 1014 char **environment,
81a2b7ce
LP
1015 bool apply_permissions,
1016 bool apply_chroot,
1e3ad081 1017 bool apply_tty_stdin,
80876c20 1018 bool confirm_spawn,
4ad49000
LP
1019 CGroupControllerMask cgroup_mask,
1020 const char *cgroup_path,
62bca2c6 1021 const char *unit_id,
31a7eb86 1022 int idle_pipe[4],
81a2b7ce
LP
1023 pid_t *ret) {
1024
4ad49000
LP
1025 _cleanup_strv_free_ char **files_env = NULL;
1026 int socket_fd;
1027 char *line;
034c6ed7 1028 pid_t pid;
8e274523 1029 int r;
034c6ed7 1030
5cb5a6ff
LP
1031 assert(command);
1032 assert(context);
1033 assert(ret);
034c6ed7
LP
1034 assert(fds || n_fds <= 0);
1035
4f2d528d
LP
1036 if (context->std_input == EXEC_INPUT_SOCKET ||
1037 context->std_output == EXEC_OUTPUT_SOCKET ||
1038 context->std_error == EXEC_OUTPUT_SOCKET) {
1039
1040 if (n_fds != 1)
1041 return -EINVAL;
1042
1043 socket_fd = fds[0];
1044
1045 fds = NULL;
1046 n_fds = 0;
1047 } else
1048 socket_fd = -1;
1049
b66871da
ZJS
1050 r = exec_context_load_environment(context, &files_env);
1051 if (r < 0) {
bbc9006e
MT
1052 log_struct_unit(LOG_ERR,
1053 unit_id,
23635a85
ZJS
1054 "MESSAGE=Failed to load environment files: %s", strerror(-r),
1055 "ERRNO=%d", -r,
1056 NULL);
8c7be95e
LP
1057 return r;
1058 }
1059
9e2f7c11
LP
1060 if (!argv)
1061 argv = command->argv;
1062
af6da548 1063 line = exec_command_line(argv);
b66871da
ZJS
1064 if (!line)
1065 return log_oom();
1a63a750 1066
bbc9006e 1067 log_struct_unit(LOG_DEBUG,
099a804b
LP
1068 unit_id,
1069 "EXECUTABLE=%s", command->path,
1070 "MESSAGE=About to execute: %s", line,
1071 NULL);
1a63a750 1072 free(line);
acbb0225 1073
c17ec25e
MS
1074 if (context->private_tmp && !context->tmp_dir && !context->var_tmp_dir) {
1075 r = setup_tmpdirs(&context->tmp_dir, &context->var_tmp_dir);
1076 if (r < 0)
1077 return r;
1078 }
1079
b66871da
ZJS
1080 pid = fork();
1081 if (pid < 0)
1082 return -errno;
034c6ed7
LP
1083
1084 if (pid == 0) {
4c2630eb 1085 int i, err;
309bff19 1086 sigset_t ss;
81a2b7ce
LP
1087 const char *username = NULL, *home = NULL;
1088 uid_t uid = (uid_t) -1;
1089 gid_t gid = (gid_t) -1;
7fd1b19b 1090 _cleanup_strv_free_ char **our_env = NULL, **pam_env = NULL,
b66871da 1091 **final_env = NULL, **final_argv = NULL;
81a2b7ce 1092 unsigned n_env = 0;
309bff19 1093
034c6ed7 1094 /* child */
5cb5a6ff 1095
5d6b1584 1096 rename_process_from_path(command->path);
5b6319dc 1097
1b91d3e8
LP
1098 /* We reset exactly these signals, since they are the
1099 * only ones we set to SIG_IGN in the main daemon. All
1100 * others we leave untouched because we set them to
1101 * SIG_DFL or a valid handler initially, both of which
1102 * will be demoted to SIG_DFL. */
1103 default_signals(SIGNALS_CRASH_HANDLER,
9a34ec5f 1104 SIGNALS_IGNORE, -1);
7b683879 1105
353e12c2
LP
1106 if (context->ignore_sigpipe)
1107 ignore_signals(SIGPIPE, -1);
1108
1109 assert_se(sigemptyset(&ss) == 0);
1110 if (sigprocmask(SIG_SETMASK, &ss, NULL) < 0) {
4c2630eb 1111 err = -errno;
309bff19 1112 r = EXIT_SIGNAL_MASK;
8c7be95e 1113 goto fail_child;
309bff19
LP
1114 }
1115
31a7eb86
ZJS
1116 if (idle_pipe)
1117 do_idle_pipe_dance(idle_pipe);
f2b68789 1118
85d73053
LP
1119 /* Close sockets very early to make sure we don't
1120 * block init reexecution because it cannot bind its
1121 * sockets */
4d8a7798 1122 log_forget_fds();
4c2630eb
MS
1123 err = close_all_fds(socket_fd >= 0 ? &socket_fd : fds,
1124 socket_fd >= 0 ? 1 : n_fds);
1125 if (err < 0) {
fc9b2a84 1126 r = EXIT_FDS;
8c7be95e 1127 goto fail_child;
fc9b2a84
LP
1128 }
1129
74922904 1130 if (!context->same_pgrp)
8d567588 1131 if (setsid() < 0) {
4c2630eb 1132 err = -errno;
8d567588 1133 r = EXIT_SETSID;
8c7be95e 1134 goto fail_child;
8d567588 1135 }
80876c20 1136
c5da34ef
LP
1137 if (context->tcpwrap_name) {
1138 if (socket_fd >= 0)
1139 if (!socket_tcpwrap(socket_fd, context->tcpwrap_name)) {
4c2630eb 1140 err = -EACCES;
c5da34ef 1141 r = EXIT_TCPWRAP;
8c7be95e 1142 goto fail_child;
c5da34ef
LP
1143 }
1144
1145 for (i = 0; i < (int) n_fds; i++) {
1146 if (!socket_tcpwrap(fds[i], context->tcpwrap_name)) {
4c2630eb 1147 err = -EACCES;
c5da34ef 1148 r = EXIT_TCPWRAP;
8c7be95e 1149 goto fail_child;
c5da34ef 1150 }
df1f0afe 1151 }
c5da34ef 1152 }
df1f0afe 1153
6ea832a2
LP
1154 exec_context_tty_reset(context);
1155
af6da548 1156 if (confirm_spawn) {
80876c20
LP
1157 char response;
1158
af6da548
LP
1159 err = ask_for_confirmation(&response, argv);
1160 if (err == -ETIMEDOUT)
1161 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
1162 else if (err < 0)
1163 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-err));
1164 else if (response == 's') {
1165 write_confirm_message("Skipping execution.\n");
4c2630eb 1166 err = -ECANCELED;
80876c20 1167 r = EXIT_CONFIRM;
8c7be95e 1168 goto fail_child;
af6da548
LP
1169 } else if (response == 'n') {
1170 write_confirm_message("Failing execution.\n");
4c2630eb 1171 err = r = 0;
8c7be95e 1172 goto fail_child;
ee2b4894 1173 }
034c6ed7
LP
1174 }
1175
da726a4d
LP
1176 /* If a socket is connected to STDIN/STDOUT/STDERR, we
1177 * must sure to drop O_NONBLOCK */
1178 if (socket_fd >= 0)
1179 fd_nonblock(socket_fd, false);
1180
af6da548
LP
1181 err = setup_input(context, socket_fd, apply_tty_stdin);
1182 if (err < 0) {
1183 r = EXIT_STDIN;
1184 goto fail_child;
4c2630eb 1185 }
9eba9da4 1186
eb17e935 1187 err = setup_output(context, STDOUT_FILENO, socket_fd, path_get_file_name(command->path), unit_id, apply_tty_stdin);
af6da548
LP
1188 if (err < 0) {
1189 r = EXIT_STDOUT;
1190 goto fail_child;
4c2630eb 1191 }
94f04347 1192
eb17e935 1193 err = setup_output(context, STDERR_FILENO, socket_fd, path_get_file_name(command->path), unit_id, apply_tty_stdin);
4c2630eb 1194 if (err < 0) {
80876c20 1195 r = EXIT_STDERR;
8c7be95e 1196 goto fail_child;
071830ff
LP
1197 }
1198
4ad49000
LP
1199 if (cgroup_path) {
1200 err = cg_attach_with_mask(cgroup_mask, cgroup_path, 0);
4c2630eb 1201 if (err < 0) {
8e274523 1202 r = EXIT_CGROUP;
8c7be95e 1203 goto fail_child;
8e274523 1204 }
4c2630eb 1205 }
8e274523 1206
dd6c17b1 1207 if (context->oom_score_adjust_set) {
fb33a393 1208 char t[16];
034c6ed7 1209
dd6c17b1 1210 snprintf(t, sizeof(t), "%i", context->oom_score_adjust);
fb33a393 1211 char_array_0(t);
034c6ed7 1212
574d5f2d 1213 if (write_string_file("/proc/self/oom_score_adj", t) < 0) {
8600c525
KS
1214 err = -errno;
1215 r = EXIT_OOM_ADJUST;
1216 goto fail_child;
fb33a393 1217 }
034c6ed7
LP
1218 }
1219
fb33a393
LP
1220 if (context->nice_set)
1221 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
4c2630eb 1222 err = -errno;
fb33a393 1223 r = EXIT_NICE;
8c7be95e 1224 goto fail_child;
fb33a393
LP
1225 }
1226
94f04347 1227 if (context->cpu_sched_set) {
b92bea5d
ZJS
1228 struct sched_param param = {
1229 .sched_priority = context->cpu_sched_priority,
1230 };
94f04347 1231
e62d8c39
ZJS
1232 r = sched_setscheduler(0,
1233 context->cpu_sched_policy |
1234 (context->cpu_sched_reset_on_fork ?
1235 SCHED_RESET_ON_FORK : 0),
1236 &param);
1237 if (r < 0) {
4c2630eb 1238 err = -errno;
94f04347 1239 r = EXIT_SETSCHEDULER;
8c7be95e 1240 goto fail_child;
94f04347
LP
1241 }
1242 }
1243
82c121a4
LP
1244 if (context->cpuset)
1245 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
4c2630eb 1246 err = -errno;
94f04347 1247 r = EXIT_CPUAFFINITY;
8c7be95e 1248 goto fail_child;
94f04347
LP
1249 }
1250
9eba9da4
LP
1251 if (context->ioprio_set)
1252 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
4c2630eb 1253 err = -errno;
9eba9da4 1254 r = EXIT_IOPRIO;
8c7be95e 1255 goto fail_child;
9eba9da4
LP
1256 }
1257
d88a251b 1258 if (context->timer_slack_nsec != (nsec_t) -1)
03fae018 1259 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
4c2630eb 1260 err = -errno;
94f04347 1261 r = EXIT_TIMERSLACK;
8c7be95e 1262 goto fail_child;
94f04347
LP
1263 }
1264
169c1bda 1265 if (context->utmp_id)
0ad26e09 1266 utmp_put_init_process(context->utmp_id, getpid(), getsid(0), context->tty_path);
169c1bda 1267
81a2b7ce
LP
1268 if (context->user) {
1269 username = context->user;
d05c5031 1270 err = get_user_creds(&username, &uid, &gid, &home, NULL);
4c2630eb 1271 if (err < 0) {
81a2b7ce 1272 r = EXIT_USER;
8c7be95e 1273 goto fail_child;
81a2b7ce 1274 }
d8b4e2e9 1275
4c2630eb
MS
1276 if (is_terminal_input(context->std_input)) {
1277 err = chown_terminal(STDIN_FILENO, uid);
1278 if (err < 0) {
d8b4e2e9 1279 r = EXIT_STDIN;
8c7be95e 1280 goto fail_child;
d8b4e2e9 1281 }
4c2630eb 1282 }
81a2b7ce
LP
1283 }
1284
8aa75193
LP
1285#ifdef HAVE_PAM
1286 if (cgroup_path && context->user && context->pam_name) {
1287 err = cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER, cgroup_path, 0644, uid, gid);
1288 if (err < 0) {
1289 r = EXIT_CGROUP;
1290 goto fail_child;
1291 }
1292
1293
1294 err = cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER, cgroup_path, 0755, uid, gid);
1295 if (err < 0) {
1296 r = EXIT_CGROUP;
1297 goto fail_child;
1298 }
1299 }
1300#endif
1301
4c2630eb
MS
1302 if (apply_permissions) {
1303 err = enforce_groups(context, username, gid);
1304 if (err < 0) {
3b8bddde
LP
1305 r = EXIT_GROUP;
1306 goto fail_child;
1307 }
4c2630eb 1308 }
3b8bddde
LP
1309
1310 umask(context->umask);
1311
5b6319dc 1312#ifdef HAVE_PAM
b7848021 1313 if (apply_permissions && context->pam_name && username) {
940c5210 1314 err = setup_pam(context->pam_name, username, uid, context->tty_path, &pam_env, fds, n_fds);
4c2630eb 1315 if (err < 0) {
5b6319dc 1316 r = EXIT_PAM;
8c7be95e 1317 goto fail_child;
5b6319dc
LP
1318 }
1319 }
1320#endif
ff01d048
LP
1321 if (context->private_network) {
1322 if (unshare(CLONE_NEWNET) < 0) {
4c2630eb 1323 err = -errno;
ff01d048
LP
1324 r = EXIT_NETWORK;
1325 goto fail_child;
1326 }
1327
1328 loopback_setup();
1329 }
5b6319dc 1330
04aa0cb9
LP
1331 if (strv_length(context->read_write_dirs) > 0 ||
1332 strv_length(context->read_only_dirs) > 0 ||
1333 strv_length(context->inaccessible_dirs) > 0 ||
ac0930c8 1334 context->mount_flags != 0 ||
4c2630eb
MS
1335 context->private_tmp) {
1336 err = setup_namespace(context->read_write_dirs,
1337 context->read_only_dirs,
1338 context->inaccessible_dirs,
c17ec25e
MS
1339 context->tmp_dir,
1340 context->var_tmp_dir,
4c2630eb
MS
1341 context->private_tmp,
1342 context->mount_flags);
1343 if (err < 0) {
1344 r = EXIT_NAMESPACE;
8c7be95e 1345 goto fail_child;
4c2630eb
MS
1346 }
1347 }
04aa0cb9 1348
81a2b7ce
LP
1349 if (apply_chroot) {
1350 if (context->root_directory)
1351 if (chroot(context->root_directory) < 0) {
4c2630eb 1352 err = -errno;
81a2b7ce 1353 r = EXIT_CHROOT;
8c7be95e 1354 goto fail_child;
81a2b7ce
LP
1355 }
1356
1357 if (chdir(context->working_directory ? context->working_directory : "/") < 0) {
4c2630eb 1358 err = -errno;
81a2b7ce 1359 r = EXIT_CHDIR;
8c7be95e 1360 goto fail_child;
81a2b7ce
LP
1361 }
1362 } else {
7fd1b19b 1363 _cleanup_free_ char *d = NULL;
81a2b7ce
LP
1364
1365 if (asprintf(&d, "%s/%s",
1366 context->root_directory ? context->root_directory : "",
1367 context->working_directory ? context->working_directory : "") < 0) {
4c2630eb 1368 err = -ENOMEM;
81a2b7ce 1369 r = EXIT_MEMORY;
8c7be95e 1370 goto fail_child;
81a2b7ce
LP
1371 }
1372
1373 if (chdir(d) < 0) {
4c2630eb 1374 err = -errno;
81a2b7ce 1375 r = EXIT_CHDIR;
8c7be95e 1376 goto fail_child;
81a2b7ce 1377 }
81a2b7ce
LP
1378 }
1379
fc9b2a84
LP
1380 /* We repeat the fd closing here, to make sure that
1381 * nothing is leaked from the PAM modules */
4c2630eb
MS
1382 err = close_all_fds(fds, n_fds);
1383 if (err >= 0)
1384 err = shift_fds(fds, n_fds);
1385 if (err >= 0)
1386 err = flags_fds(fds, n_fds, context->non_blocking);
1387 if (err < 0) {
034c6ed7 1388 r = EXIT_FDS;
8c7be95e 1389 goto fail_child;
034c6ed7
LP
1390 }
1391
81a2b7ce 1392 if (apply_permissions) {
034c6ed7 1393
81a2b7ce
LP
1394 for (i = 0; i < RLIMIT_NLIMITS; i++) {
1395 if (!context->rlimit[i])
1396 continue;
1397
68faf98c 1398 if (setrlimit_closest(i, context->rlimit[i]) < 0) {
4c2630eb 1399 err = -errno;
81a2b7ce 1400 r = EXIT_LIMITS;
8c7be95e 1401 goto fail_child;
81a2b7ce 1402 }
034c6ed7 1403 }
034c6ed7 1404
4c2630eb 1405 if (context->capability_bounding_set_drop) {
ec8927ca 1406 err = capability_bounding_set_drop(context->capability_bounding_set_drop, false);
4c2630eb 1407 if (err < 0) {
73090dc8
LP
1408 r = EXIT_CAPABILITIES;
1409 goto fail_child;
1410 }
4c2630eb 1411 }
260abb78 1412
4c2630eb
MS
1413 if (context->user) {
1414 err = enforce_user(context, uid);
1415 if (err < 0) {
81a2b7ce 1416 r = EXIT_USER;
8c7be95e 1417 goto fail_child;
81a2b7ce 1418 }
4c2630eb 1419 }
81a2b7ce 1420
35b8ca3a 1421 /* PR_GET_SECUREBITS is not privileged, while
693ced48
LP
1422 * PR_SET_SECUREBITS is. So to suppress
1423 * potential EPERMs we'll try not to call
1424 * PR_SET_SECUREBITS unless necessary. */
1425 if (prctl(PR_GET_SECUREBITS) != context->secure_bits)
1426 if (prctl(PR_SET_SECUREBITS, context->secure_bits) < 0) {
4c2630eb 1427 err = -errno;
693ced48 1428 r = EXIT_SECUREBITS;
8c7be95e 1429 goto fail_child;
693ced48 1430 }
81a2b7ce
LP
1431
1432 if (context->capabilities)
1433 if (cap_set_proc(context->capabilities) < 0) {
4c2630eb 1434 err = -errno;
81a2b7ce 1435 r = EXIT_CAPABILITIES;
8c7be95e 1436 goto fail_child;
81a2b7ce 1437 }
8351ceae
LP
1438
1439 if (context->no_new_privileges)
1440 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1441 err = -errno;
1442 r = EXIT_NO_NEW_PRIVILEGES;
1443 goto fail_child;
1444 }
1445
1446 if (context->syscall_filter) {
1447 err = apply_seccomp(context->syscall_filter);
1448 if (err < 0) {
1449 r = EXIT_SECCOMP;
1450 goto fail_child;
1451 }
1452 }
94f04347
LP
1453 }
1454
e62d8c39
ZJS
1455 our_env = new0(char*, 7);
1456 if (!our_env) {
4c2630eb 1457 err = -ENOMEM;
81a2b7ce 1458 r = EXIT_MEMORY;
8c7be95e 1459 goto fail_child;
81a2b7ce 1460 }
034c6ed7 1461
81a2b7ce 1462 if (n_fds > 0)
bb00e604 1463 if (asprintf(our_env + n_env++, "LISTEN_PID=%lu", (unsigned long) getpid()) < 0 ||
81a2b7ce 1464 asprintf(our_env + n_env++, "LISTEN_FDS=%u", n_fds) < 0) {
4c2630eb 1465 err = -ENOMEM;
81a2b7ce 1466 r = EXIT_MEMORY;
8c7be95e 1467 goto fail_child;
81a2b7ce 1468 }
034c6ed7 1469
81a2b7ce
LP
1470 if (home)
1471 if (asprintf(our_env + n_env++, "HOME=%s", home) < 0) {
4c2630eb 1472 err = -ENOMEM;
81a2b7ce 1473 r = EXIT_MEMORY;
8c7be95e 1474 goto fail_child;
81a2b7ce 1475 }
034c6ed7 1476
81a2b7ce
LP
1477 if (username)
1478 if (asprintf(our_env + n_env++, "LOGNAME=%s", username) < 0 ||
1479 asprintf(our_env + n_env++, "USER=%s", username) < 0) {
4c2630eb 1480 err = -ENOMEM;
81a2b7ce 1481 r = EXIT_MEMORY;
8c7be95e 1482 goto fail_child;
81a2b7ce 1483 }
034c6ed7 1484
e3aa71c3
LP
1485 if (is_terminal_input(context->std_input) ||
1486 context->std_output == EXEC_OUTPUT_TTY ||
1487 context->std_error == EXEC_OUTPUT_TTY)
1488 if (!(our_env[n_env++] = strdup(default_term_for_tty(tty_path(context))))) {
4c2630eb 1489 err = -ENOMEM;
e3aa71c3 1490 r = EXIT_MEMORY;
8c7be95e 1491 goto fail_child;
e3aa71c3
LP
1492 }
1493
1494 assert(n_env <= 7);
4e85aff4 1495
e62d8c39
ZJS
1496 final_env = strv_env_merge(5,
1497 environment,
1498 our_env,
1499 context->environment,
1500 files_env,
1501 pam_env,
1502 NULL);
1503 if (!final_env) {
4c2630eb 1504 err = -ENOMEM;
81a2b7ce 1505 r = EXIT_MEMORY;
8c7be95e 1506 goto fail_child;
81a2b7ce 1507 }
034c6ed7 1508
e62d8c39
ZJS
1509 final_argv = replace_env_argv(argv, final_env);
1510 if (!final_argv) {
4c2630eb 1511 err = -ENOMEM;
fab56fc5 1512 r = EXIT_MEMORY;
8c7be95e 1513 goto fail_child;
fab56fc5
LP
1514 }
1515
a6ff950e
LP
1516 final_env = strv_env_clean(final_env);
1517
03bb799e
HH
1518 if (_unlikely_(log_get_max_level() >= LOG_PRI(LOG_DEBUG))) {
1519 line = exec_command_line(final_argv);
1520 if (line) {
1521 log_open();
1522 log_struct_unit(LOG_DEBUG,
1523 unit_id,
1524 "EXECUTABLE=%s", command->path,
099a804b
LP
1525 "MESSAGE=Executing: %s", line,
1526 NULL);
03bb799e
HH
1527 log_close();
1528 free(line);
1529 line = NULL;
1530 }
1531 }
fab56fc5 1532 execve(command->path, final_argv, final_env);
4c2630eb 1533 err = -errno;
034c6ed7
LP
1534 r = EXIT_EXEC;
1535
8c7be95e 1536 fail_child:
4c2630eb
MS
1537 if (r != 0) {
1538 log_open();
23635a85
ZJS
1539 log_struct(LOG_ERR, MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED),
1540 "EXECUTABLE=%s", command->path,
1541 "MESSAGE=Failed at step %s spawning %s: %s",
1542 exit_status_to_string(r, EXIT_STATUS_SYSTEMD),
1543 command->path, strerror(-err),
1544 "ERRNO=%d", -err,
1545 NULL);
1546 log_close();
4c2630eb
MS
1547 }
1548
034c6ed7
LP
1549 _exit(r);
1550 }
1551
bbc9006e 1552 log_struct_unit(LOG_DEBUG,
e62d8c39
ZJS
1553 unit_id,
1554 "MESSAGE=Forked %s as %lu",
1555 command->path, (unsigned long) pid,
1556 NULL);
23635a85 1557
80876c20
LP
1558 /* We add the new process to the cgroup both in the child (so
1559 * that we can be sure that no user code is ever executed
1560 * outside of the cgroup) and in the parent (so that we can be
1561 * sure that when we kill the cgroup the process will be
1562 * killed too). */
4ad49000
LP
1563 if (cgroup_path)
1564 cg_attach(SYSTEMD_CGROUP_CONTROLLER, cgroup_path, pid);
2da3263a 1565
b58b4116 1566 exec_status_start(&command->exec_status, pid);
9fb86720 1567
034c6ed7 1568 *ret = pid;
5cb5a6ff
LP
1569 return 0;
1570}
1571
034c6ed7
LP
1572void exec_context_init(ExecContext *c) {
1573 assert(c);
1574
4c12626c 1575 c->umask = 0022;
9eba9da4 1576 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
94f04347 1577 c->cpu_sched_policy = SCHED_OTHER;
071830ff 1578 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 1579 c->syslog_level_prefix = true;
353e12c2 1580 c->ignore_sigpipe = true;
d88a251b 1581 c->timer_slack_nsec = (nsec_t) -1;
034c6ed7
LP
1582}
1583
c17ec25e 1584void exec_context_tmp_dirs_done(ExecContext *c) {
d34cd374
ZJS
1585 char* dirs[] = {c->tmp_dir ? c->tmp_dir : c->var_tmp_dir,
1586 c->tmp_dir ? c->var_tmp_dir : NULL,
1587 NULL};
1588 char **dirp;
c17ec25e 1589
d34cd374
ZJS
1590 for(dirp = dirs; *dirp; dirp++) {
1591 char *dir;
ebf4fb3d 1592 int r;
c17ec25e 1593
ebf4fb3d 1594 r = rm_rf_dangerous(*dirp, false, true, false);
d34cd374 1595 dir = dirname(*dirp);
ebf4fb3d
VP
1596 if (r < 0)
1597 log_warning("Failed to remove content of temporary directory %s: %s",
1598 dir, strerror(-r));
1599 else {
1600 r = rmdir(dir);
1601 if (r < 0)
1602 log_warning("Failed to remove temporary directory %s: %s",
1603 dir, strerror(-r));
1604 }
d34cd374
ZJS
1605
1606 free(*dirp);
c17ec25e 1607 }
d34cd374
ZJS
1608
1609 c->tmp_dir = c->var_tmp_dir = NULL;
c17ec25e
MS
1610}
1611
1612void exec_context_done(ExecContext *c, bool reloading_or_reexecuting) {
5cb5a6ff
LP
1613 unsigned l;
1614
1615 assert(c);
1616
1617 strv_free(c->environment);
034c6ed7 1618 c->environment = NULL;
5cb5a6ff 1619
8c7be95e
LP
1620 strv_free(c->environment_files);
1621 c->environment_files = NULL;
1622
034c6ed7 1623 for (l = 0; l < ELEMENTSOF(c->rlimit); l++) {
5cb5a6ff 1624 free(c->rlimit[l]);
034c6ed7
LP
1625 c->rlimit[l] = NULL;
1626 }
1627
9eba9da4
LP
1628 free(c->working_directory);
1629 c->working_directory = NULL;
1630 free(c->root_directory);
1631 c->root_directory = NULL;
5cb5a6ff 1632
80876c20
LP
1633 free(c->tty_path);
1634 c->tty_path = NULL;
1635
df1f0afe
LP
1636 free(c->tcpwrap_name);
1637 c->tcpwrap_name = NULL;
1638
071830ff
LP
1639 free(c->syslog_identifier);
1640 c->syslog_identifier = NULL;
1641
5cb5a6ff 1642 free(c->user);
034c6ed7
LP
1643 c->user = NULL;
1644
5cb5a6ff 1645 free(c->group);
034c6ed7
LP
1646 c->group = NULL;
1647
1648 strv_free(c->supplementary_groups);
1649 c->supplementary_groups = NULL;
94f04347 1650
5b6319dc
LP
1651 free(c->pam_name);
1652 c->pam_name = NULL;
1653
94f04347
LP
1654 if (c->capabilities) {
1655 cap_free(c->capabilities);
1656 c->capabilities = NULL;
1657 }
15ae422b
LP
1658
1659 strv_free(c->read_only_dirs);
1660 c->read_only_dirs = NULL;
1661
1662 strv_free(c->read_write_dirs);
1663 c->read_write_dirs = NULL;
1664
1665 strv_free(c->inaccessible_dirs);
1666 c->inaccessible_dirs = NULL;
82c121a4
LP
1667
1668 if (c->cpuset)
1669 CPU_FREE(c->cpuset);
86a3475b
LP
1670
1671 free(c->utmp_id);
1672 c->utmp_id = NULL;
b9a0e010
LP
1673
1674 free(c->syscall_filter);
1675 c->syscall_filter = NULL;
c17ec25e
MS
1676
1677 if (!reloading_or_reexecuting)
1678 exec_context_tmp_dirs_done(c);
5cb5a6ff
LP
1679}
1680
43d0fcbd
LP
1681void exec_command_done(ExecCommand *c) {
1682 assert(c);
1683
1684 free(c->path);
1685 c->path = NULL;
1686
1687 strv_free(c->argv);
1688 c->argv = NULL;
1689}
1690
1691void exec_command_done_array(ExecCommand *c, unsigned n) {
1692 unsigned i;
1693
1694 for (i = 0; i < n; i++)
1695 exec_command_done(c+i);
1696}
1697
5cb5a6ff
LP
1698void exec_command_free_list(ExecCommand *c) {
1699 ExecCommand *i;
1700
1701 while ((i = c)) {
034c6ed7 1702 LIST_REMOVE(ExecCommand, command, c, i);
43d0fcbd 1703 exec_command_done(i);
5cb5a6ff
LP
1704 free(i);
1705 }
1706}
1707
034c6ed7
LP
1708void exec_command_free_array(ExecCommand **c, unsigned n) {
1709 unsigned i;
1710
1711 for (i = 0; i < n; i++) {
1712 exec_command_free_list(c[i]);
1713 c[i] = NULL;
1714 }
1715}
1716
8c7be95e
LP
1717int exec_context_load_environment(const ExecContext *c, char ***l) {
1718 char **i, **r = NULL;
1719
1720 assert(c);
1721 assert(l);
1722
1723 STRV_FOREACH(i, c->environment_files) {
1724 char *fn;
1725 int k;
1726 bool ignore = false;
1727 char **p;
7fd1b19b 1728 _cleanup_globfree_ glob_t pglob = {};
2bef10ab 1729 int count, n;
8c7be95e
LP
1730
1731 fn = *i;
1732
1733 if (fn[0] == '-') {
1734 ignore = true;
1735 fn ++;
1736 }
1737
1738 if (!path_is_absolute(fn)) {
8c7be95e
LP
1739 if (ignore)
1740 continue;
1741
1742 strv_free(r);
1743 return -EINVAL;
1744 }
1745
2bef10ab 1746 /* Filename supports globbing, take all matching files */
2bef10ab
PL
1747 errno = 0;
1748 if (glob(fn, 0, NULL, &pglob) != 0) {
2bef10ab
PL
1749 if (ignore)
1750 continue;
8c7be95e 1751
2bef10ab
PL
1752 strv_free(r);
1753 return errno ? -errno : -EINVAL;
1754 }
1755 count = pglob.gl_pathc;
1756 if (count == 0) {
8c7be95e
LP
1757 if (ignore)
1758 continue;
1759
1760 strv_free(r);
2bef10ab 1761 return -EINVAL;
8c7be95e 1762 }
2bef10ab 1763 for (n = 0; n < count; n++) {
f73141d7 1764 k = load_env_file(pglob.gl_pathv[n], NULL, &p);
2bef10ab
PL
1765 if (k < 0) {
1766 if (ignore)
1767 continue;
8c7be95e 1768
2bef10ab 1769 strv_free(r);
2bef10ab 1770 return k;
e9c1ea9d 1771 }
ebc05a09 1772 /* Log invalid environment variables with filename */
e9c1ea9d
JSJ
1773 if (p)
1774 p = strv_env_clean_log(p, pglob.gl_pathv[n]);
8c7be95e 1775
2bef10ab
PL
1776 if (r == NULL)
1777 r = p;
1778 else {
1779 char **m;
8c7be95e 1780
2bef10ab
PL
1781 m = strv_env_merge(2, r, p);
1782 strv_free(r);
1783 strv_free(p);
c84a9488 1784 if (!m)
2bef10ab 1785 return -ENOMEM;
2bef10ab
PL
1786
1787 r = m;
1788 }
8c7be95e
LP
1789 }
1790 }
1791
1792 *l = r;
1793
1794 return 0;
1795}
1796
6ac8fdc9
MS
1797static bool tty_may_match_dev_console(const char *tty) {
1798 char *active = NULL, *console;
1799 bool b;
1800
1801 if (startswith(tty, "/dev/"))
1802 tty += 5;
1803
1804 /* trivial identity? */
1805 if (streq(tty, "console"))
1806 return true;
1807
1808 console = resolve_dev_console(&active);
1809 /* if we could not resolve, assume it may */
1810 if (!console)
1811 return true;
1812
1813 /* "tty0" means the active VC, so it may be the same sometimes */
1814 b = streq(console, tty) || (streq(console, "tty0") && tty_is_vc(tty));
1815 free(active);
1816
1817 return b;
1818}
1819
1820bool exec_context_may_touch_console(ExecContext *ec) {
1821 return (ec->tty_reset || ec->tty_vhangup || ec->tty_vt_disallocate ||
1822 is_terminal_input(ec->std_input) ||
1823 is_terminal_output(ec->std_output) ||
1824 is_terminal_output(ec->std_error)) &&
1825 tty_may_match_dev_console(tty_path(ec));
1826}
1827
15ae422b
LP
1828static void strv_fprintf(FILE *f, char **l) {
1829 char **g;
1830
1831 assert(f);
1832
1833 STRV_FOREACH(g, l)
1834 fprintf(f, " %s", *g);
1835}
1836
5cb5a6ff 1837void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
507f22bd 1838 char **e;
94f04347 1839 unsigned i;
9eba9da4 1840
5cb5a6ff
LP
1841 assert(c);
1842 assert(f);
1843
4ad49000 1844 prefix = strempty(prefix);
5cb5a6ff
LP
1845
1846 fprintf(f,
94f04347
LP
1847 "%sUMask: %04o\n"
1848 "%sWorkingDirectory: %s\n"
451a074f 1849 "%sRootDirectory: %s\n"
15ae422b 1850 "%sNonBlocking: %s\n"
64747e2d 1851 "%sPrivateTmp: %s\n"
4819ff03
LP
1852 "%sPrivateNetwork: %s\n"
1853 "%sIgnoreSIGPIPE: %s\n",
5cb5a6ff 1854 prefix, c->umask,
9eba9da4 1855 prefix, c->working_directory ? c->working_directory : "/",
451a074f 1856 prefix, c->root_directory ? c->root_directory : "/",
15ae422b 1857 prefix, yes_no(c->non_blocking),
64747e2d 1858 prefix, yes_no(c->private_tmp),
4819ff03
LP
1859 prefix, yes_no(c->private_network),
1860 prefix, yes_no(c->ignore_sigpipe));
fb33a393 1861
8c7be95e
LP
1862 STRV_FOREACH(e, c->environment)
1863 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
1864
1865 STRV_FOREACH(e, c->environment_files)
1866 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 1867
df1f0afe
LP
1868 if (c->tcpwrap_name)
1869 fprintf(f,
1870 "%sTCPWrapName: %s\n",
1871 prefix, c->tcpwrap_name);
1872
fb33a393
LP
1873 if (c->nice_set)
1874 fprintf(f,
1875 "%sNice: %i\n",
1876 prefix, c->nice);
1877
dd6c17b1 1878 if (c->oom_score_adjust_set)
fb33a393 1879 fprintf(f,
dd6c17b1
LP
1880 "%sOOMScoreAdjust: %i\n",
1881 prefix, c->oom_score_adjust);
9eba9da4 1882
94f04347
LP
1883 for (i = 0; i < RLIM_NLIMITS; i++)
1884 if (c->rlimit[i])
ea430986 1885 fprintf(f, "%s%s: %llu\n", prefix, rlimit_to_string(i), (unsigned long long) c->rlimit[i]->rlim_max);
94f04347 1886
f8b69d1d
MS
1887 if (c->ioprio_set) {
1888 char *class_str;
1889 int r;
1890
1891 r = ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
1892 if (r < 0)
1893 class_str = NULL;
9eba9da4
LP
1894 fprintf(f,
1895 "%sIOSchedulingClass: %s\n"
1896 "%sIOPriority: %i\n",
f8b69d1d 1897 prefix, strna(class_str),
9eba9da4 1898 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
f8b69d1d
MS
1899 free(class_str);
1900 }
94f04347 1901
f8b69d1d
MS
1902 if (c->cpu_sched_set) {
1903 char *policy_str;
1904 int r;
1905
1906 r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
1907 if (r < 0)
1908 policy_str = NULL;
94f04347
LP
1909 fprintf(f,
1910 "%sCPUSchedulingPolicy: %s\n"
38b48754
LP
1911 "%sCPUSchedulingPriority: %i\n"
1912 "%sCPUSchedulingResetOnFork: %s\n",
f8b69d1d 1913 prefix, strna(policy_str),
38b48754
LP
1914 prefix, c->cpu_sched_priority,
1915 prefix, yes_no(c->cpu_sched_reset_on_fork));
f8b69d1d 1916 free(policy_str);
b929bf04 1917 }
94f04347 1918
82c121a4 1919 if (c->cpuset) {
94f04347 1920 fprintf(f, "%sCPUAffinity:", prefix);
82c121a4
LP
1921 for (i = 0; i < c->cpuset_ncpus; i++)
1922 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
94f04347
LP
1923 fprintf(f, " %i", i);
1924 fputs("\n", f);
1925 }
1926
d88a251b 1927 if (c->timer_slack_nsec != (nsec_t) -1)
f96096db 1928 fprintf(f, "%sTimerSlackNSec: %lu\n", prefix, (unsigned long)c->timer_slack_nsec);
94f04347
LP
1929
1930 fprintf(f,
80876c20
LP
1931 "%sStandardInput: %s\n"
1932 "%sStandardOutput: %s\n"
1933 "%sStandardError: %s\n",
1934 prefix, exec_input_to_string(c->std_input),
1935 prefix, exec_output_to_string(c->std_output),
1936 prefix, exec_output_to_string(c->std_error));
1937
1938 if (c->tty_path)
1939 fprintf(f,
6ea832a2
LP
1940 "%sTTYPath: %s\n"
1941 "%sTTYReset: %s\n"
1942 "%sTTYVHangup: %s\n"
1943 "%sTTYVTDisallocate: %s\n",
1944 prefix, c->tty_path,
1945 prefix, yes_no(c->tty_reset),
1946 prefix, yes_no(c->tty_vhangup),
1947 prefix, yes_no(c->tty_vt_disallocate));
94f04347 1948
706343f4
LP
1949 if (c->std_output == EXEC_OUTPUT_SYSLOG || c->std_output == EXEC_OUTPUT_KMSG || c->std_output == EXEC_OUTPUT_JOURNAL ||
1950 c->std_output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE || c->std_output == EXEC_OUTPUT_KMSG_AND_CONSOLE || c->std_output == EXEC_OUTPUT_JOURNAL_AND_CONSOLE ||
1951 c->std_error == EXEC_OUTPUT_SYSLOG || c->std_error == EXEC_OUTPUT_KMSG || c->std_error == EXEC_OUTPUT_JOURNAL ||
f8b69d1d
MS
1952 c->std_error == EXEC_OUTPUT_SYSLOG_AND_CONSOLE || c->std_error == EXEC_OUTPUT_KMSG_AND_CONSOLE || c->std_error == EXEC_OUTPUT_JOURNAL_AND_CONSOLE) {
1953 char *fac_str, *lvl_str;
1954 int r;
1955
1956 r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
1957 if (r < 0)
1958 fac_str = NULL;
1959
1960 r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
1961 if (r < 0)
1962 lvl_str = NULL;
1963
94f04347
LP
1964 fprintf(f,
1965 "%sSyslogFacility: %s\n"
1966 "%sSyslogLevel: %s\n",
f8b69d1d
MS
1967 prefix, strna(fac_str),
1968 prefix, strna(lvl_str));
1969 free(lvl_str);
1970 free(fac_str);
1971 }
94f04347
LP
1972
1973 if (c->capabilities) {
1974 char *t;
1975 if ((t = cap_to_text(c->capabilities, NULL))) {
1976 fprintf(f, "%sCapabilities: %s\n",
1977 prefix, t);
1978 cap_free(t);
1979 }
1980 }
1981
1982 if (c->secure_bits)
1983 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
1984 prefix,
cbb21cca
ZJS
1985 (c->secure_bits & 1<<SECURE_KEEP_CAPS) ? " keep-caps" : "",
1986 (c->secure_bits & 1<<SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
1987 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
1988 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
1989 (c->secure_bits & 1<<SECURE_NOROOT) ? " noroot" : "",
1990 (c->secure_bits & 1<<SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
94f04347
LP
1991
1992 if (c->capability_bounding_set_drop) {
ae556c21 1993 unsigned long l;
260abb78 1994 fprintf(f, "%sCapabilityBoundingSet:", prefix);
94f04347 1995
64685e0c 1996 for (l = 0; l <= cap_last_cap(); l++)
ae556c21 1997 if (!(c->capability_bounding_set_drop & ((uint64_t) 1ULL << (uint64_t) l))) {
94f04347
LP
1998 char *t;
1999
ae556c21 2000 if ((t = cap_to_name(l))) {
94f04347 2001 fprintf(f, " %s", t);
260abb78 2002 cap_free(t);
94f04347
LP
2003 }
2004 }
2005
2006 fputs("\n", f);
2007 }
2008
2009 if (c->user)
f2d3769a 2010 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 2011 if (c->group)
f2d3769a 2012 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 2013
15ae422b 2014 if (strv_length(c->supplementary_groups) > 0) {
94f04347 2015 fprintf(f, "%sSupplementaryGroups:", prefix);
15ae422b
LP
2016 strv_fprintf(f, c->supplementary_groups);
2017 fputs("\n", f);
2018 }
94f04347 2019
5b6319dc 2020 if (c->pam_name)
f2d3769a 2021 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 2022
15ae422b
LP
2023 if (strv_length(c->read_write_dirs) > 0) {
2024 fprintf(f, "%sReadWriteDirs:", prefix);
2025 strv_fprintf(f, c->read_write_dirs);
2026 fputs("\n", f);
2027 }
2028
2029 if (strv_length(c->read_only_dirs) > 0) {
2030 fprintf(f, "%sReadOnlyDirs:", prefix);
2031 strv_fprintf(f, c->read_only_dirs);
2032 fputs("\n", f);
2033 }
94f04347 2034
15ae422b
LP
2035 if (strv_length(c->inaccessible_dirs) > 0) {
2036 fprintf(f, "%sInaccessibleDirs:", prefix);
2037 strv_fprintf(f, c->inaccessible_dirs);
94f04347
LP
2038 fputs("\n", f);
2039 }
2e22afe9 2040
169c1bda
LP
2041 if (c->utmp_id)
2042 fprintf(f,
2043 "%sUtmpIdentifier: %s\n",
2044 prefix, c->utmp_id);
5cb5a6ff
LP
2045}
2046
b58b4116 2047void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 2048 assert(s);
5cb5a6ff 2049
b58b4116
LP
2050 zero(*s);
2051 s->pid = pid;
2052 dual_timestamp_get(&s->start_timestamp);
2053}
2054
6ea832a2 2055void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
2056 assert(s);
2057
0b1f4ae6 2058 if (s->pid && s->pid != pid)
b58b4116
LP
2059 zero(*s);
2060
034c6ed7 2061 s->pid = pid;
63983207 2062 dual_timestamp_get(&s->exit_timestamp);
9fb86720 2063
034c6ed7
LP
2064 s->code = code;
2065 s->status = status;
169c1bda 2066
6ea832a2
LP
2067 if (context) {
2068 if (context->utmp_id)
2069 utmp_put_dead_process(context->utmp_id, pid, code, status);
2070
2071 exec_context_tty_reset(context);
2072 }
9fb86720
LP
2073}
2074
2075void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
2076 char buf[FORMAT_TIMESTAMP_MAX];
2077
2078 assert(s);
2079 assert(f);
2080
2081 if (!prefix)
2082 prefix = "";
2083
2084 if (s->pid <= 0)
2085 return;
2086
2087 fprintf(f,
bb00e604
LP
2088 "%sPID: %lu\n",
2089 prefix, (unsigned long) s->pid);
9fb86720 2090
63983207 2091 if (s->start_timestamp.realtime > 0)
9fb86720
LP
2092 fprintf(f,
2093 "%sStart Timestamp: %s\n",
63983207 2094 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
9fb86720 2095
63983207 2096 if (s->exit_timestamp.realtime > 0)
9fb86720
LP
2097 fprintf(f,
2098 "%sExit Timestamp: %s\n"
2099 "%sExit Code: %s\n"
2100 "%sExit Status: %i\n",
63983207 2101 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
9fb86720
LP
2102 prefix, sigchld_code_to_string(s->code),
2103 prefix, s->status);
5cb5a6ff 2104}
44d8db9e 2105
9e2f7c11 2106char *exec_command_line(char **argv) {
44d8db9e
LP
2107 size_t k;
2108 char *n, *p, **a;
2109 bool first = true;
2110
9e2f7c11 2111 assert(argv);
44d8db9e 2112
9164977d 2113 k = 1;
9e2f7c11 2114 STRV_FOREACH(a, argv)
44d8db9e
LP
2115 k += strlen(*a)+3;
2116
2117 if (!(n = new(char, k)))
2118 return NULL;
2119
2120 p = n;
9e2f7c11 2121 STRV_FOREACH(a, argv) {
44d8db9e
LP
2122
2123 if (!first)
2124 *(p++) = ' ';
2125 else
2126 first = false;
2127
2128 if (strpbrk(*a, WHITESPACE)) {
2129 *(p++) = '\'';
2130 p = stpcpy(p, *a);
2131 *(p++) = '\'';
2132 } else
2133 p = stpcpy(p, *a);
2134
2135 }
2136
9164977d
LP
2137 *p = 0;
2138
44d8db9e
LP
2139 /* FIXME: this doesn't really handle arguments that have
2140 * spaces and ticks in them */
2141
2142 return n;
2143}
2144
2145void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
9fb86720
LP
2146 char *p2;
2147 const char *prefix2;
2148
44d8db9e
LP
2149 char *cmd;
2150
2151 assert(c);
2152 assert(f);
2153
2154 if (!prefix)
2155 prefix = "";
9fb86720
LP
2156 p2 = strappend(prefix, "\t");
2157 prefix2 = p2 ? p2 : prefix;
44d8db9e 2158
9e2f7c11 2159 cmd = exec_command_line(c->argv);
44d8db9e
LP
2160
2161 fprintf(f,
2162 "%sCommand Line: %s\n",
2163 prefix, cmd ? cmd : strerror(ENOMEM));
2164
2165 free(cmd);
9fb86720
LP
2166
2167 exec_status_dump(&c->exec_status, f, prefix2);
2168
2169 free(p2);
44d8db9e
LP
2170}
2171
2172void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
2173 assert(f);
2174
2175 if (!prefix)
2176 prefix = "";
2177
2178 LIST_FOREACH(command, c, c)
2179 exec_command_dump(c, f, prefix);
2180}
94f04347 2181
a6a80b4f
LP
2182void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
2183 ExecCommand *end;
2184
2185 assert(l);
2186 assert(e);
2187
2188 if (*l) {
35b8ca3a 2189 /* It's kind of important, that we keep the order here */
a6a80b4f
LP
2190 LIST_FIND_TAIL(ExecCommand, command, *l, end);
2191 LIST_INSERT_AFTER(ExecCommand, command, *l, end, e);
2192 } else
2193 *l = e;
2194}
2195
26fd040d
LP
2196int exec_command_set(ExecCommand *c, const char *path, ...) {
2197 va_list ap;
2198 char **l, *p;
2199
2200 assert(c);
2201 assert(path);
2202
2203 va_start(ap, path);
2204 l = strv_new_ap(path, ap);
2205 va_end(ap);
2206
2207 if (!l)
2208 return -ENOMEM;
2209
2210 if (!(p = strdup(path))) {
2211 strv_free(l);
2212 return -ENOMEM;
2213 }
2214
2215 free(c->path);
2216 c->path = p;
2217
2218 strv_free(c->argv);
2219 c->argv = l;
2220
2221 return 0;
2222}
2223
80876c20
LP
2224static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
2225 [EXEC_INPUT_NULL] = "null",
2226 [EXEC_INPUT_TTY] = "tty",
2227 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d
LP
2228 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
2229 [EXEC_INPUT_SOCKET] = "socket"
80876c20
LP
2230};
2231
8a0867d6
LP
2232DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
2233
94f04347 2234static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 2235 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 2236 [EXEC_OUTPUT_NULL] = "null",
80876c20 2237 [EXEC_OUTPUT_TTY] = "tty",
94f04347 2238 [EXEC_OUTPUT_SYSLOG] = "syslog",
28dbc1e8 2239 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
9a6bca7a 2240 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 2241 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
2242 [EXEC_OUTPUT_JOURNAL] = "journal",
2243 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
4f2d528d 2244 [EXEC_OUTPUT_SOCKET] = "socket"
94f04347
LP
2245};
2246
2247DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);