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