]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/execute.c
basic: log: Increase static buffer for source file location (#3674)
[thirdparty/systemd.git] / src / core / execute.c
CommitLineData
a7334b09
LP
1/***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
a7334b09
LP
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 14 Lesser General Public License for more details.
a7334b09 15
5430f7f2 16 You should have received a copy of the GNU Lesser General Public License
a7334b09
LP
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
034c6ed7
LP
20#include <errno.h>
21#include <fcntl.h>
8dd4c05b
LP
22#include <glob.h>
23#include <grp.h>
24#include <poll.h>
309bff19 25#include <signal.h>
8dd4c05b 26#include <string.h>
19c0b0b9 27#include <sys/capability.h>
f3e43635 28#include <sys/mman.h>
8dd4c05b 29#include <sys/personality.h>
94f04347 30#include <sys/prctl.h>
8dd4c05b 31#include <sys/socket.h>
451a074f 32#include <sys/stat.h>
8dd4c05b
LP
33#include <sys/un.h>
34#include <unistd.h>
023a4f67 35#include <utmpx.h>
5cb5a6ff 36
5b6319dc
LP
37#ifdef HAVE_PAM
38#include <security/pam_appl.h>
39#endif
40
7b52a628
MS
41#ifdef HAVE_SELINUX
42#include <selinux/selinux.h>
43#endif
44
17df7223
LP
45#ifdef HAVE_SECCOMP
46#include <seccomp.h>
47#endif
48
eef65bf3
MS
49#ifdef HAVE_APPARMOR
50#include <sys/apparmor.h>
51#endif
52
24882e06 53#include "sd-messages.h"
8dd4c05b
LP
54
55#include "af-list.h"
b5efdb8a 56#include "alloc-util.h"
3ffd4af2
LP
57#ifdef HAVE_APPARMOR
58#include "apparmor-util.h"
59#endif
8dd4c05b
LP
60#include "async.h"
61#include "barrier.h"
8dd4c05b 62#include "cap-list.h"
430f0182 63#include "capability-util.h"
f6a6225e 64#include "def.h"
4d1a6904 65#include "env-util.h"
17df7223 66#include "errno-list.h"
3ffd4af2 67#include "execute.h"
8dd4c05b 68#include "exit-status.h"
3ffd4af2 69#include "fd-util.h"
8dd4c05b 70#include "fileio.h"
6482f626 71#include "formats-util.h"
f4f15635 72#include "fs-util.h"
7d50b32a 73#include "glob-util.h"
c004493c 74#include "io-util.h"
8dd4c05b
LP
75#include "ioprio.h"
76#include "log.h"
77#include "macro.h"
78#include "missing.h"
79#include "mkdir.h"
80#include "namespace.h"
6bedfcbb 81#include "parse-util.h"
8dd4c05b 82#include "path-util.h"
0b452006 83#include "process-util.h"
78f22b97 84#include "rlimit-util.h"
8dd4c05b 85#include "rm-rf.h"
3ffd4af2
LP
86#ifdef HAVE_SECCOMP
87#include "seccomp-util.h"
88#endif
8dd4c05b
LP
89#include "securebits.h"
90#include "selinux-util.h"
24882e06 91#include "signal-util.h"
8dd4c05b 92#include "smack-util.h"
8b43440b 93#include "string-table.h"
07630cea 94#include "string-util.h"
8dd4c05b 95#include "strv.h"
7ccbd1ae 96#include "syslog-util.h"
8dd4c05b
LP
97#include "terminal-util.h"
98#include "unit.h"
b1d4f8e1 99#include "user-util.h"
8dd4c05b
LP
100#include "util.h"
101#include "utmp-wtmp.h"
5cb5a6ff 102
e056b01d 103#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
31a7eb86 104#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
e6a26745 105
02a51aba
LP
106/* This assumes there is a 'tty' group */
107#define TTY_MODE 0620
108
531dca78
LP
109#define SNDBUF_SIZE (8*1024*1024)
110
034c6ed7
LP
111static int shift_fds(int fds[], unsigned n_fds) {
112 int start, restart_from;
113
114 if (n_fds <= 0)
115 return 0;
116
a0d40ac5
LP
117 /* Modifies the fds array! (sorts it) */
118
034c6ed7
LP
119 assert(fds);
120
121 start = 0;
122 for (;;) {
123 int i;
124
125 restart_from = -1;
126
127 for (i = start; i < (int) n_fds; i++) {
128 int nfd;
129
130 /* Already at right index? */
131 if (fds[i] == i+3)
132 continue;
133
3cc2aff1
LP
134 nfd = fcntl(fds[i], F_DUPFD, i + 3);
135 if (nfd < 0)
034c6ed7
LP
136 return -errno;
137
03e334a1 138 safe_close(fds[i]);
034c6ed7
LP
139 fds[i] = nfd;
140
141 /* Hmm, the fd we wanted isn't free? Then
ee33e53a 142 * let's remember that and try again from here */
034c6ed7
LP
143 if (nfd != i+3 && restart_from < 0)
144 restart_from = i;
145 }
146
147 if (restart_from < 0)
148 break;
149
150 start = restart_from;
151 }
152
153 return 0;
154}
155
c2748801 156static int flags_fds(const int fds[], unsigned n_fds, bool nonblock) {
47a71eed 157 unsigned i;
e2c76839 158 int r;
47a71eed
LP
159
160 if (n_fds <= 0)
161 return 0;
162
163 assert(fds);
164
451a074f 165 /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags */
47a71eed
LP
166
167 for (i = 0; i < n_fds; i++) {
47a71eed 168
3cc2aff1
LP
169 r = fd_nonblock(fds[i], nonblock);
170 if (r < 0)
e2c76839 171 return r;
47a71eed 172
451a074f
LP
173 /* We unconditionally drop FD_CLOEXEC from the fds,
174 * since after all we want to pass these fds to our
175 * children */
47a71eed 176
3cc2aff1
LP
177 r = fd_cloexec(fds[i], false);
178 if (r < 0)
e2c76839 179 return r;
47a71eed
LP
180 }
181
182 return 0;
183}
184
1e22b5cd 185static const char *exec_context_tty_path(const ExecContext *context) {
80876c20
LP
186 assert(context);
187
1e22b5cd
LP
188 if (context->stdio_as_fds)
189 return NULL;
190
80876c20
LP
191 if (context->tty_path)
192 return context->tty_path;
193
194 return "/dev/console";
195}
196
1e22b5cd
LP
197static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
198 const char *path;
199
6ea832a2
LP
200 assert(context);
201
1e22b5cd 202 path = exec_context_tty_path(context);
6ea832a2 203
1e22b5cd
LP
204 if (context->tty_vhangup) {
205 if (p && p->stdin_fd >= 0)
206 (void) terminal_vhangup_fd(p->stdin_fd);
207 else if (path)
208 (void) terminal_vhangup(path);
209 }
6ea832a2 210
1e22b5cd
LP
211 if (context->tty_reset) {
212 if (p && p->stdin_fd >= 0)
213 (void) reset_terminal_fd(p->stdin_fd, true);
214 else if (path)
215 (void) reset_terminal(path);
216 }
217
218 if (context->tty_vt_disallocate && path)
219 (void) vt_disallocate(path);
6ea832a2
LP
220}
221
3a1286b6
MS
222static bool is_terminal_output(ExecOutput o) {
223 return
224 o == EXEC_OUTPUT_TTY ||
225 o == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
226 o == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
227 o == EXEC_OUTPUT_JOURNAL_AND_CONSOLE;
228}
229
80876c20
LP
230static int open_null_as(int flags, int nfd) {
231 int fd, r;
071830ff 232
80876c20 233 assert(nfd >= 0);
071830ff 234
613b411c
LP
235 fd = open("/dev/null", flags|O_NOCTTY);
236 if (fd < 0)
071830ff
LP
237 return -errno;
238
80876c20
LP
239 if (fd != nfd) {
240 r = dup2(fd, nfd) < 0 ? -errno : nfd;
03e334a1 241 safe_close(fd);
80876c20
LP
242 } else
243 r = nfd;
071830ff 244
80876c20 245 return r;
071830ff
LP
246}
247
524daa8c 248static int connect_journal_socket(int fd, uid_t uid, gid_t gid) {
b92bea5d
ZJS
249 union sockaddr_union sa = {
250 .un.sun_family = AF_UNIX,
251 .un.sun_path = "/run/systemd/journal/stdout",
252 };
524daa8c
ZJS
253 uid_t olduid = UID_INVALID;
254 gid_t oldgid = GID_INVALID;
255 int r;
256
257 if (gid != GID_INVALID) {
258 oldgid = getgid();
259
260 r = setegid(gid);
261 if (r < 0)
262 return -errno;
263 }
264
265 if (uid != UID_INVALID) {
266 olduid = getuid();
267
268 r = seteuid(uid);
269 if (r < 0) {
270 r = -errno;
271 goto restore_gid;
272 }
273 }
274
fc2fffe7 275 r = connect(fd, &sa.sa, SOCKADDR_UN_LEN(sa.un));
524daa8c
ZJS
276 if (r < 0)
277 r = -errno;
278
279 /* If we fail to restore the uid or gid, things will likely
280 fail later on. This should only happen if an LSM interferes. */
281
282 if (uid != UID_INVALID)
283 (void) seteuid(olduid);
284
285 restore_gid:
286 if (gid != GID_INVALID)
287 (void) setegid(oldgid);
288
289 return r;
290}
291
fd1f9c89
LP
292static int connect_logger_as(
293 const ExecContext *context,
294 ExecOutput output,
295 const char *ident,
296 const char *unit_id,
297 int nfd,
298 uid_t uid,
299 gid_t gid) {
300
524daa8c 301 int fd, r;
071830ff
LP
302
303 assert(context);
80876c20
LP
304 assert(output < _EXEC_OUTPUT_MAX);
305 assert(ident);
306 assert(nfd >= 0);
071830ff 307
54fe0cdb
LP
308 fd = socket(AF_UNIX, SOCK_STREAM, 0);
309 if (fd < 0)
80876c20 310 return -errno;
071830ff 311
524daa8c
ZJS
312 r = connect_journal_socket(fd, uid, gid);
313 if (r < 0)
314 return r;
071830ff 315
80876c20 316 if (shutdown(fd, SHUT_RD) < 0) {
03e334a1 317 safe_close(fd);
80876c20
LP
318 return -errno;
319 }
071830ff 320
fd1f9c89 321 (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
531dca78 322
80876c20 323 dprintf(fd,
62bca2c6 324 "%s\n"
80876c20
LP
325 "%s\n"
326 "%i\n"
54fe0cdb
LP
327 "%i\n"
328 "%i\n"
329 "%i\n"
4f4a1dbf 330 "%i\n",
4f4a1dbf 331 context->syslog_identifier ? context->syslog_identifier : ident,
62bca2c6 332 unit_id,
54fe0cdb
LP
333 context->syslog_priority,
334 !!context->syslog_level_prefix,
335 output == EXEC_OUTPUT_SYSLOG || output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE,
336 output == EXEC_OUTPUT_KMSG || output == EXEC_OUTPUT_KMSG_AND_CONSOLE,
3a1286b6 337 is_terminal_output(output));
80876c20 338
fd1f9c89
LP
339 if (fd == nfd)
340 return nfd;
341
342 r = dup2(fd, nfd) < 0 ? -errno : nfd;
343 safe_close(fd);
071830ff 344
80876c20
LP
345 return r;
346}
347static int open_terminal_as(const char *path, mode_t mode, int nfd) {
348 int fd, r;
071830ff 349
80876c20
LP
350 assert(path);
351 assert(nfd >= 0);
071830ff 352
3cc2aff1
LP
353 fd = open_terminal(path, mode | O_NOCTTY);
354 if (fd < 0)
80876c20 355 return fd;
071830ff 356
80876c20
LP
357 if (fd != nfd) {
358 r = dup2(fd, nfd) < 0 ? -errno : nfd;
03e334a1 359 safe_close(fd);
80876c20
LP
360 } else
361 r = nfd;
071830ff 362
80876c20
LP
363 return r;
364}
071830ff 365
80876c20
LP
366static bool is_terminal_input(ExecInput i) {
367 return
368 i == EXEC_INPUT_TTY ||
369 i == EXEC_INPUT_TTY_FORCE ||
370 i == EXEC_INPUT_TTY_FAIL;
371}
071830ff 372
1e3ad081
LP
373static int fixup_input(ExecInput std_input, int socket_fd, bool apply_tty_stdin) {
374
375 if (is_terminal_input(std_input) && !apply_tty_stdin)
376 return EXEC_INPUT_NULL;
071830ff 377
03fd9c49 378 if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
379 return EXEC_INPUT_NULL;
380
03fd9c49 381 return std_input;
4f2d528d
LP
382}
383
03fd9c49 384static int fixup_output(ExecOutput std_output, int socket_fd) {
4f2d528d 385
03fd9c49 386 if (std_output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
4f2d528d
LP
387 return EXEC_OUTPUT_INHERIT;
388
03fd9c49 389 return std_output;
4f2d528d
LP
390}
391
a34ceba6
LP
392static int setup_input(
393 const ExecContext *context,
394 const ExecParameters *params,
395 int socket_fd) {
396
4f2d528d
LP
397 ExecInput i;
398
399 assert(context);
a34ceba6
LP
400 assert(params);
401
402 if (params->stdin_fd >= 0) {
403 if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
404 return -errno;
405
406 /* Try to make this the controlling tty, if it is a tty, and reset it */
407 (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
408 (void) reset_terminal_fd(STDIN_FILENO, true);
409
410 return STDIN_FILENO;
411 }
4f2d528d 412
a34ceba6 413 i = fixup_input(context->std_input, socket_fd, params->apply_tty_stdin);
4f2d528d
LP
414
415 switch (i) {
071830ff 416
80876c20
LP
417 case EXEC_INPUT_NULL:
418 return open_null_as(O_RDONLY, STDIN_FILENO);
419
420 case EXEC_INPUT_TTY:
421 case EXEC_INPUT_TTY_FORCE:
422 case EXEC_INPUT_TTY_FAIL: {
423 int fd, r;
071830ff 424
1e22b5cd 425 fd = acquire_terminal(exec_context_tty_path(context),
970edce6
ZJS
426 i == EXEC_INPUT_TTY_FAIL,
427 i == EXEC_INPUT_TTY_FORCE,
428 false,
3a43da28 429 USEC_INFINITY);
970edce6 430 if (fd < 0)
80876c20
LP
431 return fd;
432
433 if (fd != STDIN_FILENO) {
434 r = dup2(fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
03e334a1 435 safe_close(fd);
80876c20
LP
436 } else
437 r = STDIN_FILENO;
438
439 return r;
440 }
441
4f2d528d
LP
442 case EXEC_INPUT_SOCKET:
443 return dup2(socket_fd, STDIN_FILENO) < 0 ? -errno : STDIN_FILENO;
444
80876c20
LP
445 default:
446 assert_not_reached("Unknown input type");
447 }
448}
449
a34ceba6
LP
450static int setup_output(
451 Unit *unit,
452 const ExecContext *context,
453 const ExecParameters *params,
454 int fileno,
455 int socket_fd,
456 const char *ident,
7bce046b
LP
457 uid_t uid,
458 gid_t gid,
459 dev_t *journal_stream_dev,
460 ino_t *journal_stream_ino) {
a34ceba6 461
4f2d528d
LP
462 ExecOutput o;
463 ExecInput i;
47c1d80d 464 int r;
4f2d528d 465
f2341e0a 466 assert(unit);
80876c20 467 assert(context);
a34ceba6 468 assert(params);
80876c20 469 assert(ident);
7bce046b
LP
470 assert(journal_stream_dev);
471 assert(journal_stream_ino);
80876c20 472
a34ceba6
LP
473 if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
474
475 if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
476 return -errno;
477
478 return STDOUT_FILENO;
479 }
480
481 if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
482 if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
483 return -errno;
484
485 return STDERR_FILENO;
486 }
487
488 i = fixup_input(context->std_input, socket_fd, params->apply_tty_stdin);
03fd9c49 489 o = fixup_output(context->std_output, socket_fd);
4f2d528d 490
eb17e935
MS
491 if (fileno == STDERR_FILENO) {
492 ExecOutput e;
493 e = fixup_output(context->std_error, socket_fd);
80876c20 494
eb17e935
MS
495 /* This expects the input and output are already set up */
496
497 /* Don't change the stderr file descriptor if we inherit all
498 * the way and are not on a tty */
499 if (e == EXEC_OUTPUT_INHERIT &&
500 o == EXEC_OUTPUT_INHERIT &&
501 i == EXEC_INPUT_NULL &&
502 !is_terminal_input(context->std_input) &&
503 getppid () != 1)
504 return fileno;
505
506 /* Duplicate from stdout if possible */
507 if (e == o || e == EXEC_OUTPUT_INHERIT)
508 return dup2(STDOUT_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 509
eb17e935 510 o = e;
80876c20 511
eb17e935 512 } else if (o == EXEC_OUTPUT_INHERIT) {
21d21ea4
LP
513 /* If input got downgraded, inherit the original value */
514 if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
1e22b5cd 515 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
21d21ea4 516
acb591e4 517 /* If the input is connected to anything that's not a /dev/null, inherit that... */
ff876e28 518 if (i != EXEC_INPUT_NULL)
eb17e935 519 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
071830ff 520
acb591e4
LP
521 /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
522 if (getppid() != 1)
eb17e935 523 return fileno;
94f04347 524
eb17e935
MS
525 /* We need to open /dev/null here anew, to get the right access mode. */
526 return open_null_as(O_WRONLY, fileno);
071830ff 527 }
94f04347 528
eb17e935 529 switch (o) {
80876c20
LP
530
531 case EXEC_OUTPUT_NULL:
eb17e935 532 return open_null_as(O_WRONLY, fileno);
80876c20
LP
533
534 case EXEC_OUTPUT_TTY:
4f2d528d 535 if (is_terminal_input(i))
eb17e935 536 return dup2(STDIN_FILENO, fileno) < 0 ? -errno : fileno;
80876c20
LP
537
538 /* We don't reset the terminal if this is just about output */
1e22b5cd 539 return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
80876c20
LP
540
541 case EXEC_OUTPUT_SYSLOG:
28dbc1e8 542 case EXEC_OUTPUT_SYSLOG_AND_CONSOLE:
9a6bca7a 543 case EXEC_OUTPUT_KMSG:
28dbc1e8 544 case EXEC_OUTPUT_KMSG_AND_CONSOLE:
706343f4
LP
545 case EXEC_OUTPUT_JOURNAL:
546 case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
f2341e0a 547 r = connect_logger_as(context, o, ident, unit->id, fileno, uid, gid);
47c1d80d 548 if (r < 0) {
f2341e0a 549 log_unit_error_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m", fileno == STDOUT_FILENO ? "stdout" : "stderr");
eb17e935 550 r = open_null_as(O_WRONLY, fileno);
7bce046b
LP
551 } else {
552 struct stat st;
553
554 /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
555 * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
556 * services to detect whether they are connected to the journal or not. */
557
558 if (fstat(fileno, &st) >= 0) {
559 *journal_stream_dev = st.st_dev;
560 *journal_stream_ino = st.st_ino;
561 }
47c1d80d
MS
562 }
563 return r;
4f2d528d
LP
564
565 case EXEC_OUTPUT_SOCKET:
566 assert(socket_fd >= 0);
eb17e935 567 return dup2(socket_fd, fileno) < 0 ? -errno : fileno;
94f04347
LP
568
569 default:
80876c20 570 assert_not_reached("Unknown error type");
94f04347 571 }
071830ff
LP
572}
573
02a51aba
LP
574static int chown_terminal(int fd, uid_t uid) {
575 struct stat st;
576
577 assert(fd >= 0);
02a51aba 578
1ff74fb6
LP
579 /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
580 if (isatty(fd) < 1)
581 return 0;
582
02a51aba 583 /* This might fail. What matters are the results. */
bab45044
LP
584 (void) fchown(fd, uid, -1);
585 (void) fchmod(fd, TTY_MODE);
02a51aba
LP
586
587 if (fstat(fd, &st) < 0)
588 return -errno;
589
d8b4e2e9 590 if (st.st_uid != uid || (st.st_mode & 0777) != TTY_MODE)
02a51aba
LP
591 return -EPERM;
592
593 return 0;
594}
595
3d18b167
LP
596static int setup_confirm_stdio(int *_saved_stdin, int *_saved_stdout) {
597 _cleanup_close_ int fd = -1, saved_stdin = -1, saved_stdout = -1;
598 int r;
80876c20 599
80876c20
LP
600 assert(_saved_stdin);
601 assert(_saved_stdout);
602
af6da548
LP
603 saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
604 if (saved_stdin < 0)
605 return -errno;
80876c20 606
af6da548 607 saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
3d18b167
LP
608 if (saved_stdout < 0)
609 return -errno;
80876c20 610
af6da548
LP
611 fd = acquire_terminal(
612 "/dev/console",
613 false,
614 false,
615 false,
616 DEFAULT_CONFIRM_USEC);
3d18b167
LP
617 if (fd < 0)
618 return fd;
80876c20 619
af6da548
LP
620 r = chown_terminal(fd, getuid());
621 if (r < 0)
3d18b167 622 return r;
02a51aba 623
3d18b167
LP
624 r = reset_terminal_fd(fd, true);
625 if (r < 0)
626 return r;
80876c20 627
3d18b167
LP
628 if (dup2(fd, STDIN_FILENO) < 0)
629 return -errno;
630
631 if (dup2(fd, STDOUT_FILENO) < 0)
632 return -errno;
80876c20
LP
633
634 if (fd >= 2)
03e334a1 635 safe_close(fd);
3d18b167 636 fd = -1;
80876c20
LP
637
638 *_saved_stdin = saved_stdin;
639 *_saved_stdout = saved_stdout;
640
3d18b167 641 saved_stdin = saved_stdout = -1;
80876c20 642
3d18b167 643 return 0;
80876c20
LP
644}
645
44b601bc 646_printf_(1, 2) static int write_confirm_message(const char *format, ...) {
03e334a1 647 _cleanup_close_ int fd = -1;
af6da548 648 va_list ap;
80876c20 649
af6da548 650 assert(format);
80876c20 651
af6da548
LP
652 fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
653 if (fd < 0)
654 return fd;
80876c20 655
af6da548
LP
656 va_start(ap, format);
657 vdprintf(fd, format, ap);
658 va_end(ap);
80876c20 659
af6da548
LP
660 return 0;
661}
80876c20 662
3d18b167 663static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
af6da548 664 int r = 0;
80876c20 665
af6da548
LP
666 assert(saved_stdin);
667 assert(saved_stdout);
668
669 release_terminal();
670
671 if (*saved_stdin >= 0)
80876c20 672 if (dup2(*saved_stdin, STDIN_FILENO) < 0)
af6da548 673 r = -errno;
80876c20 674
af6da548 675 if (*saved_stdout >= 0)
80876c20 676 if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
af6da548 677 r = -errno;
80876c20 678
3d18b167
LP
679 *saved_stdin = safe_close(*saved_stdin);
680 *saved_stdout = safe_close(*saved_stdout);
af6da548
LP
681
682 return r;
683}
684
685static int ask_for_confirmation(char *response, char **argv) {
686 int saved_stdout = -1, saved_stdin = -1, r;
e1d75803 687 _cleanup_free_ char *line = NULL;
af6da548
LP
688
689 r = setup_confirm_stdio(&saved_stdin, &saved_stdout);
690 if (r < 0)
691 return r;
692
693 line = exec_command_line(argv);
694 if (!line)
695 return -ENOMEM;
696
418b9be5 697 r = ask_char(response, "yns", "Execute %s? [Yes, No, Skip] ", line);
af6da548
LP
698
699 restore_confirm_stdio(&saved_stdin, &saved_stdout);
700
701 return r;
80876c20
LP
702}
703
81a2b7ce
LP
704static int enforce_groups(const ExecContext *context, const char *username, gid_t gid) {
705 bool keep_groups = false;
706 int r;
707
708 assert(context);
709
35b8ca3a 710 /* Lookup and set GID and supplementary group list. Here too
81a2b7ce
LP
711 * we avoid NSS lookups for gid=0. */
712
713 if (context->group || username) {
81a2b7ce
LP
714 /* First step, initialize groups from /etc/groups */
715 if (username && gid != 0) {
716 if (initgroups(username, gid) < 0)
717 return -errno;
718
719 keep_groups = true;
720 }
721
722 /* Second step, set our gids */
723 if (setresgid(gid, gid, gid) < 0)
724 return -errno;
725 }
726
727 if (context->supplementary_groups) {
728 int ngroups_max, k;
729 gid_t *gids;
730 char **i;
731
732 /* Final step, initialize any manually set supplementary groups */
da19d5c1 733 assert_se((ngroups_max = (int) sysconf(_SC_NGROUPS_MAX)) > 0);
81a2b7ce
LP
734
735 if (!(gids = new(gid_t, ngroups_max)))
736 return -ENOMEM;
737
738 if (keep_groups) {
3cc2aff1
LP
739 k = getgroups(ngroups_max, gids);
740 if (k < 0) {
81a2b7ce
LP
741 free(gids);
742 return -errno;
743 }
744 } else
745 k = 0;
746
747 STRV_FOREACH(i, context->supplementary_groups) {
4b67834e 748 const char *g;
81a2b7ce
LP
749
750 if (k >= ngroups_max) {
751 free(gids);
752 return -E2BIG;
753 }
754
4b67834e
LP
755 g = *i;
756 r = get_group_creds(&g, gids+k);
757 if (r < 0) {
81a2b7ce
LP
758 free(gids);
759 return r;
760 }
761
762 k++;
763 }
764
765 if (setgroups(k, gids) < 0) {
766 free(gids);
767 return -errno;
768 }
769
770 free(gids);
771 }
772
773 return 0;
774}
775
776static int enforce_user(const ExecContext *context, uid_t uid) {
81a2b7ce
LP
777 assert(context);
778
479050b3 779 /* Sets (but doesn't look up) the uid and make sure we keep the
81a2b7ce
LP
780 * capabilities while doing so. */
781
479050b3 782 if (context->capability_ambient_set != 0) {
81a2b7ce
LP
783
784 /* First step: If we need to keep capabilities but
785 * drop privileges we need to make sure we keep our
cbb21cca 786 * caps, while we drop privileges. */
693ced48 787 if (uid != 0) {
cbb21cca 788 int sb = context->secure_bits | 1<<SECURE_KEEP_CAPS;
693ced48
LP
789
790 if (prctl(PR_GET_SECUREBITS) != sb)
791 if (prctl(PR_SET_SECUREBITS, sb) < 0)
792 return -errno;
793 }
81a2b7ce
LP
794 }
795
479050b3 796 /* Second step: actually set the uids */
81a2b7ce
LP
797 if (setresuid(uid, uid, uid) < 0)
798 return -errno;
799
800 /* At this point we should have all necessary capabilities but
801 are otherwise a normal user. However, the caps might got
802 corrupted due to the setresuid() so we need clean them up
803 later. This is done outside of this call. */
804
805 return 0;
806}
807
5b6319dc
LP
808#ifdef HAVE_PAM
809
810static int null_conv(
811 int num_msg,
812 const struct pam_message **msg,
813 struct pam_response **resp,
814 void *appdata_ptr) {
815
816 /* We don't support conversations */
817
818 return PAM_CONV_ERR;
819}
820
821static int setup_pam(
822 const char *name,
823 const char *user,
940c5210 824 uid_t uid,
5b6319dc 825 const char *tty,
2065ca69 826 char ***env,
5b6319dc
LP
827 int fds[], unsigned n_fds) {
828
829 static const struct pam_conv conv = {
830 .conv = null_conv,
831 .appdata_ptr = NULL
832 };
833
2d7c6aa2 834 _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
5b6319dc 835 pam_handle_t *handle = NULL;
d6e5f3ad 836 sigset_t old_ss;
7bb70b6e 837 int pam_code = PAM_SUCCESS, r;
5b6319dc
LP
838 char **e = NULL;
839 bool close_session = false;
840 pid_t pam_pid = 0, parent_pid;
970edce6 841 int flags = 0;
5b6319dc
LP
842
843 assert(name);
844 assert(user);
2065ca69 845 assert(env);
5b6319dc
LP
846
847 /* We set up PAM in the parent process, then fork. The child
35b8ca3a 848 * will then stay around until killed via PR_GET_PDEATHSIG or
5b6319dc
LP
849 * systemd via the cgroup logic. It will then remove the PAM
850 * session again. The parent process will exec() the actual
851 * daemon. We do things this way to ensure that the main PID
852 * of the daemon is the one we initially fork()ed. */
853
7bb70b6e
LP
854 r = barrier_create(&barrier);
855 if (r < 0)
2d7c6aa2
DH
856 goto fail;
857
553d2243 858 if (log_get_max_level() < LOG_DEBUG)
970edce6
ZJS
859 flags |= PAM_SILENT;
860
f546241b
ZJS
861 pam_code = pam_start(name, user, &conv, &handle);
862 if (pam_code != PAM_SUCCESS) {
5b6319dc
LP
863 handle = NULL;
864 goto fail;
865 }
866
f546241b
ZJS
867 if (tty) {
868 pam_code = pam_set_item(handle, PAM_TTY, tty);
869 if (pam_code != PAM_SUCCESS)
5b6319dc 870 goto fail;
f546241b 871 }
5b6319dc 872
2065ca69
JW
873 STRV_FOREACH(e, *env) {
874 pam_code = pam_putenv(handle, *e);
875 if (pam_code != PAM_SUCCESS)
876 goto fail;
877 }
878
970edce6 879 pam_code = pam_acct_mgmt(handle, flags);
f546241b 880 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
881 goto fail;
882
970edce6 883 pam_code = pam_open_session(handle, flags);
f546241b 884 if (pam_code != PAM_SUCCESS)
5b6319dc
LP
885 goto fail;
886
887 close_session = true;
888
f546241b
ZJS
889 e = pam_getenvlist(handle);
890 if (!e) {
5b6319dc
LP
891 pam_code = PAM_BUF_ERR;
892 goto fail;
893 }
894
895 /* Block SIGTERM, so that we know that it won't get lost in
896 * the child */
ce30c8dc 897
72c0a2c2 898 assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
5b6319dc
LP
899
900 parent_pid = getpid();
901
f546241b 902 pam_pid = fork();
7bb70b6e
LP
903 if (pam_pid < 0) {
904 r = -errno;
5b6319dc 905 goto fail;
7bb70b6e 906 }
5b6319dc
LP
907
908 if (pam_pid == 0) {
7bb70b6e 909 int sig, ret = EXIT_PAM;
5b6319dc
LP
910
911 /* The child's job is to reset the PAM session on
912 * termination */
2d7c6aa2 913 barrier_set_role(&barrier, BARRIER_CHILD);
5b6319dc
LP
914
915 /* This string must fit in 10 chars (i.e. the length
5d6b1584
LP
916 * of "/sbin/init"), to look pretty in /bin/ps */
917 rename_process("(sd-pam)");
5b6319dc
LP
918
919 /* Make sure we don't keep open the passed fds in this
920 child. We assume that otherwise only those fds are
921 open here that have been opened by PAM. */
922 close_many(fds, n_fds);
923
940c5210
AK
924 /* Drop privileges - we don't need any to pam_close_session
925 * and this will make PR_SET_PDEATHSIG work in most cases.
926 * If this fails, ignore the error - but expect sd-pam threads
927 * to fail to exit normally */
928 if (setresuid(uid, uid, uid) < 0)
da927ba9 929 log_error_errno(r, "Error: Failed to setresuid() in sd-pam: %m");
940c5210 930
ce30c8dc
LP
931 (void) ignore_signals(SIGPIPE, -1);
932
940c5210
AK
933 /* Wait until our parent died. This will only work if
934 * the above setresuid() succeeds, otherwise the kernel
935 * will not allow unprivileged parents kill their privileged
936 * children this way. We rely on the control groups kill logic
5b6319dc
LP
937 * to do the rest for us. */
938 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
939 goto child_finish;
940
2d7c6aa2
DH
941 /* Tell the parent that our setup is done. This is especially
942 * important regarding dropping privileges. Otherwise, unit
943 * setup might race against our setresuid(2) call. */
944 barrier_place(&barrier);
945
5b6319dc
LP
946 /* Check if our parent process might already have
947 * died? */
948 if (getppid() == parent_pid) {
d6e5f3ad
DM
949 sigset_t ss;
950
951 assert_se(sigemptyset(&ss) >= 0);
952 assert_se(sigaddset(&ss, SIGTERM) >= 0);
953
3dead8d9
LP
954 for (;;) {
955 if (sigwait(&ss, &sig) < 0) {
956 if (errno == EINTR)
957 continue;
958
959 goto child_finish;
960 }
5b6319dc 961
3dead8d9
LP
962 assert(sig == SIGTERM);
963 break;
964 }
5b6319dc
LP
965 }
966
3dead8d9 967 /* If our parent died we'll end the session */
f546241b 968 if (getppid() != parent_pid) {
970edce6 969 pam_code = pam_close_session(handle, flags);
f546241b 970 if (pam_code != PAM_SUCCESS)
5b6319dc 971 goto child_finish;
f546241b 972 }
5b6319dc 973
7bb70b6e 974 ret = 0;
5b6319dc
LP
975
976 child_finish:
970edce6 977 pam_end(handle, pam_code | flags);
7bb70b6e 978 _exit(ret);
5b6319dc
LP
979 }
980
2d7c6aa2
DH
981 barrier_set_role(&barrier, BARRIER_PARENT);
982
5b6319dc
LP
983 /* If the child was forked off successfully it will do all the
984 * cleanups, so forget about the handle here. */
985 handle = NULL;
986
3b8bddde 987 /* Unblock SIGTERM again in the parent */
72c0a2c2 988 assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
5b6319dc
LP
989
990 /* We close the log explicitly here, since the PAM modules
991 * might have opened it, but we don't want this fd around. */
992 closelog();
993
2d7c6aa2
DH
994 /* Synchronously wait for the child to initialize. We don't care for
995 * errors as we cannot recover. However, warn loudly if it happens. */
996 if (!barrier_place_and_sync(&barrier))
997 log_error("PAM initialization failed");
998
2065ca69
JW
999 strv_free(*env);
1000 *env = e;
aa87e624 1001
5b6319dc
LP
1002 return 0;
1003
1004fail:
970edce6
ZJS
1005 if (pam_code != PAM_SUCCESS) {
1006 log_error("PAM failed: %s", pam_strerror(handle, pam_code));
7bb70b6e
LP
1007 r = -EPERM; /* PAM errors do not map to errno */
1008 } else
1009 log_error_errno(r, "PAM failed: %m");
9ba35398 1010
5b6319dc
LP
1011 if (handle) {
1012 if (close_session)
970edce6 1013 pam_code = pam_close_session(handle, flags);
5b6319dc 1014
970edce6 1015 pam_end(handle, pam_code | flags);
5b6319dc
LP
1016 }
1017
1018 strv_free(e);
5b6319dc
LP
1019 closelog();
1020
7bb70b6e 1021 return r;
5b6319dc
LP
1022}
1023#endif
1024
5d6b1584
LP
1025static void rename_process_from_path(const char *path) {
1026 char process_name[11];
1027 const char *p;
1028 size_t l;
1029
1030 /* This resulting string must fit in 10 chars (i.e. the length
1031 * of "/sbin/init") to look pretty in /bin/ps */
1032
2b6bf07d 1033 p = basename(path);
5d6b1584
LP
1034 if (isempty(p)) {
1035 rename_process("(...)");
1036 return;
1037 }
1038
1039 l = strlen(p);
1040 if (l > 8) {
1041 /* The end of the process name is usually more
1042 * interesting, since the first bit might just be
1043 * "systemd-" */
1044 p = p + l - 8;
1045 l = 8;
1046 }
1047
1048 process_name[0] = '(';
1049 memcpy(process_name+1, p, l);
1050 process_name[1+l] = ')';
1051 process_name[1+l+1] = 0;
1052
1053 rename_process(process_name);
1054}
1055
c0467cf3 1056#ifdef HAVE_SECCOMP
17df7223 1057
822a5960 1058static int apply_seccomp(const ExecContext *c) {
17df7223
LP
1059 uint32_t negative_action, action;
1060 scmp_filter_ctx *seccomp;
c0467cf3
RC
1061 Iterator i;
1062 void *id;
17df7223 1063 int r;
8351ceae 1064
c0467cf3 1065 assert(c);
8351ceae 1066
17df7223
LP
1067 negative_action = c->syscall_errno == 0 ? SCMP_ACT_KILL : SCMP_ACT_ERRNO(c->syscall_errno);
1068
1069 seccomp = seccomp_init(c->syscall_whitelist ? negative_action : SCMP_ACT_ALLOW);
1070 if (!seccomp)
1071 return -ENOMEM;
8351ceae 1072
e9642be2
LP
1073 if (c->syscall_archs) {
1074
1075 SET_FOREACH(id, c->syscall_archs, i) {
1076 r = seccomp_arch_add(seccomp, PTR_TO_UINT32(id) - 1);
1077 if (r == -EEXIST)
1078 continue;
7c66bae2
LP
1079 if (r < 0)
1080 goto finish;
e9642be2 1081 }
e9642be2 1082
7c66bae2 1083 } else {
e9642be2 1084 r = seccomp_add_secondary_archs(seccomp);
7c66bae2
LP
1085 if (r < 0)
1086 goto finish;
57183d11 1087 }
8351ceae 1088
57183d11 1089 action = c->syscall_whitelist ? SCMP_ACT_ALLOW : negative_action;
17df7223
LP
1090 SET_FOREACH(id, c->syscall_filter, i) {
1091 r = seccomp_rule_add(seccomp, action, PTR_TO_INT(id) - 1, 0);
7c66bae2
LP
1092 if (r < 0)
1093 goto finish;
c0467cf3 1094 }
8351ceae 1095
7c66bae2
LP
1096 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1097 if (r < 0)
1098 goto finish;
1099
17df7223 1100 r = seccomp_load(seccomp);
7c66bae2
LP
1101
1102finish:
17df7223 1103 seccomp_release(seccomp);
4298d0b5
LP
1104 return r;
1105}
1106
822a5960 1107static int apply_address_families(const ExecContext *c) {
4298d0b5
LP
1108 scmp_filter_ctx *seccomp;
1109 Iterator i;
1110 int r;
1111
1112 assert(c);
1113
1114 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1115 if (!seccomp)
1116 return -ENOMEM;
1117
1118 r = seccomp_add_secondary_archs(seccomp);
1119 if (r < 0)
1120 goto finish;
1121
1122 if (c->address_families_whitelist) {
1123 int af, first = 0, last = 0;
1124 void *afp;
1125
1126 /* If this is a whitelist, we first block the address
1127 * families that are out of range and then everything
1128 * that is not in the set. First, we find the lowest
1129 * and highest address family in the set. */
1130
1131 SET_FOREACH(afp, c->address_families, i) {
1132 af = PTR_TO_INT(afp);
17df7223 1133
4298d0b5
LP
1134 if (af <= 0 || af >= af_max())
1135 continue;
1136
1137 if (first == 0 || af < first)
1138 first = af;
1139
1140 if (last == 0 || af > last)
1141 last = af;
1142 }
1143
1144 assert((first == 0) == (last == 0));
1145
1146 if (first == 0) {
1147
1148 /* No entries in the valid range, block everything */
1149 r = seccomp_rule_add(
1150 seccomp,
1151 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1152 SCMP_SYS(socket),
1153 0);
1154 if (r < 0)
1155 goto finish;
1156
1157 } else {
1158
1159 /* Block everything below the first entry */
1160 r = seccomp_rule_add(
1161 seccomp,
1162 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1163 SCMP_SYS(socket),
1164 1,
1165 SCMP_A0(SCMP_CMP_LT, first));
1166 if (r < 0)
1167 goto finish;
1168
1169 /* Block everything above the last entry */
1170 r = seccomp_rule_add(
1171 seccomp,
1172 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1173 SCMP_SYS(socket),
1174 1,
1175 SCMP_A0(SCMP_CMP_GT, last));
1176 if (r < 0)
1177 goto finish;
1178
1179 /* Block everything between the first and last
1180 * entry */
1181 for (af = 1; af < af_max(); af++) {
1182
1183 if (set_contains(c->address_families, INT_TO_PTR(af)))
1184 continue;
1185
1186 r = seccomp_rule_add(
1187 seccomp,
1188 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1189 SCMP_SYS(socket),
1190 1,
1191 SCMP_A0(SCMP_CMP_EQ, af));
1192 if (r < 0)
1193 goto finish;
1194 }
1195 }
1196
1197 } else {
1198 void *af;
1199
1200 /* If this is a blacklist, then generate one rule for
1201 * each address family that are then combined in OR
1202 * checks. */
1203
1204 SET_FOREACH(af, c->address_families, i) {
1205
1206 r = seccomp_rule_add(
1207 seccomp,
1208 SCMP_ACT_ERRNO(EPROTONOSUPPORT),
1209 SCMP_SYS(socket),
1210 1,
1211 SCMP_A0(SCMP_CMP_EQ, PTR_TO_INT(af)));
1212 if (r < 0)
1213 goto finish;
1214 }
1215 }
1216
1217 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1218 if (r < 0)
1219 goto finish;
1220
1221 r = seccomp_load(seccomp);
1222
1223finish:
1224 seccomp_release(seccomp);
17df7223 1225 return r;
8351ceae 1226}
4298d0b5 1227
f3e43635
TM
1228static int apply_memory_deny_write_execute(const ExecContext *c) {
1229 scmp_filter_ctx *seccomp;
1230 int r;
1231
1232 assert(c);
1233
1234 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1235 if (!seccomp)
1236 return -ENOMEM;
1237
1238 r = seccomp_rule_add(
1239 seccomp,
abd84d4d 1240 SCMP_ACT_ERRNO(EPERM),
f3e43635
TM
1241 SCMP_SYS(mmap),
1242 1,
1243 SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC|PROT_WRITE, PROT_EXEC|PROT_WRITE));
1244 if (r < 0)
1245 goto finish;
1246
1247 r = seccomp_rule_add(
1248 seccomp,
abd84d4d 1249 SCMP_ACT_ERRNO(EPERM),
f3e43635
TM
1250 SCMP_SYS(mprotect),
1251 1,
1252 SCMP_A2(SCMP_CMP_MASKED_EQ, PROT_EXEC, PROT_EXEC));
1253 if (r < 0)
1254 goto finish;
1255
1256 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1257 if (r < 0)
1258 goto finish;
1259
1260 r = seccomp_load(seccomp);
1261
1262finish:
1263 seccomp_release(seccomp);
1264 return r;
1265}
1266
f4170c67
LP
1267static int apply_restrict_realtime(const ExecContext *c) {
1268 static const int permitted_policies[] = {
1269 SCHED_OTHER,
1270 SCHED_BATCH,
1271 SCHED_IDLE,
1272 };
1273
1274 scmp_filter_ctx *seccomp;
1275 unsigned i;
1276 int r, p, max_policy = 0;
1277
1278 assert(c);
1279
1280 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1281 if (!seccomp)
1282 return -ENOMEM;
1283
1284 /* Determine the highest policy constant we want to allow */
1285 for (i = 0; i < ELEMENTSOF(permitted_policies); i++)
1286 if (permitted_policies[i] > max_policy)
1287 max_policy = permitted_policies[i];
1288
1289 /* Go through all policies with lower values than that, and block them -- unless they appear in the
1290 * whitelist. */
1291 for (p = 0; p < max_policy; p++) {
1292 bool good = false;
1293
1294 /* Check if this is in the whitelist. */
1295 for (i = 0; i < ELEMENTSOF(permitted_policies); i++)
1296 if (permitted_policies[i] == p) {
1297 good = true;
1298 break;
1299 }
1300
1301 if (good)
1302 continue;
1303
1304 /* Deny this policy */
1305 r = seccomp_rule_add(
1306 seccomp,
1307 SCMP_ACT_ERRNO(EPERM),
1308 SCMP_SYS(sched_setscheduler),
1309 1,
1310 SCMP_A1(SCMP_CMP_EQ, p));
1311 if (r < 0)
1312 goto finish;
1313 }
1314
1315 /* Blacklist all other policies, i.e. the ones with higher values. Note that all comparisons are unsigned here,
1316 * hence no need no check for < 0 values. */
1317 r = seccomp_rule_add(
1318 seccomp,
1319 SCMP_ACT_ERRNO(EPERM),
1320 SCMP_SYS(sched_setscheduler),
1321 1,
1322 SCMP_A1(SCMP_CMP_GT, max_policy));
1323 if (r < 0)
1324 goto finish;
1325
1326 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1327 if (r < 0)
1328 goto finish;
1329
1330 r = seccomp_load(seccomp);
1331
1332finish:
1333 seccomp_release(seccomp);
1334 return r;
1335}
1336
c0467cf3 1337#endif
8351ceae 1338
31a7eb86
ZJS
1339static void do_idle_pipe_dance(int idle_pipe[4]) {
1340 assert(idle_pipe);
1341
03e334a1 1342
54eb2300
LP
1343 idle_pipe[1] = safe_close(idle_pipe[1]);
1344 idle_pipe[2] = safe_close(idle_pipe[2]);
31a7eb86
ZJS
1345
1346 if (idle_pipe[0] >= 0) {
1347 int r;
1348
1349 r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
1350
1351 if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
c7cc737f
LP
1352 ssize_t n;
1353
31a7eb86 1354 /* Signal systemd that we are bored and want to continue. */
c7cc737f
LP
1355 n = write(idle_pipe[3], "x", 1);
1356 if (n > 0)
cd972d69
ZJS
1357 /* Wait for systemd to react to the signal above. */
1358 fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
31a7eb86
ZJS
1359 }
1360
54eb2300 1361 idle_pipe[0] = safe_close(idle_pipe[0]);
31a7eb86
ZJS
1362
1363 }
1364
54eb2300 1365 idle_pipe[3] = safe_close(idle_pipe[3]);
31a7eb86
ZJS
1366}
1367
7cae38c4 1368static int build_environment(
9fa95f85 1369 const ExecContext *c,
1e22b5cd 1370 const ExecParameters *p,
7cae38c4
LP
1371 unsigned n_fds,
1372 const char *home,
1373 const char *username,
1374 const char *shell,
7bce046b
LP
1375 dev_t journal_stream_dev,
1376 ino_t journal_stream_ino,
7cae38c4
LP
1377 char ***ret) {
1378
1379 _cleanup_strv_free_ char **our_env = NULL;
1380 unsigned n_env = 0;
1381 char *x;
1382
1383 assert(c);
1384 assert(ret);
1385
7bce046b 1386 our_env = new0(char*, 12);
7cae38c4
LP
1387 if (!our_env)
1388 return -ENOMEM;
1389
1390 if (n_fds > 0) {
8dd4c05b
LP
1391 _cleanup_free_ char *joined = NULL;
1392
ccd06097 1393 if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid()) < 0)
7cae38c4
LP
1394 return -ENOMEM;
1395 our_env[n_env++] = x;
1396
1397 if (asprintf(&x, "LISTEN_FDS=%u", n_fds) < 0)
1398 return -ENOMEM;
1399 our_env[n_env++] = x;
8dd4c05b 1400
1e22b5cd 1401 joined = strv_join(p->fd_names, ":");
8dd4c05b
LP
1402 if (!joined)
1403 return -ENOMEM;
1404
1405 x = strjoin("LISTEN_FDNAMES=", joined, NULL);
1406 if (!x)
1407 return -ENOMEM;
1408 our_env[n_env++] = x;
7cae38c4
LP
1409 }
1410
1e22b5cd 1411 if (p->watchdog_usec > 0) {
ccd06097 1412 if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid()) < 0)
09812eb7
LP
1413 return -ENOMEM;
1414 our_env[n_env++] = x;
1415
1e22b5cd 1416 if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
09812eb7
LP
1417 return -ENOMEM;
1418 our_env[n_env++] = x;
1419 }
1420
7cae38c4
LP
1421 if (home) {
1422 x = strappend("HOME=", home);
1423 if (!x)
1424 return -ENOMEM;
1425 our_env[n_env++] = x;
1426 }
1427
1428 if (username) {
1429 x = strappend("LOGNAME=", username);
1430 if (!x)
1431 return -ENOMEM;
1432 our_env[n_env++] = x;
1433
1434 x = strappend("USER=", username);
1435 if (!x)
1436 return -ENOMEM;
1437 our_env[n_env++] = x;
1438 }
1439
1440 if (shell) {
1441 x = strappend("SHELL=", shell);
1442 if (!x)
1443 return -ENOMEM;
1444 our_env[n_env++] = x;
1445 }
1446
1447 if (is_terminal_input(c->std_input) ||
1448 c->std_output == EXEC_OUTPUT_TTY ||
1449 c->std_error == EXEC_OUTPUT_TTY ||
1450 c->tty_path) {
1451
1e22b5cd 1452 x = strdup(default_term_for_tty(exec_context_tty_path(c)));
7cae38c4
LP
1453 if (!x)
1454 return -ENOMEM;
1455 our_env[n_env++] = x;
1456 }
1457
7bce046b
LP
1458 if (journal_stream_dev != 0 && journal_stream_ino != 0) {
1459 if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
1460 return -ENOMEM;
1461
1462 our_env[n_env++] = x;
1463 }
1464
7cae38c4 1465 our_env[n_env++] = NULL;
7bce046b 1466 assert(n_env <= 12);
7cae38c4
LP
1467
1468 *ret = our_env;
1469 our_env = NULL;
1470
1471 return 0;
1472}
1473
b4c14404
FB
1474static int build_pass_environment(const ExecContext *c, char ***ret) {
1475 _cleanup_strv_free_ char **pass_env = NULL;
1476 size_t n_env = 0, n_bufsize = 0;
1477 char **i;
1478
1479 STRV_FOREACH(i, c->pass_environment) {
1480 _cleanup_free_ char *x = NULL;
1481 char *v;
1482
1483 v = getenv(*i);
1484 if (!v)
1485 continue;
1486 x = strjoin(*i, "=", v, NULL);
1487 if (!x)
1488 return -ENOMEM;
1489 if (!GREEDY_REALLOC(pass_env, n_bufsize, n_env + 2))
1490 return -ENOMEM;
1491 pass_env[n_env++] = x;
1492 pass_env[n_env] = NULL;
1493 x = NULL;
1494 }
1495
1496 *ret = pass_env;
1497 pass_env = NULL;
1498
1499 return 0;
1500}
1501
8b44a3d2
LP
1502static bool exec_needs_mount_namespace(
1503 const ExecContext *context,
1504 const ExecParameters *params,
1505 ExecRuntime *runtime) {
1506
1507 assert(context);
1508 assert(params);
1509
1510 if (!strv_isempty(context->read_write_dirs) ||
1511 !strv_isempty(context->read_only_dirs) ||
1512 !strv_isempty(context->inaccessible_dirs))
1513 return true;
1514
1515 if (context->mount_flags != 0)
1516 return true;
1517
1518 if (context->private_tmp && runtime && (runtime->tmp_dir || runtime->var_tmp_dir))
1519 return true;
1520
8b44a3d2
LP
1521 if (context->private_devices ||
1522 context->protect_system != PROTECT_SYSTEM_NO ||
1523 context->protect_home != PROTECT_HOME_NO)
1524 return true;
1525
1526 return false;
1527}
1528
a34ceba6
LP
1529static int close_remaining_fds(
1530 const ExecParameters *params,
1531 ExecRuntime *runtime,
1532 int socket_fd,
1533 int *fds, unsigned n_fds) {
1534
1535 unsigned n_dont_close = 0;
1536 int dont_close[n_fds + 7];
1537
1538 assert(params);
1539
1540 if (params->stdin_fd >= 0)
1541 dont_close[n_dont_close++] = params->stdin_fd;
1542 if (params->stdout_fd >= 0)
1543 dont_close[n_dont_close++] = params->stdout_fd;
1544 if (params->stderr_fd >= 0)
1545 dont_close[n_dont_close++] = params->stderr_fd;
1546
1547 if (socket_fd >= 0)
1548 dont_close[n_dont_close++] = socket_fd;
1549 if (n_fds > 0) {
1550 memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
1551 n_dont_close += n_fds;
1552 }
1553
a34ceba6
LP
1554 if (runtime) {
1555 if (runtime->netns_storage_socket[0] >= 0)
1556 dont_close[n_dont_close++] = runtime->netns_storage_socket[0];
1557 if (runtime->netns_storage_socket[1] >= 0)
1558 dont_close[n_dont_close++] = runtime->netns_storage_socket[1];
1559 }
1560
1561 return close_all_fds(dont_close, n_dont_close);
1562}
1563
ff0af2a1 1564static int exec_child(
f2341e0a 1565 Unit *unit,
ff0af2a1
LP
1566 ExecCommand *command,
1567 const ExecContext *context,
1568 const ExecParameters *params,
1569 ExecRuntime *runtime,
1570 char **argv,
1571 int socket_fd,
1572 int *fds, unsigned n_fds,
1573 char **files_env,
1574 int *exit_status) {
d35fbf6b 1575
2065ca69 1576 _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **accum_env = NULL, **final_argv = NULL;
9008e1ac 1577 _cleanup_free_ char *mac_selinux_context_net = NULL;
5f5d8eab 1578 const char *username = NULL, *home = NULL, *shell = NULL, *wd;
7bce046b
LP
1579 dev_t journal_stream_dev = 0;
1580 ino_t journal_stream_ino = 0;
1581 bool needs_mount_namespace;
fed1e721
LP
1582 uid_t uid = UID_INVALID;
1583 gid_t gid = GID_INVALID;
ff0af2a1 1584 int i, r;
034c6ed7 1585
f2341e0a 1586 assert(unit);
5cb5a6ff
LP
1587 assert(command);
1588 assert(context);
d35fbf6b 1589 assert(params);
ff0af2a1 1590 assert(exit_status);
d35fbf6b
DM
1591
1592 rename_process_from_path(command->path);
1593
1594 /* We reset exactly these signals, since they are the
1595 * only ones we set to SIG_IGN in the main daemon. All
1596 * others we leave untouched because we set them to
1597 * SIG_DFL or a valid handler initially, both of which
1598 * will be demoted to SIG_DFL. */
ce30c8dc
LP
1599 (void) default_signals(SIGNALS_CRASH_HANDLER,
1600 SIGNALS_IGNORE, -1);
d35fbf6b
DM
1601
1602 if (context->ignore_sigpipe)
ce30c8dc 1603 (void) ignore_signals(SIGPIPE, -1);
d35fbf6b 1604
ff0af2a1
LP
1605 r = reset_signal_mask();
1606 if (r < 0) {
1607 *exit_status = EXIT_SIGNAL_MASK;
1608 return r;
d35fbf6b 1609 }
034c6ed7 1610
d35fbf6b
DM
1611 if (params->idle_pipe)
1612 do_idle_pipe_dance(params->idle_pipe);
4f2d528d 1613
d35fbf6b
DM
1614 /* Close sockets very early to make sure we don't
1615 * block init reexecution because it cannot bind its
1616 * sockets */
ff0af2a1 1617
d35fbf6b 1618 log_forget_fds();
4f2d528d 1619
a34ceba6 1620 r = close_remaining_fds(params, runtime, socket_fd, fds, n_fds);
ff0af2a1
LP
1621 if (r < 0) {
1622 *exit_status = EXIT_FDS;
1623 return r;
8c7be95e
LP
1624 }
1625
d35fbf6b
DM
1626 if (!context->same_pgrp)
1627 if (setsid() < 0) {
ff0af2a1 1628 *exit_status = EXIT_SETSID;
d35fbf6b
DM
1629 return -errno;
1630 }
9e2f7c11 1631
1e22b5cd 1632 exec_context_tty_reset(context, params);
d35fbf6b
DM
1633
1634 if (params->confirm_spawn) {
1635 char response;
1636
ff0af2a1
LP
1637 r = ask_for_confirmation(&response, argv);
1638 if (r == -ETIMEDOUT)
d35fbf6b 1639 write_confirm_message("Confirmation question timed out, assuming positive response.\n");
ff0af2a1
LP
1640 else if (r < 0)
1641 write_confirm_message("Couldn't ask confirmation question, assuming positive response: %s\n", strerror(-r));
d35fbf6b
DM
1642 else if (response == 's') {
1643 write_confirm_message("Skipping execution.\n");
ff0af2a1 1644 *exit_status = EXIT_CONFIRM;
d35fbf6b
DM
1645 return -ECANCELED;
1646 } else if (response == 'n') {
1647 write_confirm_message("Failing execution.\n");
ff0af2a1 1648 *exit_status = 0;
d35fbf6b
DM
1649 return 0;
1650 }
1651 }
1a63a750 1652
524daa8c
ZJS
1653 if (context->user) {
1654 username = context->user;
ff0af2a1
LP
1655 r = get_user_creds(&username, &uid, &gid, &home, &shell);
1656 if (r < 0) {
1657 *exit_status = EXIT_USER;
1658 return r;
524daa8c
ZJS
1659 }
1660 }
1661
5bc7452b
RC
1662 if (context->group) {
1663 const char *g = context->group;
1664
1665 r = get_group_creds(&g, &gid);
1666 if (r < 0) {
1667 *exit_status = EXIT_GROUP;
1668 return r;
1669 }
1670 }
1671
1672
d35fbf6b
DM
1673 /* If a socket is connected to STDIN/STDOUT/STDERR, we
1674 * must sure to drop O_NONBLOCK */
1675 if (socket_fd >= 0)
a34ceba6 1676 (void) fd_nonblock(socket_fd, false);
acbb0225 1677
a34ceba6 1678 r = setup_input(context, params, socket_fd);
ff0af2a1
LP
1679 if (r < 0) {
1680 *exit_status = EXIT_STDIN;
1681 return r;
d35fbf6b 1682 }
034c6ed7 1683
7bce046b 1684 r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
1685 if (r < 0) {
1686 *exit_status = EXIT_STDOUT;
1687 return r;
d35fbf6b
DM
1688 }
1689
7bce046b 1690 r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
ff0af2a1
LP
1691 if (r < 0) {
1692 *exit_status = EXIT_STDERR;
1693 return r;
d35fbf6b
DM
1694 }
1695
1696 if (params->cgroup_path) {
ff0af2a1
LP
1697 r = cg_attach_everywhere(params->cgroup_supported, params->cgroup_path, 0, NULL, NULL);
1698 if (r < 0) {
1699 *exit_status = EXIT_CGROUP;
1700 return r;
309bff19 1701 }
d35fbf6b 1702 }
309bff19 1703
d35fbf6b 1704 if (context->oom_score_adjust_set) {
d5243d62 1705 char t[DECIMAL_STR_MAX(context->oom_score_adjust)];
f2b68789 1706
d5243d62
LP
1707 /* When we can't make this change due to EPERM, then
1708 * let's silently skip over it. User namespaces
1709 * prohibit write access to this file, and we
1710 * shouldn't trip up over that. */
613b411c 1711
d5243d62 1712 sprintf(t, "%i", context->oom_score_adjust);
ad118bda 1713 r = write_string_file("/proc/self/oom_score_adj", t, 0);
6cb7fa17 1714 if (r == -EPERM || r == -EACCES) {
ff0af2a1 1715 log_open();
f2341e0a 1716 log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
ff0af2a1
LP
1717 log_close();
1718 } else if (r < 0) {
1719 *exit_status = EXIT_OOM_ADJUST;
d35fbf6b 1720 return -errno;
613b411c 1721 }
d35fbf6b
DM
1722 }
1723
1724 if (context->nice_set)
1725 if (setpriority(PRIO_PROCESS, 0, context->nice) < 0) {
ff0af2a1 1726 *exit_status = EXIT_NICE;
d35fbf6b 1727 return -errno;
613b411c
LP
1728 }
1729
d35fbf6b
DM
1730 if (context->cpu_sched_set) {
1731 struct sched_param param = {
1732 .sched_priority = context->cpu_sched_priority,
1733 };
1734
ff0af2a1
LP
1735 r = sched_setscheduler(0,
1736 context->cpu_sched_policy |
1737 (context->cpu_sched_reset_on_fork ?
1738 SCHED_RESET_ON_FORK : 0),
1739 &param);
1740 if (r < 0) {
1741 *exit_status = EXIT_SETSCHEDULER;
d35fbf6b 1742 return -errno;
fc9b2a84 1743 }
d35fbf6b 1744 }
fc9b2a84 1745
d35fbf6b
DM
1746 if (context->cpuset)
1747 if (sched_setaffinity(0, CPU_ALLOC_SIZE(context->cpuset_ncpus), context->cpuset) < 0) {
ff0af2a1 1748 *exit_status = EXIT_CPUAFFINITY;
d35fbf6b 1749 return -errno;
034c6ed7
LP
1750 }
1751
d35fbf6b
DM
1752 if (context->ioprio_set)
1753 if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
ff0af2a1 1754 *exit_status = EXIT_IOPRIO;
d35fbf6b
DM
1755 return -errno;
1756 }
da726a4d 1757
d35fbf6b
DM
1758 if (context->timer_slack_nsec != NSEC_INFINITY)
1759 if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
ff0af2a1 1760 *exit_status = EXIT_TIMERSLACK;
d35fbf6b 1761 return -errno;
4c2630eb 1762 }
9eba9da4 1763
050f7277 1764 if (context->personality != PERSONALITY_INVALID)
d35fbf6b 1765 if (personality(context->personality) < 0) {
ff0af2a1 1766 *exit_status = EXIT_PERSONALITY;
d35fbf6b 1767 return -errno;
4c2630eb 1768 }
94f04347 1769
d35fbf6b 1770 if (context->utmp_id)
023a4f67
LP
1771 utmp_put_init_process(context->utmp_id, getpid(), getsid(0), context->tty_path,
1772 context->utmp_mode == EXEC_UTMP_INIT ? INIT_PROCESS :
1773 context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
1774 USER_PROCESS,
1775 username ? "root" : context->user);
d35fbf6b 1776
524daa8c 1777 if (context->user && is_terminal_input(context->std_input)) {
ff0af2a1
LP
1778 r = chown_terminal(STDIN_FILENO, uid);
1779 if (r < 0) {
1780 *exit_status = EXIT_STDIN;
1781 return r;
071830ff 1782 }
d35fbf6b 1783 }
8e274523 1784
a931ad47
LP
1785 /* If delegation is enabled we'll pass ownership of the cgroup
1786 * (but only in systemd's own controller hierarchy!) to the
1787 * user of the new process. */
1788 if (params->cgroup_path && context->user && params->cgroup_delegate) {
ff0af2a1
LP
1789 r = cg_set_task_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0644, uid, gid);
1790 if (r < 0) {
1791 *exit_status = EXIT_CGROUP;
1792 return r;
d35fbf6b 1793 }
034c6ed7 1794
034c6ed7 1795
ff0af2a1
LP
1796 r = cg_set_group_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, 0755, uid, gid);
1797 if (r < 0) {
1798 *exit_status = EXIT_CGROUP;
1799 return r;
034c6ed7 1800 }
d35fbf6b 1801 }
034c6ed7 1802
d35fbf6b
DM
1803 if (!strv_isempty(context->runtime_directory) && params->runtime_prefix) {
1804 char **rt;
fb33a393 1805
d35fbf6b
DM
1806 STRV_FOREACH(rt, context->runtime_directory) {
1807 _cleanup_free_ char *p;
94f04347 1808
d35fbf6b
DM
1809 p = strjoin(params->runtime_prefix, "/", *rt, NULL);
1810 if (!p) {
ff0af2a1 1811 *exit_status = EXIT_RUNTIME_DIRECTORY;
d35fbf6b 1812 return -ENOMEM;
94f04347 1813 }
94f04347 1814
6bfe5c28
LP
1815 r = mkdir_p_label(p, context->runtime_directory_mode);
1816 if (r < 0) {
1817 *exit_status = EXIT_RUNTIME_DIRECTORY;
1818 return r;
1819 }
1820
1821 r = chmod_and_chown(p, context->runtime_directory_mode, uid, gid);
ff0af2a1
LP
1822 if (r < 0) {
1823 *exit_status = EXIT_RUNTIME_DIRECTORY;
1824 return r;
94f04347 1825 }
d35fbf6b
DM
1826 }
1827 }
94f04347 1828
7bce046b
LP
1829 r = build_environment(
1830 context,
1831 params,
1832 n_fds,
1833 home,
1834 username,
1835 shell,
1836 journal_stream_dev,
1837 journal_stream_ino,
1838 &our_env);
2065ca69
JW
1839 if (r < 0) {
1840 *exit_status = EXIT_MEMORY;
1841 return r;
1842 }
1843
1844 r = build_pass_environment(context, &pass_env);
1845 if (r < 0) {
1846 *exit_status = EXIT_MEMORY;
1847 return r;
1848 }
1849
1850 accum_env = strv_env_merge(5,
1851 params->environment,
1852 our_env,
1853 pass_env,
1854 context->environment,
1855 files_env,
1856 NULL);
1857 if (!accum_env) {
1858 *exit_status = EXIT_MEMORY;
1859 return -ENOMEM;
1860 }
1861
b213e1c1
SW
1862 umask(context->umask);
1863
cf677fe6 1864 if (params->apply_permissions && !command->privileged) {
ff0af2a1
LP
1865 r = enforce_groups(context, username, gid);
1866 if (r < 0) {
1867 *exit_status = EXIT_GROUP;
1868 return r;
d35fbf6b 1869 }
6bf6e43e 1870#ifdef HAVE_SMACK
6bf6e43e
SW
1871 if (context->smack_process_label) {
1872 r = mac_smack_apply_pid(0, context->smack_process_label);
1873 if (r < 0) {
1874 *exit_status = EXIT_SMACK_PROCESS_LABEL;
1875 return r;
1876 }
1877 }
1878#ifdef SMACK_DEFAULT_PROCESS_LABEL
1879 else {
1880 _cleanup_free_ char *exec_label = NULL;
1881
1882 r = mac_smack_read(command->path, SMACK_ATTR_EXEC, &exec_label);
1883 if (r < 0 && r != -ENODATA && r != -EOPNOTSUPP) {
1884 *exit_status = EXIT_SMACK_PROCESS_LABEL;
1885 return r;
1886 }
1887
1888 r = mac_smack_apply_pid(0, exec_label ? : SMACK_DEFAULT_PROCESS_LABEL);
1889 if (r < 0) {
1890 *exit_status = EXIT_SMACK_PROCESS_LABEL;
1891 return r;
1892 }
1893 }
6bf6e43e
SW
1894#endif
1895#endif
d35fbf6b 1896#ifdef HAVE_PAM
b213e1c1 1897 if (context->pam_name && username) {
2065ca69 1898 r = setup_pam(context->pam_name, username, uid, context->tty_path, &accum_env, fds, n_fds);
b213e1c1
SW
1899 if (r < 0) {
1900 *exit_status = EXIT_PAM;
1901 return r;
1902 }
d35fbf6b 1903 }
d35fbf6b 1904#endif
b213e1c1 1905 }
ac45f971 1906
d35fbf6b 1907 if (context->private_network && runtime && runtime->netns_storage_socket[0] >= 0) {
ff0af2a1
LP
1908 r = setup_netns(runtime->netns_storage_socket);
1909 if (r < 0) {
1910 *exit_status = EXIT_NETWORK;
1911 return r;
d35fbf6b
DM
1912 }
1913 }
169c1bda 1914
ee818b89
AC
1915 needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
1916
1917 if (needs_mount_namespace) {
d35fbf6b
DM
1918 char *tmp = NULL, *var = NULL;
1919
1920 /* The runtime struct only contains the parent
1921 * of the private /tmp, which is
1922 * non-accessible to world users. Inside of it
1923 * there's a /tmp that is sticky, and that's
1924 * the one we want to use here. */
1925
1926 if (context->private_tmp && runtime) {
1927 if (runtime->tmp_dir)
63c372cb 1928 tmp = strjoina(runtime->tmp_dir, "/tmp");
d35fbf6b 1929 if (runtime->var_tmp_dir)
63c372cb 1930 var = strjoina(runtime->var_tmp_dir, "/tmp");
d35fbf6b 1931 }
d8b4e2e9 1932
ff0af2a1 1933 r = setup_namespace(
ee818b89 1934 params->apply_chroot ? context->root_directory : NULL,
d35fbf6b
DM
1935 context->read_write_dirs,
1936 context->read_only_dirs,
1937 context->inaccessible_dirs,
1938 tmp,
1939 var,
1940 context->private_devices,
1941 context->protect_home,
1942 context->protect_system,
1943 context->mount_flags);
0015ebf3 1944
ff0af2a1
LP
1945 /* If we couldn't set up the namespace this is
1946 * probably due to a missing capability. In this case,
1947 * silently proceeed. */
1948 if (r == -EPERM || r == -EACCES) {
1949 log_open();
f2341e0a 1950 log_unit_debug_errno(unit, r, "Failed to set up namespace, assuming containerized execution, ignoring: %m");
ff0af2a1
LP
1951 log_close();
1952 } else if (r < 0) {
1953 *exit_status = EXIT_NAMESPACE;
1954 return r;
81a2b7ce 1955 }
d35fbf6b 1956 }
81a2b7ce 1957
5f5d8eab
LP
1958 if (context->working_directory_home)
1959 wd = home;
1960 else if (context->working_directory)
1961 wd = context->working_directory;
1962 else
1963 wd = "/";
1964
d35fbf6b 1965 if (params->apply_chroot) {
ee818b89 1966 if (!needs_mount_namespace && context->root_directory)
d35fbf6b 1967 if (chroot(context->root_directory) < 0) {
ff0af2a1 1968 *exit_status = EXIT_CHROOT;
d35fbf6b 1969 return -errno;
8aa75193
LP
1970 }
1971
5f5d8eab 1972 if (chdir(wd) < 0 &&
4c08c824 1973 !context->working_directory_missing_ok) {
ff0af2a1 1974 *exit_status = EXIT_CHDIR;
d35fbf6b
DM
1975 return -errno;
1976 }
1977 } else {
5f5d8eab 1978 const char *d;
8aa75193 1979
5f5d8eab 1980 d = strjoina(strempty(context->root_directory), "/", strempty(wd));
cf1d0302
LP
1981 if (chdir(d) < 0 &&
1982 !context->working_directory_missing_ok) {
ff0af2a1 1983 *exit_status = EXIT_CHDIR;
d35fbf6b
DM
1984 return -errno;
1985 }
1986 }
e66cf1a3 1987
9008e1ac 1988#ifdef HAVE_SELINUX
cf677fe6 1989 if (params->apply_permissions && mac_selinux_use() && params->selinux_context_net && socket_fd >= 0 && !command->privileged) {
ff0af2a1
LP
1990 r = mac_selinux_get_child_mls_label(socket_fd, command->path, context->selinux_context, &mac_selinux_context_net);
1991 if (r < 0) {
1992 *exit_status = EXIT_SELINUX_CONTEXT;
1993 return r;
9008e1ac
MS
1994 }
1995 }
1996#endif
1997
d35fbf6b
DM
1998 /* We repeat the fd closing here, to make sure that
1999 * nothing is leaked from the PAM modules. Note that
2000 * we are more aggressive this time since socket_fd
e44da745
DM
2001 * and the netns fds we don't need anymore. The custom
2002 * endpoint fd was needed to upload the policy and can
2003 * now be closed as well. */
ff0af2a1
LP
2004 r = close_all_fds(fds, n_fds);
2005 if (r >= 0)
2006 r = shift_fds(fds, n_fds);
2007 if (r >= 0)
2008 r = flags_fds(fds, n_fds, context->non_blocking);
2009 if (r < 0) {
2010 *exit_status = EXIT_FDS;
2011 return r;
d35fbf6b 2012 }
e66cf1a3 2013
cf677fe6 2014 if (params->apply_permissions && !command->privileged) {
e66cf1a3 2015
19c0b0b9
RC
2016 bool use_address_families = context->address_families_whitelist ||
2017 !set_isempty(context->address_families);
2018 bool use_syscall_filter = context->syscall_whitelist ||
2019 !set_isempty(context->syscall_filter) ||
2020 !set_isempty(context->syscall_archs);
755d4b67
IP
2021 int secure_bits = context->secure_bits;
2022
d35fbf6b 2023 for (i = 0; i < _RLIMIT_MAX; i++) {
03857c43 2024
d35fbf6b
DM
2025 if (!context->rlimit[i])
2026 continue;
2027
03857c43
LP
2028 r = setrlimit_closest(i, context->rlimit[i]);
2029 if (r < 0) {
ff0af2a1 2030 *exit_status = EXIT_LIMITS;
03857c43 2031 return r;
e66cf1a3
LP
2032 }
2033 }
2034
f4170c67
LP
2035 /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested. */
2036 if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
2037 if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
2038 *exit_status = EXIT_LIMITS;
2039 return -errno;
2040 }
2041 }
2042
a103496c
IP
2043 if (!cap_test_all(context->capability_bounding_set)) {
2044 r = capability_bounding_set_drop(context->capability_bounding_set, false);
ff0af2a1
LP
2045 if (r < 0) {
2046 *exit_status = EXIT_CAPABILITIES;
2047 return r;
3b8bddde 2048 }
4c2630eb 2049 }
3b8bddde 2050
755d4b67
IP
2051 /* This is done before enforce_user, but ambient set
2052 * does not survive over setresuid() if keep_caps is not set. */
2053 if (context->capability_ambient_set != 0) {
2054 r = capability_ambient_set_apply(context->capability_ambient_set, true);
2055 if (r < 0) {
2056 *exit_status = EXIT_CAPABILITIES;
2057 return r;
2058 }
755d4b67
IP
2059 }
2060
d35fbf6b 2061 if (context->user) {
ff0af2a1
LP
2062 r = enforce_user(context, uid);
2063 if (r < 0) {
2064 *exit_status = EXIT_USER;
2065 return r;
5b6319dc 2066 }
755d4b67
IP
2067 if (context->capability_ambient_set != 0) {
2068
2069 /* Fix the ambient capabilities after user change. */
2070 r = capability_ambient_set_apply(context->capability_ambient_set, false);
2071 if (r < 0) {
2072 *exit_status = EXIT_CAPABILITIES;
2073 return r;
2074 }
2075
2076 /* If we were asked to change user and ambient capabilities
2077 * were requested, we had to add keep-caps to the securebits
2078 * so that we would maintain the inherited capability set
2079 * through the setresuid(). Make sure that the bit is added
2080 * also to the context secure_bits so that we don't try to
2081 * drop the bit away next. */
2082
7f508f2c 2083 secure_bits |= 1<<SECURE_KEEP_CAPS;
755d4b67 2084 }
5b6319dc 2085 }
d35fbf6b
DM
2086
2087 /* PR_GET_SECUREBITS is not privileged, while
2088 * PR_SET_SECUREBITS is. So to suppress
2089 * potential EPERMs we'll try not to call
2090 * PR_SET_SECUREBITS unless necessary. */
755d4b67
IP
2091 if (prctl(PR_GET_SECUREBITS) != secure_bits)
2092 if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
ff0af2a1 2093 *exit_status = EXIT_SECUREBITS;
d35fbf6b 2094 return -errno;
ff01d048 2095 }
5b6319dc 2096
19c0b0b9 2097 if (context->no_new_privileges ||
f4170c67 2098 (!have_effective_cap(CAP_SYS_ADMIN) && (use_address_families || context->memory_deny_write_execute || context->restrict_realtime || use_syscall_filter)))
d35fbf6b 2099 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
ff0af2a1 2100 *exit_status = EXIT_NO_NEW_PRIVILEGES;
d35fbf6b
DM
2101 return -errno;
2102 }
2103
2104#ifdef HAVE_SECCOMP
19c0b0b9 2105 if (use_address_families) {
ff0af2a1
LP
2106 r = apply_address_families(context);
2107 if (r < 0) {
2108 *exit_status = EXIT_ADDRESS_FAMILIES;
2109 return r;
4c2630eb
MS
2110 }
2111 }
04aa0cb9 2112
f3e43635
TM
2113 if (context->memory_deny_write_execute) {
2114 r = apply_memory_deny_write_execute(context);
2115 if (r < 0) {
2116 *exit_status = EXIT_SECCOMP;
2117 return r;
2118 }
2119 }
f4170c67
LP
2120
2121 if (context->restrict_realtime) {
2122 r = apply_restrict_realtime(context);
2123 if (r < 0) {
2124 *exit_status = EXIT_SECCOMP;
2125 return r;
2126 }
2127 }
2128
19c0b0b9 2129 if (use_syscall_filter) {
ff0af2a1
LP
2130 r = apply_seccomp(context);
2131 if (r < 0) {
2132 *exit_status = EXIT_SECCOMP;
2133 return r;
81a2b7ce 2134 }
d35fbf6b
DM
2135 }
2136#endif
81a2b7ce 2137
d35fbf6b 2138#ifdef HAVE_SELINUX
6baa7db0 2139 if (mac_selinux_use()) {
9008e1ac 2140 char *exec_context = mac_selinux_context_net ?: context->selinux_context;
16115b0a 2141
9008e1ac 2142 if (exec_context) {
ff0af2a1
LP
2143 r = setexeccon(exec_context);
2144 if (r < 0) {
2145 *exit_status = EXIT_SELINUX_CONTEXT;
2146 return r;
16115b0a 2147 }
81a2b7ce 2148 }
81a2b7ce 2149 }
d35fbf6b 2150#endif
81a2b7ce 2151
d35fbf6b 2152#ifdef HAVE_APPARMOR
6baa7db0 2153 if (context->apparmor_profile && mac_apparmor_use()) {
ff0af2a1
LP
2154 r = aa_change_onexec(context->apparmor_profile);
2155 if (r < 0 && !context->apparmor_profile_ignore) {
2156 *exit_status = EXIT_APPARMOR_PROFILE;
5482192e 2157 return -errno;
d35fbf6b 2158 }
034c6ed7 2159 }
d35fbf6b
DM
2160#endif
2161 }
034c6ed7 2162
2065ca69 2163 final_argv = replace_env_argv(argv, accum_env);
d35fbf6b 2164 if (!final_argv) {
ff0af2a1 2165 *exit_status = EXIT_MEMORY;
d35fbf6b
DM
2166 return -ENOMEM;
2167 }
034c6ed7 2168
2065ca69 2169 accum_env = strv_env_clean(accum_env);
260abb78 2170
553d2243 2171 if (_unlikely_(log_get_max_level() >= LOG_DEBUG)) {
d35fbf6b 2172 _cleanup_free_ char *line;
81a2b7ce 2173
d35fbf6b
DM
2174 line = exec_command_line(final_argv);
2175 if (line) {
2176 log_open();
f2341e0a
LP
2177 log_struct(LOG_DEBUG,
2178 LOG_UNIT_ID(unit),
2179 "EXECUTABLE=%s", command->path,
2180 LOG_UNIT_MESSAGE(unit, "Executing: %s", line),
2181 NULL);
d35fbf6b
DM
2182 log_close();
2183 }
2184 }
dd305ec9 2185
2065ca69 2186 execve(command->path, final_argv, accum_env);
ff0af2a1 2187 *exit_status = EXIT_EXEC;
d35fbf6b
DM
2188 return -errno;
2189}
81a2b7ce 2190
f2341e0a
LP
2191int exec_spawn(Unit *unit,
2192 ExecCommand *command,
d35fbf6b
DM
2193 const ExecContext *context,
2194 const ExecParameters *params,
2195 ExecRuntime *runtime,
2196 pid_t *ret) {
8351ceae 2197
d35fbf6b
DM
2198 _cleanup_strv_free_ char **files_env = NULL;
2199 int *fds = NULL; unsigned n_fds = 0;
ff0af2a1
LP
2200 _cleanup_free_ char *line = NULL;
2201 int socket_fd, r;
2202 char **argv;
d35fbf6b 2203 pid_t pid;
8351ceae 2204
f2341e0a 2205 assert(unit);
d35fbf6b
DM
2206 assert(command);
2207 assert(context);
2208 assert(ret);
2209 assert(params);
2210 assert(params->fds || params->n_fds <= 0);
4298d0b5 2211
d35fbf6b
DM
2212 if (context->std_input == EXEC_INPUT_SOCKET ||
2213 context->std_output == EXEC_OUTPUT_SOCKET ||
2214 context->std_error == EXEC_OUTPUT_SOCKET) {
17df7223 2215
ff0af2a1 2216 if (params->n_fds != 1) {
f2341e0a 2217 log_unit_error(unit, "Got more than one socket.");
d35fbf6b 2218 return -EINVAL;
ff0af2a1 2219 }
eef65bf3 2220
d35fbf6b
DM
2221 socket_fd = params->fds[0];
2222 } else {
2223 socket_fd = -1;
2224 fds = params->fds;
2225 n_fds = params->n_fds;
2226 }
94f04347 2227
f2341e0a 2228 r = exec_context_load_environment(unit, context, &files_env);
ff0af2a1 2229 if (r < 0)
f2341e0a 2230 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
034c6ed7 2231
d35fbf6b 2232 argv = params->argv ?: command->argv;
d35fbf6b
DM
2233 line = exec_command_line(argv);
2234 if (!line)
2235 return log_oom();
fab56fc5 2236
f2341e0a
LP
2237 log_struct(LOG_DEBUG,
2238 LOG_UNIT_ID(unit),
2239 LOG_UNIT_MESSAGE(unit, "About to execute: %s", line),
2240 "EXECUTABLE=%s", command->path,
2241 NULL);
d35fbf6b
DM
2242 pid = fork();
2243 if (pid < 0)
74129a12 2244 return log_unit_error_errno(unit, errno, "Failed to fork: %m");
d35fbf6b
DM
2245
2246 if (pid == 0) {
ff0af2a1
LP
2247 int exit_status;
2248
f2341e0a
LP
2249 r = exec_child(unit,
2250 command,
ff0af2a1
LP
2251 context,
2252 params,
2253 runtime,
2254 argv,
2255 socket_fd,
2256 fds, n_fds,
2257 files_env,
2258 &exit_status);
2259 if (r < 0) {
4c2630eb 2260 log_open();
f2341e0a
LP
2261 log_struct_errno(LOG_ERR, r,
2262 LOG_MESSAGE_ID(SD_MESSAGE_SPAWN_FAILED),
2263 LOG_UNIT_ID(unit),
2264 LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
2265 exit_status_to_string(exit_status, EXIT_STATUS_SYSTEMD),
2266 command->path),
2267 "EXECUTABLE=%s", command->path,
2268 NULL);
4c2630eb
MS
2269 }
2270
ff0af2a1 2271 _exit(exit_status);
034c6ed7
LP
2272 }
2273
f2341e0a 2274 log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
23635a85 2275
80876c20
LP
2276 /* We add the new process to the cgroup both in the child (so
2277 * that we can be sure that no user code is ever executed
2278 * outside of the cgroup) and in the parent (so that we can be
2279 * sure that when we kill the cgroup the process will be
2280 * killed too). */
d35fbf6b 2281 if (params->cgroup_path)
dd305ec9 2282 (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, pid);
2da3263a 2283
b58b4116 2284 exec_status_start(&command->exec_status, pid);
9fb86720 2285
034c6ed7 2286 *ret = pid;
5cb5a6ff
LP
2287 return 0;
2288}
2289
034c6ed7
LP
2290void exec_context_init(ExecContext *c) {
2291 assert(c);
2292
4c12626c 2293 c->umask = 0022;
9eba9da4 2294 c->ioprio = IOPRIO_PRIO_VALUE(IOPRIO_CLASS_BE, 0);
94f04347 2295 c->cpu_sched_policy = SCHED_OTHER;
071830ff 2296 c->syslog_priority = LOG_DAEMON|LOG_INFO;
74922904 2297 c->syslog_level_prefix = true;
353e12c2 2298 c->ignore_sigpipe = true;
3a43da28 2299 c->timer_slack_nsec = NSEC_INFINITY;
050f7277 2300 c->personality = PERSONALITY_INVALID;
e66cf1a3 2301 c->runtime_directory_mode = 0755;
a103496c 2302 c->capability_bounding_set = CAP_ALL;
034c6ed7
LP
2303}
2304
613b411c 2305void exec_context_done(ExecContext *c) {
5cb5a6ff
LP
2306 unsigned l;
2307
2308 assert(c);
2309
6796073e
LP
2310 c->environment = strv_free(c->environment);
2311 c->environment_files = strv_free(c->environment_files);
b4c14404 2312 c->pass_environment = strv_free(c->pass_environment);
8c7be95e 2313
1f6b4113 2314 for (l = 0; l < ELEMENTSOF(c->rlimit); l++)
a1e58e8e 2315 c->rlimit[l] = mfree(c->rlimit[l]);
034c6ed7 2316
a1e58e8e
LP
2317 c->working_directory = mfree(c->working_directory);
2318 c->root_directory = mfree(c->root_directory);
2319 c->tty_path = mfree(c->tty_path);
2320 c->syslog_identifier = mfree(c->syslog_identifier);
2321 c->user = mfree(c->user);
2322 c->group = mfree(c->group);
034c6ed7 2323
6796073e 2324 c->supplementary_groups = strv_free(c->supplementary_groups);
94f04347 2325
a1e58e8e 2326 c->pam_name = mfree(c->pam_name);
5b6319dc 2327
6796073e
LP
2328 c->read_only_dirs = strv_free(c->read_only_dirs);
2329 c->read_write_dirs = strv_free(c->read_write_dirs);
2330 c->inaccessible_dirs = strv_free(c->inaccessible_dirs);
82c121a4
LP
2331
2332 if (c->cpuset)
2333 CPU_FREE(c->cpuset);
86a3475b 2334
a1e58e8e
LP
2335 c->utmp_id = mfree(c->utmp_id);
2336 c->selinux_context = mfree(c->selinux_context);
2337 c->apparmor_profile = mfree(c->apparmor_profile);
eef65bf3 2338
525d3cc7
LP
2339 c->syscall_filter = set_free(c->syscall_filter);
2340 c->syscall_archs = set_free(c->syscall_archs);
2341 c->address_families = set_free(c->address_families);
e66cf1a3 2342
6796073e 2343 c->runtime_directory = strv_free(c->runtime_directory);
e66cf1a3
LP
2344}
2345
2346int exec_context_destroy_runtime_directory(ExecContext *c, const char *runtime_prefix) {
2347 char **i;
2348
2349 assert(c);
2350
2351 if (!runtime_prefix)
2352 return 0;
2353
2354 STRV_FOREACH(i, c->runtime_directory) {
2355 _cleanup_free_ char *p;
2356
2357 p = strjoin(runtime_prefix, "/", *i, NULL);
2358 if (!p)
2359 return -ENOMEM;
2360
2361 /* We execute this synchronously, since we need to be
2362 * sure this is gone when we start the service
2363 * next. */
c6878637 2364 (void) rm_rf(p, REMOVE_ROOT);
e66cf1a3
LP
2365 }
2366
2367 return 0;
5cb5a6ff
LP
2368}
2369
43d0fcbd
LP
2370void exec_command_done(ExecCommand *c) {
2371 assert(c);
2372
a1e58e8e 2373 c->path = mfree(c->path);
43d0fcbd 2374
6796073e 2375 c->argv = strv_free(c->argv);
43d0fcbd
LP
2376}
2377
2378void exec_command_done_array(ExecCommand *c, unsigned n) {
2379 unsigned i;
2380
2381 for (i = 0; i < n; i++)
2382 exec_command_done(c+i);
2383}
2384
f1acf85a 2385ExecCommand* exec_command_free_list(ExecCommand *c) {
5cb5a6ff
LP
2386 ExecCommand *i;
2387
2388 while ((i = c)) {
71fda00f 2389 LIST_REMOVE(command, c, i);
43d0fcbd 2390 exec_command_done(i);
5cb5a6ff
LP
2391 free(i);
2392 }
f1acf85a
ZJS
2393
2394 return NULL;
5cb5a6ff
LP
2395}
2396
034c6ed7
LP
2397void exec_command_free_array(ExecCommand **c, unsigned n) {
2398 unsigned i;
2399
f1acf85a
ZJS
2400 for (i = 0; i < n; i++)
2401 c[i] = exec_command_free_list(c[i]);
034c6ed7
LP
2402}
2403
039f0e70 2404typedef struct InvalidEnvInfo {
f2341e0a 2405 Unit *unit;
039f0e70
LP
2406 const char *path;
2407} InvalidEnvInfo;
2408
2409static void invalid_env(const char *p, void *userdata) {
2410 InvalidEnvInfo *info = userdata;
2411
f2341e0a 2412 log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
039f0e70
LP
2413}
2414
f2341e0a 2415int exec_context_load_environment(Unit *unit, const ExecContext *c, char ***l) {
8c7be95e
LP
2416 char **i, **r = NULL;
2417
2418 assert(c);
2419 assert(l);
2420
2421 STRV_FOREACH(i, c->environment_files) {
2422 char *fn;
2423 int k;
2424 bool ignore = false;
2425 char **p;
7fd1b19b 2426 _cleanup_globfree_ glob_t pglob = {};
2bef10ab 2427 int count, n;
8c7be95e
LP
2428
2429 fn = *i;
2430
2431 if (fn[0] == '-') {
2432 ignore = true;
313cefa1 2433 fn++;
8c7be95e
LP
2434 }
2435
2436 if (!path_is_absolute(fn)) {
8c7be95e
LP
2437 if (ignore)
2438 continue;
2439
2440 strv_free(r);
2441 return -EINVAL;
2442 }
2443
2bef10ab 2444 /* Filename supports globbing, take all matching files */
2bef10ab
PL
2445 errno = 0;
2446 if (glob(fn, 0, NULL, &pglob) != 0) {
2bef10ab
PL
2447 if (ignore)
2448 continue;
8c7be95e 2449
2bef10ab 2450 strv_free(r);
f5e5c28f 2451 return errno > 0 ? -errno : -EINVAL;
2bef10ab
PL
2452 }
2453 count = pglob.gl_pathc;
2454 if (count == 0) {
8c7be95e
LP
2455 if (ignore)
2456 continue;
2457
2458 strv_free(r);
2bef10ab 2459 return -EINVAL;
8c7be95e 2460 }
2bef10ab 2461 for (n = 0; n < count; n++) {
717603e3 2462 k = load_env_file(NULL, pglob.gl_pathv[n], NULL, &p);
2bef10ab
PL
2463 if (k < 0) {
2464 if (ignore)
2465 continue;
8c7be95e 2466
2bef10ab 2467 strv_free(r);
2bef10ab 2468 return k;
e9c1ea9d 2469 }
ebc05a09 2470 /* Log invalid environment variables with filename */
039f0e70
LP
2471 if (p) {
2472 InvalidEnvInfo info = {
f2341e0a 2473 .unit = unit,
039f0e70
LP
2474 .path = pglob.gl_pathv[n]
2475 };
2476
2477 p = strv_env_clean_with_callback(p, invalid_env, &info);
2478 }
8c7be95e 2479
2bef10ab
PL
2480 if (r == NULL)
2481 r = p;
2482 else {
2483 char **m;
8c7be95e 2484
2bef10ab
PL
2485 m = strv_env_merge(2, r, p);
2486 strv_free(r);
2487 strv_free(p);
c84a9488 2488 if (!m)
2bef10ab 2489 return -ENOMEM;
2bef10ab
PL
2490
2491 r = m;
2492 }
8c7be95e
LP
2493 }
2494 }
2495
2496 *l = r;
2497
2498 return 0;
2499}
2500
6ac8fdc9 2501static bool tty_may_match_dev_console(const char *tty) {
e1d75803 2502 _cleanup_free_ char *active = NULL;
7d6884b6 2503 char *console;
6ac8fdc9 2504
1e22b5cd
LP
2505 if (!tty)
2506 return true;
2507
6ac8fdc9
MS
2508 if (startswith(tty, "/dev/"))
2509 tty += 5;
2510
2511 /* trivial identity? */
2512 if (streq(tty, "console"))
2513 return true;
2514
2515 console = resolve_dev_console(&active);
2516 /* if we could not resolve, assume it may */
2517 if (!console)
2518 return true;
2519
2520 /* "tty0" means the active VC, so it may be the same sometimes */
e1d75803 2521 return streq(console, tty) || (streq(console, "tty0") && tty_is_vc(tty));
6ac8fdc9
MS
2522}
2523
2524bool exec_context_may_touch_console(ExecContext *ec) {
1e22b5cd
LP
2525
2526 return (ec->tty_reset ||
2527 ec->tty_vhangup ||
2528 ec->tty_vt_disallocate ||
6ac8fdc9
MS
2529 is_terminal_input(ec->std_input) ||
2530 is_terminal_output(ec->std_output) ||
2531 is_terminal_output(ec->std_error)) &&
1e22b5cd 2532 tty_may_match_dev_console(exec_context_tty_path(ec));
6ac8fdc9
MS
2533}
2534
15ae422b
LP
2535static void strv_fprintf(FILE *f, char **l) {
2536 char **g;
2537
2538 assert(f);
2539
2540 STRV_FOREACH(g, l)
2541 fprintf(f, " %s", *g);
2542}
2543
5cb5a6ff 2544void exec_context_dump(ExecContext *c, FILE* f, const char *prefix) {
c2bbd90b 2545 char **e, **d;
94f04347 2546 unsigned i;
9eba9da4 2547
5cb5a6ff
LP
2548 assert(c);
2549 assert(f);
2550
4ad49000 2551 prefix = strempty(prefix);
5cb5a6ff
LP
2552
2553 fprintf(f,
94f04347
LP
2554 "%sUMask: %04o\n"
2555 "%sWorkingDirectory: %s\n"
451a074f 2556 "%sRootDirectory: %s\n"
15ae422b 2557 "%sNonBlocking: %s\n"
64747e2d 2558 "%sPrivateTmp: %s\n"
4819ff03 2559 "%sPrivateNetwork: %s\n"
7f112f50 2560 "%sPrivateDevices: %s\n"
1b8689f9
LP
2561 "%sProtectHome: %s\n"
2562 "%sProtectSystem: %s\n"
f3e43635 2563 "%sIgnoreSIGPIPE: %s\n"
f4170c67
LP
2564 "%sMemoryDenyWriteExecute: %s\n"
2565 "%sRestrictRealtime: %s\n",
5cb5a6ff 2566 prefix, c->umask,
9eba9da4 2567 prefix, c->working_directory ? c->working_directory : "/",
451a074f 2568 prefix, c->root_directory ? c->root_directory : "/",
15ae422b 2569 prefix, yes_no(c->non_blocking),
64747e2d 2570 prefix, yes_no(c->private_tmp),
4819ff03 2571 prefix, yes_no(c->private_network),
7f112f50 2572 prefix, yes_no(c->private_devices),
1b8689f9
LP
2573 prefix, protect_home_to_string(c->protect_home),
2574 prefix, protect_system_to_string(c->protect_system),
f3e43635 2575 prefix, yes_no(c->ignore_sigpipe),
f4170c67
LP
2576 prefix, yes_no(c->memory_deny_write_execute),
2577 prefix, yes_no(c->restrict_realtime));
fb33a393 2578
8c7be95e
LP
2579 STRV_FOREACH(e, c->environment)
2580 fprintf(f, "%sEnvironment: %s\n", prefix, *e);
2581
2582 STRV_FOREACH(e, c->environment_files)
2583 fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);
94f04347 2584
b4c14404
FB
2585 STRV_FOREACH(e, c->pass_environment)
2586 fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);
2587
c2bbd90b
EV
2588 fprintf(f, "%sRuntimeDirectoryMode: %04o\n", prefix, c->runtime_directory_mode);
2589
2590 STRV_FOREACH(d, c->runtime_directory)
2591 fprintf(f, "%sRuntimeDirectory: %s\n", prefix, *d);
2592
fb33a393
LP
2593 if (c->nice_set)
2594 fprintf(f,
2595 "%sNice: %i\n",
2596 prefix, c->nice);
2597
dd6c17b1 2598 if (c->oom_score_adjust_set)
fb33a393 2599 fprintf(f,
dd6c17b1
LP
2600 "%sOOMScoreAdjust: %i\n",
2601 prefix, c->oom_score_adjust);
9eba9da4 2602
94f04347 2603 for (i = 0; i < RLIM_NLIMITS; i++)
3c11da9d
EV
2604 if (c->rlimit[i]) {
2605 fprintf(f, "%s%s: " RLIM_FMT "\n",
2606 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
2607 fprintf(f, "%s%sSoft: " RLIM_FMT "\n",
2608 prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
2609 }
94f04347 2610
f8b69d1d 2611 if (c->ioprio_set) {
1756a011 2612 _cleanup_free_ char *class_str = NULL;
f8b69d1d 2613
1756a011 2614 ioprio_class_to_string_alloc(IOPRIO_PRIO_CLASS(c->ioprio), &class_str);
9eba9da4
LP
2615 fprintf(f,
2616 "%sIOSchedulingClass: %s\n"
2617 "%sIOPriority: %i\n",
f8b69d1d 2618 prefix, strna(class_str),
9eba9da4 2619 prefix, (int) IOPRIO_PRIO_DATA(c->ioprio));
f8b69d1d 2620 }
94f04347 2621
f8b69d1d 2622 if (c->cpu_sched_set) {
1756a011 2623 _cleanup_free_ char *policy_str = NULL;
f8b69d1d 2624
1756a011 2625 sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
94f04347
LP
2626 fprintf(f,
2627 "%sCPUSchedulingPolicy: %s\n"
38b48754
LP
2628 "%sCPUSchedulingPriority: %i\n"
2629 "%sCPUSchedulingResetOnFork: %s\n",
f8b69d1d 2630 prefix, strna(policy_str),
38b48754
LP
2631 prefix, c->cpu_sched_priority,
2632 prefix, yes_no(c->cpu_sched_reset_on_fork));
b929bf04 2633 }
94f04347 2634
82c121a4 2635 if (c->cpuset) {
94f04347 2636 fprintf(f, "%sCPUAffinity:", prefix);
82c121a4
LP
2637 for (i = 0; i < c->cpuset_ncpus; i++)
2638 if (CPU_ISSET_S(i, CPU_ALLOC_SIZE(c->cpuset_ncpus), c->cpuset))
43a99a7a 2639 fprintf(f, " %u", i);
94f04347
LP
2640 fputs("\n", f);
2641 }
2642
3a43da28 2643 if (c->timer_slack_nsec != NSEC_INFINITY)
ccd06097 2644 fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);
94f04347
LP
2645
2646 fprintf(f,
80876c20
LP
2647 "%sStandardInput: %s\n"
2648 "%sStandardOutput: %s\n"
2649 "%sStandardError: %s\n",
2650 prefix, exec_input_to_string(c->std_input),
2651 prefix, exec_output_to_string(c->std_output),
2652 prefix, exec_output_to_string(c->std_error));
2653
2654 if (c->tty_path)
2655 fprintf(f,
6ea832a2
LP
2656 "%sTTYPath: %s\n"
2657 "%sTTYReset: %s\n"
2658 "%sTTYVHangup: %s\n"
2659 "%sTTYVTDisallocate: %s\n",
2660 prefix, c->tty_path,
2661 prefix, yes_no(c->tty_reset),
2662 prefix, yes_no(c->tty_vhangup),
2663 prefix, yes_no(c->tty_vt_disallocate));
94f04347 2664
5ce70e5b
ZJS
2665 if (c->std_output == EXEC_OUTPUT_SYSLOG ||
2666 c->std_output == EXEC_OUTPUT_KMSG ||
2667 c->std_output == EXEC_OUTPUT_JOURNAL ||
2668 c->std_output == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
2669 c->std_output == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
2670 c->std_output == EXEC_OUTPUT_JOURNAL_AND_CONSOLE ||
2671 c->std_error == EXEC_OUTPUT_SYSLOG ||
2672 c->std_error == EXEC_OUTPUT_KMSG ||
2673 c->std_error == EXEC_OUTPUT_JOURNAL ||
2674 c->std_error == EXEC_OUTPUT_SYSLOG_AND_CONSOLE ||
2675 c->std_error == EXEC_OUTPUT_KMSG_AND_CONSOLE ||
2676 c->std_error == EXEC_OUTPUT_JOURNAL_AND_CONSOLE) {
f8b69d1d 2677
5ce70e5b 2678 _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;
f8b69d1d 2679
5ce70e5b
ZJS
2680 log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
2681 log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
f8b69d1d 2682
94f04347
LP
2683 fprintf(f,
2684 "%sSyslogFacility: %s\n"
2685 "%sSyslogLevel: %s\n",
f8b69d1d
MS
2686 prefix, strna(fac_str),
2687 prefix, strna(lvl_str));
f8b69d1d 2688 }
94f04347 2689
94f04347
LP
2690 if (c->secure_bits)
2691 fprintf(f, "%sSecure Bits:%s%s%s%s%s%s\n",
2692 prefix,
cbb21cca
ZJS
2693 (c->secure_bits & 1<<SECURE_KEEP_CAPS) ? " keep-caps" : "",
2694 (c->secure_bits & 1<<SECURE_KEEP_CAPS_LOCKED) ? " keep-caps-locked" : "",
2695 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP) ? " no-setuid-fixup" : "",
2696 (c->secure_bits & 1<<SECURE_NO_SETUID_FIXUP_LOCKED) ? " no-setuid-fixup-locked" : "",
2697 (c->secure_bits & 1<<SECURE_NOROOT) ? " noroot" : "",
2698 (c->secure_bits & 1<<SECURE_NOROOT_LOCKED) ? "noroot-locked" : "");
94f04347 2699
a103496c 2700 if (c->capability_bounding_set != CAP_ALL) {
ae556c21 2701 unsigned long l;
260abb78 2702 fprintf(f, "%sCapabilityBoundingSet:", prefix);
94f04347 2703
64685e0c 2704 for (l = 0; l <= cap_last_cap(); l++)
a103496c 2705 if (c->capability_bounding_set & (UINT64_C(1) << l))
2822da4f 2706 fprintf(f, " %s", strna(capability_to_name(l)));
94f04347
LP
2707
2708 fputs("\n", f);
755d4b67
IP
2709 }
2710
2711 if (c->capability_ambient_set != 0) {
2712 unsigned long l;
2713 fprintf(f, "%sAmbientCapabilities:", prefix);
2714
2715 for (l = 0; l <= cap_last_cap(); l++)
2716 if (c->capability_ambient_set & (UINT64_C(1) << l))
2717 fprintf(f, " %s", strna(capability_to_name(l)));
2718
2719 fputs("\n", f);
94f04347
LP
2720 }
2721
2722 if (c->user)
f2d3769a 2723 fprintf(f, "%sUser: %s\n", prefix, c->user);
94f04347 2724 if (c->group)
f2d3769a 2725 fprintf(f, "%sGroup: %s\n", prefix, c->group);
94f04347 2726
15ae422b 2727 if (strv_length(c->supplementary_groups) > 0) {
94f04347 2728 fprintf(f, "%sSupplementaryGroups:", prefix);
15ae422b
LP
2729 strv_fprintf(f, c->supplementary_groups);
2730 fputs("\n", f);
2731 }
94f04347 2732
5b6319dc 2733 if (c->pam_name)
f2d3769a 2734 fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);
5b6319dc 2735
15ae422b
LP
2736 if (strv_length(c->read_write_dirs) > 0) {
2737 fprintf(f, "%sReadWriteDirs:", prefix);
2738 strv_fprintf(f, c->read_write_dirs);
2739 fputs("\n", f);
2740 }
2741
2742 if (strv_length(c->read_only_dirs) > 0) {
2743 fprintf(f, "%sReadOnlyDirs:", prefix);
2744 strv_fprintf(f, c->read_only_dirs);
2745 fputs("\n", f);
2746 }
94f04347 2747
15ae422b
LP
2748 if (strv_length(c->inaccessible_dirs) > 0) {
2749 fprintf(f, "%sInaccessibleDirs:", prefix);
2750 strv_fprintf(f, c->inaccessible_dirs);
94f04347
LP
2751 fputs("\n", f);
2752 }
2e22afe9 2753
169c1bda
LP
2754 if (c->utmp_id)
2755 fprintf(f,
2756 "%sUtmpIdentifier: %s\n",
2757 prefix, c->utmp_id);
7b52a628
MS
2758
2759 if (c->selinux_context)
2760 fprintf(f,
5f8640fb
LP
2761 "%sSELinuxContext: %s%s\n",
2762 prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);
17df7223 2763
050f7277 2764 if (c->personality != PERSONALITY_INVALID)
ac45f971
LP
2765 fprintf(f,
2766 "%sPersonality: %s\n",
2767 prefix, strna(personality_to_string(c->personality)));
2768
17df7223 2769 if (c->syscall_filter) {
351a19b1 2770#ifdef HAVE_SECCOMP
17df7223
LP
2771 Iterator j;
2772 void *id;
2773 bool first = true;
351a19b1 2774#endif
17df7223
LP
2775
2776 fprintf(f,
57183d11 2777 "%sSystemCallFilter: ",
17df7223
LP
2778 prefix);
2779
2780 if (!c->syscall_whitelist)
2781 fputc('~', f);
2782
351a19b1 2783#ifdef HAVE_SECCOMP
17df7223
LP
2784 SET_FOREACH(id, c->syscall_filter, j) {
2785 _cleanup_free_ char *name = NULL;
2786
2787 if (first)
2788 first = false;
2789 else
2790 fputc(' ', f);
2791
57183d11 2792 name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
17df7223
LP
2793 fputs(strna(name), f);
2794 }
351a19b1 2795#endif
17df7223
LP
2796
2797 fputc('\n', f);
2798 }
2799
57183d11
LP
2800 if (c->syscall_archs) {
2801#ifdef HAVE_SECCOMP
2802 Iterator j;
2803 void *id;
2804#endif
2805
2806 fprintf(f,
2807 "%sSystemCallArchitectures:",
2808 prefix);
2809
2810#ifdef HAVE_SECCOMP
2811 SET_FOREACH(id, c->syscall_archs, j)
2812 fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
2813#endif
2814 fputc('\n', f);
2815 }
2816
b3267152 2817 if (c->syscall_errno > 0)
17df7223
LP
2818 fprintf(f,
2819 "%sSystemCallErrorNumber: %s\n",
2820 prefix, strna(errno_to_name(c->syscall_errno)));
eef65bf3
MS
2821
2822 if (c->apparmor_profile)
2823 fprintf(f,
2824 "%sAppArmorProfile: %s%s\n",
2825 prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);
5cb5a6ff
LP
2826}
2827
a931ad47
LP
2828bool exec_context_maintains_privileges(ExecContext *c) {
2829 assert(c);
2830
2831 /* Returns true if the process forked off would run run under
2832 * an unchanged UID or as root. */
2833
2834 if (!c->user)
2835 return true;
2836
2837 if (streq(c->user, "root") || streq(c->user, "0"))
2838 return true;
2839
2840 return false;
2841}
2842
b58b4116 2843void exec_status_start(ExecStatus *s, pid_t pid) {
034c6ed7 2844 assert(s);
5cb5a6ff 2845
b58b4116
LP
2846 zero(*s);
2847 s->pid = pid;
2848 dual_timestamp_get(&s->start_timestamp);
2849}
2850
6ea832a2 2851void exec_status_exit(ExecStatus *s, ExecContext *context, pid_t pid, int code, int status) {
b58b4116
LP
2852 assert(s);
2853
0b1f4ae6 2854 if (s->pid && s->pid != pid)
b58b4116
LP
2855 zero(*s);
2856
034c6ed7 2857 s->pid = pid;
63983207 2858 dual_timestamp_get(&s->exit_timestamp);
9fb86720 2859
034c6ed7
LP
2860 s->code = code;
2861 s->status = status;
169c1bda 2862
6ea832a2
LP
2863 if (context) {
2864 if (context->utmp_id)
2865 utmp_put_dead_process(context->utmp_id, pid, code, status);
2866
1e22b5cd 2867 exec_context_tty_reset(context, NULL);
6ea832a2 2868 }
9fb86720
LP
2869}
2870
2871void exec_status_dump(ExecStatus *s, FILE *f, const char *prefix) {
2872 char buf[FORMAT_TIMESTAMP_MAX];
2873
2874 assert(s);
2875 assert(f);
2876
9fb86720
LP
2877 if (s->pid <= 0)
2878 return;
2879
4c940960
LP
2880 prefix = strempty(prefix);
2881
9fb86720 2882 fprintf(f,
ccd06097
ZJS
2883 "%sPID: "PID_FMT"\n",
2884 prefix, s->pid);
9fb86720 2885
63983207 2886 if (s->start_timestamp.realtime > 0)
9fb86720
LP
2887 fprintf(f,
2888 "%sStart Timestamp: %s\n",
63983207 2889 prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime));
9fb86720 2890
63983207 2891 if (s->exit_timestamp.realtime > 0)
9fb86720
LP
2892 fprintf(f,
2893 "%sExit Timestamp: %s\n"
2894 "%sExit Code: %s\n"
2895 "%sExit Status: %i\n",
63983207 2896 prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime),
9fb86720
LP
2897 prefix, sigchld_code_to_string(s->code),
2898 prefix, s->status);
5cb5a6ff 2899}
44d8db9e 2900
9e2f7c11 2901char *exec_command_line(char **argv) {
44d8db9e
LP
2902 size_t k;
2903 char *n, *p, **a;
2904 bool first = true;
2905
9e2f7c11 2906 assert(argv);
44d8db9e 2907
9164977d 2908 k = 1;
9e2f7c11 2909 STRV_FOREACH(a, argv)
44d8db9e
LP
2910 k += strlen(*a)+3;
2911
2912 if (!(n = new(char, k)))
2913 return NULL;
2914
2915 p = n;
9e2f7c11 2916 STRV_FOREACH(a, argv) {
44d8db9e
LP
2917
2918 if (!first)
2919 *(p++) = ' ';
2920 else
2921 first = false;
2922
2923 if (strpbrk(*a, WHITESPACE)) {
2924 *(p++) = '\'';
2925 p = stpcpy(p, *a);
2926 *(p++) = '\'';
2927 } else
2928 p = stpcpy(p, *a);
2929
2930 }
2931
9164977d
LP
2932 *p = 0;
2933
44d8db9e
LP
2934 /* FIXME: this doesn't really handle arguments that have
2935 * spaces and ticks in them */
2936
2937 return n;
2938}
2939
2940void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
e1d75803 2941 _cleanup_free_ char *cmd = NULL;
4c940960 2942 const char *prefix2;
44d8db9e
LP
2943
2944 assert(c);
2945 assert(f);
2946
4c940960 2947 prefix = strempty(prefix);
63c372cb 2948 prefix2 = strjoina(prefix, "\t");
44d8db9e 2949
9e2f7c11 2950 cmd = exec_command_line(c->argv);
44d8db9e
LP
2951 fprintf(f,
2952 "%sCommand Line: %s\n",
2953 prefix, cmd ? cmd : strerror(ENOMEM));
2954
9fb86720 2955 exec_status_dump(&c->exec_status, f, prefix2);
44d8db9e
LP
2956}
2957
2958void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
2959 assert(f);
2960
4c940960 2961 prefix = strempty(prefix);
44d8db9e
LP
2962
2963 LIST_FOREACH(command, c, c)
2964 exec_command_dump(c, f, prefix);
2965}
94f04347 2966
a6a80b4f
LP
2967void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
2968 ExecCommand *end;
2969
2970 assert(l);
2971 assert(e);
2972
2973 if (*l) {
35b8ca3a 2974 /* It's kind of important, that we keep the order here */
71fda00f
LP
2975 LIST_FIND_TAIL(command, *l, end);
2976 LIST_INSERT_AFTER(command, *l, end, e);
a6a80b4f
LP
2977 } else
2978 *l = e;
2979}
2980
26fd040d
LP
2981int exec_command_set(ExecCommand *c, const char *path, ...) {
2982 va_list ap;
2983 char **l, *p;
2984
2985 assert(c);
2986 assert(path);
2987
2988 va_start(ap, path);
2989 l = strv_new_ap(path, ap);
2990 va_end(ap);
2991
2992 if (!l)
2993 return -ENOMEM;
2994
250a918d
LP
2995 p = strdup(path);
2996 if (!p) {
26fd040d
LP
2997 strv_free(l);
2998 return -ENOMEM;
2999 }
3000
3001 free(c->path);
3002 c->path = p;
3003
3004 strv_free(c->argv);
3005 c->argv = l;
3006
3007 return 0;
3008}
3009
86b23b07 3010int exec_command_append(ExecCommand *c, const char *path, ...) {
e63ff941 3011 _cleanup_strv_free_ char **l = NULL;
86b23b07 3012 va_list ap;
86b23b07
JS
3013 int r;
3014
3015 assert(c);
3016 assert(path);
3017
3018 va_start(ap, path);
3019 l = strv_new_ap(path, ap);
3020 va_end(ap);
3021
3022 if (!l)
3023 return -ENOMEM;
3024
e287086b 3025 r = strv_extend_strv(&c->argv, l, false);
e63ff941 3026 if (r < 0)
86b23b07 3027 return r;
86b23b07
JS
3028
3029 return 0;
3030}
3031
3032
613b411c
LP
3033static int exec_runtime_allocate(ExecRuntime **rt) {
3034
3035 if (*rt)
3036 return 0;
3037
3038 *rt = new0(ExecRuntime, 1);
f146f5e1 3039 if (!*rt)
613b411c
LP
3040 return -ENOMEM;
3041
3042 (*rt)->n_ref = 1;
3043 (*rt)->netns_storage_socket[0] = (*rt)->netns_storage_socket[1] = -1;
3044
3045 return 0;
3046}
3047
3048int exec_runtime_make(ExecRuntime **rt, ExecContext *c, const char *id) {
3049 int r;
3050
3051 assert(rt);
3052 assert(c);
3053 assert(id);
3054
3055 if (*rt)
3056 return 1;
3057
3058 if (!c->private_network && !c->private_tmp)
3059 return 0;
3060
3061 r = exec_runtime_allocate(rt);
3062 if (r < 0)
3063 return r;
3064
3065 if (c->private_network && (*rt)->netns_storage_socket[0] < 0) {
3066 if (socketpair(AF_UNIX, SOCK_DGRAM, 0, (*rt)->netns_storage_socket) < 0)
3067 return -errno;
3068 }
3069
3070 if (c->private_tmp && !(*rt)->tmp_dir) {
3071 r = setup_tmp_dirs(id, &(*rt)->tmp_dir, &(*rt)->var_tmp_dir);
3072 if (r < 0)
3073 return r;
3074 }
3075
3076 return 1;
3077}
3078
3079ExecRuntime *exec_runtime_ref(ExecRuntime *r) {
3080 assert(r);
3081 assert(r->n_ref > 0);
3082
3083 r->n_ref++;
3084 return r;
3085}
3086
3087ExecRuntime *exec_runtime_unref(ExecRuntime *r) {
3088
3089 if (!r)
3090 return NULL;
3091
3092 assert(r->n_ref > 0);
3093
3094 r->n_ref--;
f2341e0a
LP
3095 if (r->n_ref > 0)
3096 return NULL;
3097
3098 free(r->tmp_dir);
3099 free(r->var_tmp_dir);
3100 safe_close_pair(r->netns_storage_socket);
3101 free(r);
613b411c
LP
3102
3103 return NULL;
3104}
3105
f2341e0a 3106int exec_runtime_serialize(Unit *u, ExecRuntime *rt, FILE *f, FDSet *fds) {
613b411c
LP
3107 assert(u);
3108 assert(f);
3109 assert(fds);
3110
3111 if (!rt)
3112 return 0;
3113
3114 if (rt->tmp_dir)
3115 unit_serialize_item(u, f, "tmp-dir", rt->tmp_dir);
3116
3117 if (rt->var_tmp_dir)
3118 unit_serialize_item(u, f, "var-tmp-dir", rt->var_tmp_dir);
3119
3120 if (rt->netns_storage_socket[0] >= 0) {
3121 int copy;
3122
3123 copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
3124 if (copy < 0)
3125 return copy;
3126
3127 unit_serialize_item_format(u, f, "netns-socket-0", "%i", copy);
3128 }
3129
3130 if (rt->netns_storage_socket[1] >= 0) {
3131 int copy;
3132
3133 copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
3134 if (copy < 0)
3135 return copy;
3136
3137 unit_serialize_item_format(u, f, "netns-socket-1", "%i", copy);
3138 }
3139
3140 return 0;
3141}
3142
f2341e0a 3143int exec_runtime_deserialize_item(Unit *u, ExecRuntime **rt, const char *key, const char *value, FDSet *fds) {
613b411c
LP
3144 int r;
3145
3146 assert(rt);
3147 assert(key);
3148 assert(value);
3149
3150 if (streq(key, "tmp-dir")) {
3151 char *copy;
3152
3153 r = exec_runtime_allocate(rt);
3154 if (r < 0)
f2341e0a 3155 return log_oom();
613b411c
LP
3156
3157 copy = strdup(value);
3158 if (!copy)
3159 return log_oom();
3160
3161 free((*rt)->tmp_dir);
3162 (*rt)->tmp_dir = copy;
3163
3164 } else if (streq(key, "var-tmp-dir")) {
3165 char *copy;
3166
3167 r = exec_runtime_allocate(rt);
3168 if (r < 0)
f2341e0a 3169 return log_oom();
613b411c
LP
3170
3171 copy = strdup(value);
3172 if (!copy)
3173 return log_oom();
3174
3175 free((*rt)->var_tmp_dir);
3176 (*rt)->var_tmp_dir = copy;
3177
3178 } else if (streq(key, "netns-socket-0")) {
3179 int fd;
3180
3181 r = exec_runtime_allocate(rt);
3182 if (r < 0)
f2341e0a 3183 return log_oom();
613b411c
LP
3184
3185 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3186 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3187 else {
03e334a1 3188 safe_close((*rt)->netns_storage_socket[0]);
613b411c
LP
3189 (*rt)->netns_storage_socket[0] = fdset_remove(fds, fd);
3190 }
3191 } else if (streq(key, "netns-socket-1")) {
3192 int fd;
3193
3194 r = exec_runtime_allocate(rt);
3195 if (r < 0)
f2341e0a 3196 return log_oom();
613b411c
LP
3197
3198 if (safe_atoi(value, &fd) < 0 || !fdset_contains(fds, fd))
f2341e0a 3199 log_unit_debug(u, "Failed to parse netns socket value: %s", value);
613b411c 3200 else {
03e334a1 3201 safe_close((*rt)->netns_storage_socket[1]);
613b411c
LP
3202 (*rt)->netns_storage_socket[1] = fdset_remove(fds, fd);
3203 }
3204 } else
3205 return 0;
3206
3207 return 1;
3208}
3209
3210static void *remove_tmpdir_thread(void *p) {
3211 _cleanup_free_ char *path = p;
3212
c6878637 3213 (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
613b411c
LP
3214 return NULL;
3215}
3216
3217void exec_runtime_destroy(ExecRuntime *rt) {
98b47d54
LP
3218 int r;
3219
613b411c
LP
3220 if (!rt)
3221 return;
3222
3223 /* If there are multiple users of this, let's leave the stuff around */
3224 if (rt->n_ref > 1)
3225 return;
3226
3227 if (rt->tmp_dir) {
3228 log_debug("Spawning thread to nuke %s", rt->tmp_dir);
98b47d54
LP
3229
3230 r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
3231 if (r < 0) {
da927ba9 3232 log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
98b47d54
LP
3233 free(rt->tmp_dir);
3234 }
3235
613b411c
LP
3236 rt->tmp_dir = NULL;
3237 }
3238
3239 if (rt->var_tmp_dir) {
3240 log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);
98b47d54
LP
3241
3242 r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
3243 if (r < 0) {
da927ba9 3244 log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
98b47d54
LP
3245 free(rt->var_tmp_dir);
3246 }
3247
613b411c
LP
3248 rt->var_tmp_dir = NULL;
3249 }
3250
3d94f76c 3251 safe_close_pair(rt->netns_storage_socket);
613b411c
LP
3252}
3253
80876c20
LP
3254static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
3255 [EXEC_INPUT_NULL] = "null",
3256 [EXEC_INPUT_TTY] = "tty",
3257 [EXEC_INPUT_TTY_FORCE] = "tty-force",
4f2d528d
LP
3258 [EXEC_INPUT_TTY_FAIL] = "tty-fail",
3259 [EXEC_INPUT_SOCKET] = "socket"
80876c20
LP
3260};
3261
8a0867d6
LP
3262DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);
3263
94f04347 3264static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
80876c20 3265 [EXEC_OUTPUT_INHERIT] = "inherit",
94f04347 3266 [EXEC_OUTPUT_NULL] = "null",
80876c20 3267 [EXEC_OUTPUT_TTY] = "tty",
94f04347 3268 [EXEC_OUTPUT_SYSLOG] = "syslog",
28dbc1e8 3269 [EXEC_OUTPUT_SYSLOG_AND_CONSOLE] = "syslog+console",
9a6bca7a 3270 [EXEC_OUTPUT_KMSG] = "kmsg",
28dbc1e8 3271 [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
706343f4
LP
3272 [EXEC_OUTPUT_JOURNAL] = "journal",
3273 [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
4f2d528d 3274 [EXEC_OUTPUT_SOCKET] = "socket"
94f04347
LP
3275};
3276
3277DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);
023a4f67
LP
3278
3279static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
3280 [EXEC_UTMP_INIT] = "init",
3281 [EXEC_UTMP_LOGIN] = "login",
3282 [EXEC_UTMP_USER] = "user",
3283};
3284
3285DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);