]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
mount-tool: return 0 instead of NULL in the acquire_description() (#4009)
[thirdparty/systemd.git] / src / core / main.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
60918275 20#include <errno.h>
3dfc9763 21#include <fcntl.h>
f170852a 22#include <getopt.h>
97c4f35c 23#include <signal.h>
3dfc9763
LP
24#include <stdio.h>
25#include <string.h>
664f88a7 26#include <sys/mount.h>
3dfc9763 27#include <sys/prctl.h>
b9e74c39 28#include <sys/reboot.h>
3dfc9763
LP
29#include <sys/stat.h>
30#include <unistd.h>
b64a3d86
LP
31#ifdef HAVE_SECCOMP
32#include <seccomp.h>
33#endif
3dfc9763
LP
34#ifdef HAVE_VALGRIND_VALGRIND_H
35#include <valgrind/valgrind.h>
36#endif
54b434b1 37
718db961 38#include "sd-bus.h"
cf0fbc49 39#include "sd-daemon.h"
3dfc9763 40
b5efdb8a 41#include "alloc-util.h"
d9d93745 42#include "architecture.h"
3dfc9763
LP
43#include "build.h"
44#include "bus-error.h"
45#include "bus-util.h"
430f0182 46#include "capability-util.h"
24efb112 47#include "clock-util.h"
3dfc9763 48#include "conf-parser.h"
618234a5 49#include "cpu-set-util.h"
3dfc9763
LP
50#include "dbus-manager.h"
51#include "def.h"
52#include "env-util.h"
3ffd4af2 53#include "fd-util.h"
3dfc9763 54#include "fdset.h"
718db961 55#include "fileio.h"
24882e06 56#include "formats-util.h"
f4f15635 57#include "fs-util.h"
3dfc9763
LP
58#include "hostname-setup.h"
59#include "ima-setup.h"
60#include "killall.h"
61#include "kmod-setup.h"
d7b8eec7 62#include "load-fragment.h"
3dfc9763 63#include "log.h"
b6e66135 64#include "loopback-setup.h"
b6e66135 65#include "machine-id-setup.h"
3dfc9763
LP
66#include "manager.h"
67#include "missing.h"
68#include "mount-setup.h"
69#include "pager.h"
6bedfcbb 70#include "parse-util.h"
4e731273 71#include "proc-cmdline.h"
3dfc9763 72#include "process-util.h"
8869a0b4 73#include "raw-clone.h"
78f22b97 74#include "rlimit-util.h"
b6e66135 75#include "selinux-setup.h"
3dfc9763
LP
76#include "selinux-util.h"
77#include "signal-util.h"
ffbd2c4d 78#include "smack-setup.h"
3dfc9763 79#include "special.h"
8fcde012 80#include "stat-util.h"
15a5e950 81#include "stdio-util.h"
3dfc9763
LP
82#include "strv.h"
83#include "switch-root.h"
84#include "terminal-util.h"
8612da97 85#include "umask-util.h"
b1d4f8e1 86#include "user-util.h"
3dfc9763
LP
87#include "virt.h"
88#include "watchdog.h"
b6e66135 89
f170852a
LP
90static enum {
91 ACTION_RUN,
e965d56d 92 ACTION_HELP,
9ba0bc4e 93 ACTION_VERSION,
e537352b 94 ACTION_TEST,
494294d6 95 ACTION_DUMP_CONFIGURATION_ITEMS
fa0f4d8a 96} arg_action = ACTION_RUN;
fa0f4d8a 97static char *arg_default_unit = NULL;
463d0d15 98static bool arg_system = false;
fa0f4d8a 99static bool arg_dump_core = true;
fa0f4d8a 100static int arg_crash_chvt = -1;
b9e74c39
LP
101static bool arg_crash_shell = false;
102static bool arg_crash_reboot = false;
fa0f4d8a 103static bool arg_confirm_spawn = false;
b6e2f329 104static ShowStatus arg_show_status = _SHOW_STATUS_UNSET;
bf4df7c3 105static bool arg_switched_root = false;
ea4b98e6 106static bool arg_no_pager = false;
0c85a4f3 107static char ***arg_join_controllers = NULL;
706343f4 108static ExecOutput arg_default_std_output = EXEC_OUTPUT_JOURNAL;
0a494f1f 109static ExecOutput arg_default_std_error = EXEC_OUTPUT_INHERIT;
1f19a534
OS
110static usec_t arg_default_restart_usec = DEFAULT_RESTART_USEC;
111static usec_t arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
112static usec_t arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
3f41e1e5
LN
113static usec_t arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
114static unsigned arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
e96d6be7
LP
115static usec_t arg_runtime_watchdog = 0;
116static usec_t arg_shutdown_watchdog = 10 * USEC_PER_MINUTE;
97d0e5f8 117static char **arg_default_environment = NULL;
517d56b1 118static struct rlimit *arg_default_rlimit[_RLIMIT_MAX] = {};
a103496c 119static uint64_t arg_capability_bounding_set = CAP_ALL;
3a43da28 120static nsec_t arg_timer_slack_nsec = NSEC_INFINITY;
bd8f585b 121static usec_t arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
d3b1c508
LP
122static Set* arg_syscall_archs = NULL;
123static FILE* arg_serialization = NULL;
085afe36 124static bool arg_default_cpu_accounting = false;
13c31542 125static bool arg_default_io_accounting = false;
085afe36
LP
126static bool arg_default_blockio_accounting = false;
127static bool arg_default_memory_accounting = false;
9ded9cd1 128static bool arg_default_tasks_accounting = true;
79baeeb9 129static uint64_t arg_default_tasks_max = UINT64_MAX;
ee48dbd5 130static sd_id128_t arg_machine_id = {};
4fc935ca 131
b9e74c39
LP
132noreturn static void freeze_or_reboot(void) {
133
134 if (arg_crash_reboot) {
135 log_notice("Rebooting in 10s...");
136 (void) sleep(10);
137
138 log_notice("Rebooting now...");
139 (void) reboot(RB_AUTOBOOT);
140 log_emergency_errno(errno, "Failed to reboot: %m");
141 }
142
143 log_emergency("Freezing execution.");
144 freeze();
145}
146
919ce0b7 147noreturn static void crash(int sig) {
7d06dad9
MS
148 struct sigaction sa;
149 pid_t pid;
97c4f35c 150
abb26902
LP
151 if (getpid() != 1)
152 /* Pass this on immediately, if this is not PID 1 */
92ca4cac 153 (void) raise(sig);
abb26902 154 else if (!arg_dump_core)
4104970e 155 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
97c4f35c 156 else {
7d06dad9 157 sa = (struct sigaction) {
189d5bac 158 .sa_handler = nop_signal_handler,
b92bea5d
ZJS
159 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
160 };
97c4f35c 161
6f5e3f35 162 /* We want to wait for the core process, hence let's enable SIGCHLD */
92ca4cac 163 (void) sigaction(SIGCHLD, &sa, NULL);
6f5e3f35 164
8869a0b4 165 pid = raw_clone(SIGCHLD);
e62d8c39 166 if (pid < 0)
56f64d95 167 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
97c4f35c 168 else if (pid == 0) {
97c4f35c 169 /* Enable default signal handler for core dump */
15a90032 170
92ca4cac
LP
171 sa = (struct sigaction) {
172 .sa_handler = SIG_DFL,
173 };
174 (void) sigaction(sig, &sa, NULL);
97c4f35c 175
15a90032
LP
176 /* Don't limit the coredump size */
177 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
97c4f35c
LP
178
179 /* Just to be sure... */
e62d9b81 180 (void) chdir("/");
97c4f35c
LP
181
182 /* Raise the signal again */
ee05e779 183 pid = raw_getpid();
92ca4cac 184 (void) kill(pid, sig); /* raise() would kill the parent */
97c4f35c
LP
185
186 assert_not_reached("We shouldn't be here...");
92ca4cac 187 _exit(EXIT_FAILURE);
4fc935ca 188 } else {
8e12a6ae
LP
189 siginfo_t status;
190 int r;
4fc935ca
LP
191
192 /* Order things nicely. */
e62d8c39
ZJS
193 r = wait_for_terminate(pid, &status);
194 if (r < 0)
da927ba9 195 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
8e12a6ae 196 else if (status.si_code != CLD_DUMPED)
ee05e779
ZJS
197 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
198 signal_to_string(sig),
199 pid, sigchld_code_to_string(status.si_code),
200 status.si_status,
201 strna(status.si_code == CLD_EXITED
202 ? exit_status_to_string(status.si_status, EXIT_STATUS_FULL)
203 : signal_to_string(status.si_status)));
4fc935ca 204 else
4104970e 205 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".", signal_to_string(sig), pid);
97c4f35c
LP
206 }
207 }
208
b9e74c39 209 if (arg_crash_chvt >= 0)
92ca4cac 210 (void) chvt(arg_crash_chvt);
601f6a1e 211
7d06dad9
MS
212 sa = (struct sigaction) {
213 .sa_handler = SIG_IGN,
214 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
215 };
216
217 /* Let the kernel reap children for us */
218 (void) sigaction(SIGCHLD, &sa, NULL);
8c43883a 219
7d06dad9 220 if (arg_crash_shell) {
b9e74c39 221 log_notice("Executing crash shell in 10s...");
92ca4cac 222 (void) sleep(10);
4fc935ca 223
8869a0b4 224 pid = raw_clone(SIGCHLD);
cd3bd60a 225 if (pid < 0)
56f64d95 226 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
6f5e3f35 227 else if (pid == 0) {
b9e74c39 228 (void) setsid();
92ca4cac
LP
229 (void) make_console_stdio();
230 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
6f5e3f35 231
ee05e779 232 log_emergency_errno(errno, "execle() failed: %m");
92ca4cac 233 _exit(EXIT_FAILURE);
b9e74c39
LP
234 } else {
235 log_info("Spawned crash shell as PID "PID_FMT".", pid);
4cf0b03b 236 (void) wait_for_terminate(pid, NULL);
b9e74c39 237 }
4fc935ca
LP
238 }
239
b9e74c39 240 freeze_or_reboot();
97c4f35c
LP
241}
242
243static void install_crash_handler(void) {
297d563d 244 static const struct sigaction sa = {
b92bea5d 245 .sa_handler = crash,
297d563d 246 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
b92bea5d 247 };
297d563d 248 int r;
97c4f35c 249
297d563d
LP
250 /* We ignore the return value here, since, we don't mind if we
251 * cannot set up a crash handler */
252 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
253 if (r < 0)
254 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
97c4f35c 255}
f170852a 256
56d96fc0
LP
257static int console_setup(void) {
258 _cleanup_close_ int tty_fd = -1;
259 int r;
80876c20 260
512947d4 261 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
262 if (tty_fd < 0)
263 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 264
56d96fc0
LP
265 /* We don't want to force text mode. plymouth may be showing
266 * pictures already from initrd. */
512947d4 267 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
268 if (r < 0)
269 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 270
56d96fc0 271 return 0;
80876c20
LP
272}
273
b9e74c39
LP
274static int parse_crash_chvt(const char *value) {
275 int b;
276
277 if (safe_atoi(value, &arg_crash_chvt) >= 0)
278 return 0;
279
280 b = parse_boolean(value);
281 if (b < 0)
282 return b;
283
284 if (b > 0)
285 arg_crash_chvt = 0; /* switch to where kmsg goes */
286 else
287 arg_crash_chvt = -1; /* turn off switching */
288
289 return 0;
290}
291
ee48dbd5 292static int set_machine_id(const char *m) {
e042eab7 293 sd_id128_t t;
8b26cdbd 294 assert(m);
ee48dbd5 295
e042eab7 296 if (sd_id128_from_string(m, &t) < 0)
ee48dbd5
NC
297 return -EINVAL;
298
e042eab7 299 if (sd_id128_is_null(t))
ee48dbd5
NC
300 return -EINVAL;
301
e042eab7 302 arg_machine_id = t;
ee48dbd5
NC
303 return 0;
304}
305
059cb385 306static int parse_proc_cmdline_item(const char *key, const char *value) {
f170852a 307
059cb385 308 int r;
f170852a 309
059cb385 310 assert(key);
5192bd19 311
059cb385 312 if (streq(key, "systemd.unit") && value) {
bf4df7c3
LP
313
314 if (!in_initrd())
e6e242ad 315 return free_and_strdup(&arg_default_unit, value);
bf4df7c3 316
059cb385 317 } else if (streq(key, "rd.systemd.unit") && value) {
bf4df7c3 318
ca05941b 319 if (in_initrd())
e6e242ad 320 return free_and_strdup(&arg_default_unit, value);
f170852a 321
059cb385 322 } else if (streq(key, "systemd.dump_core") && value) {
4fc935ca 323
059cb385 324 r = parse_boolean(value);
fb472900 325 if (r < 0)
059cb385 326 log_warning("Failed to parse dump core switch %s. Ignoring.", value);
4fc935ca 327 else
fa0f4d8a 328 arg_dump_core = r;
4fc935ca 329
b9e74c39
LP
330 } else if (streq(key, "systemd.crash_chvt") && value) {
331
332 if (parse_crash_chvt(value) < 0)
333 log_warning("Failed to parse crash chvt switch %s. Ignoring.", value);
334
059cb385 335 } else if (streq(key, "systemd.crash_shell") && value) {
4fc935ca 336
059cb385 337 r = parse_boolean(value);
fb472900 338 if (r < 0)
059cb385 339 log_warning("Failed to parse crash shell switch %s. Ignoring.", value);
4fc935ca 340 else
fa0f4d8a 341 arg_crash_shell = r;
5e7ee61c 342
b9e74c39 343 } else if (streq(key, "systemd.crash_reboot") && value) {
5e7ee61c 344
b9e74c39
LP
345 r = parse_boolean(value);
346 if (r < 0)
347 log_warning("Failed to parse crash reboot switch %s. Ignoring.", value);
5e7ee61c 348 else
b9e74c39 349 arg_crash_reboot = r;
5e7ee61c 350
059cb385 351 } else if (streq(key, "systemd.confirm_spawn") && value) {
601f6a1e 352
059cb385
LP
353 r = parse_boolean(value);
354 if (r < 0)
355 log_warning("Failed to parse confirm spawn switch %s. Ignoring.", value);
601f6a1e 356 else
059cb385 357 arg_confirm_spawn = r;
601f6a1e 358
059cb385 359 } else if (streq(key, "systemd.show_status") && value) {
9e58ff9c 360
059cb385 361 r = parse_show_status(value, &arg_show_status);
d450b6f2 362 if (r < 0)
059cb385
LP
363 log_warning("Failed to parse show status switch %s. Ignoring.", value);
364
365 } else if (streq(key, "systemd.default_standard_output") && value) {
0a494f1f 366
059cb385 367 r = exec_output_from_string(value);
fb472900 368 if (r < 0)
059cb385 369 log_warning("Failed to parse default standard output switch %s. Ignoring.", value);
0a494f1f
LP
370 else
371 arg_default_std_output = r;
0a494f1f 372
059cb385
LP
373 } else if (streq(key, "systemd.default_standard_error") && value) {
374
375 r = exec_output_from_string(value);
fb472900 376 if (r < 0)
059cb385 377 log_warning("Failed to parse default standard error switch %s. Ignoring.", value);
0a494f1f
LP
378 else
379 arg_default_std_error = r;
9e7c5357 380
059cb385
LP
381 } else if (streq(key, "systemd.setenv") && value) {
382
383 if (env_assignment_is_valid(value)) {
e21fea24
KS
384 char **env;
385
059cb385 386 env = strv_env_set(arg_default_environment, value);
e21fea24
KS
387 if (env)
388 arg_default_environment = env;
389 else
279d3c9c 390 log_warning_errno(ENOMEM, "Setting environment variable '%s' failed, ignoring: %m", value);
e21fea24 391 } else
059cb385 392 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
9e58ff9c 393
ee48dbd5
NC
394 } else if (streq(key, "systemd.machine_id") && value) {
395
396 r = set_machine_id(value);
397 if (r < 0)
398 log_warning("MachineID '%s' is not valid. Ignoring.", value);
399
059cb385 400 } else if (streq(key, "quiet") && !value) {
d7b15e0a 401
b6e2f329 402 if (arg_show_status == _SHOW_STATUS_UNSET)
d450b6f2 403 arg_show_status = SHOW_STATUS_AUTO;
059cb385
LP
404
405 } else if (streq(key, "debug") && !value) {
d7b15e0a 406
1de1c9c3
LP
407 /* Note that log_parse_environment() handles 'debug'
408 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 409
75f86906 410 if (detect_container() > 0)
b2103dcc 411 log_set_target(LOG_TARGET_CONSOLE);
059cb385 412
dcd61450 413 } else if (!value) {
e2c9a131 414 const char *target;
f170852a
LP
415
416 /* SysV compatibility */
e2c9a131
EV
417 target = runlevel_to_target(key);
418 if (target)
419 return free_and_strdup(&arg_default_unit, target);
959718c6
TB
420
421 } else if (streq(key, "systemd.default_timeout_start_sec") && value) {
422
423 r = parse_sec(value, &arg_default_timeout_start_usec);
424 if (r < 0)
425 log_warning_errno(r, "Failed to parse default start timeout: %s, ignoring.", value);
426
427 if (arg_default_timeout_start_usec <= 0)
428 arg_default_timeout_start_usec = USEC_INFINITY;
f170852a
LP
429 }
430
431 return 0;
432}
433
e8e581bf
ZJS
434#define DEFINE_SETTER(name, func, descr) \
435 static int name(const char *unit, \
436 const char *filename, \
437 unsigned line, \
438 const char *section, \
71a61510 439 unsigned section_line, \
e8e581bf
ZJS
440 const char *lvalue, \
441 int ltype, \
442 const char *rvalue, \
443 void *data, \
444 void *userdata) { \
445 \
446 int r; \
447 \
448 assert(filename); \
449 assert(lvalue); \
450 assert(rvalue); \
451 \
452 r = func(rvalue); \
453 if (r < 0) \
d1cefe0a
LP
454 log_syntax(unit, LOG_ERR, filename, line, r, \
455 "Invalid " descr "'%s': %m", \
456 rvalue); \
e8e581bf
ZJS
457 \
458 return 0; \
459 }
487393e9 460
e8e581bf
ZJS
461DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level")
462DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target")
463DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" )
464DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location")
487393e9 465
4d7213b2
LP
466static int config_parse_cpu_affinity2(
467 const char *unit,
468 const char *filename,
469 unsigned line,
470 const char *section,
471 unsigned section_line,
472 const char *lvalue,
473 int ltype,
474 const char *rvalue,
475 void *data,
476 void *userdata) {
487393e9 477
4b40bc38 478 _cleanup_cpu_free_ cpu_set_t *c = NULL;
f5c72b73 479 int ncpus;
487393e9 480
765d143b 481 ncpus = parse_cpu_set_and_warn(rvalue, &c, unit, filename, line, lvalue);
f5c72b73
FB
482 if (ncpus < 0)
483 return ncpus;
487393e9 484
f5c72b73
FB
485 if (sched_setaffinity(0, CPU_ALLOC_SIZE(ncpus), c) < 0)
486 log_warning("Failed to set CPU affinity: %m");
487393e9 487
487393e9
LP
488 return 0;
489}
490
4d7213b2
LP
491static int config_parse_show_status(
492 const char* unit,
493 const char *filename,
494 unsigned line,
495 const char *section,
496 unsigned section_line,
497 const char *lvalue,
498 int ltype,
499 const char *rvalue,
500 void *data,
501 void *userdata) {
502
503 int k;
504 ShowStatus *b = data;
505
506 assert(filename);
507 assert(lvalue);
508 assert(rvalue);
509 assert(data);
510
511 k = parse_show_status(rvalue, b);
512 if (k < 0) {
12ca818f 513 log_syntax(unit, LOG_ERR, filename, line, k, "Failed to parse show status setting, ignoring: %s", rvalue);
4d7213b2
LP
514 return 0;
515 }
516
517 return 0;
518}
519
b9e74c39
LP
520static int config_parse_crash_chvt(
521 const char* unit,
522 const char *filename,
523 unsigned line,
524 const char *section,
525 unsigned section_line,
526 const char *lvalue,
527 int ltype,
528 const char *rvalue,
529 void *data,
530 void *userdata) {
531
532 int r;
533
534 assert(filename);
535 assert(lvalue);
536 assert(rvalue);
b9e74c39
LP
537
538 r = parse_crash_chvt(rvalue);
539 if (r < 0) {
540 log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CrashChangeVT= setting, ignoring: %s", rvalue);
541 return 0;
542 }
543
544 return 0;
545}
546
e8e581bf
ZJS
547static int config_parse_join_controllers(const char *unit,
548 const char *filename,
549 unsigned line,
550 const char *section,
71a61510 551 unsigned section_line,
e8e581bf
ZJS
552 const char *lvalue,
553 int ltype,
554 const char *rvalue,
555 void *data,
556 void *userdata) {
0c85a4f3 557
3875c85b 558 const char *whole_rvalue = rvalue;
0c85a4f3 559 unsigned n = 0;
0c85a4f3
LP
560
561 assert(filename);
562 assert(lvalue);
563 assert(rvalue);
564
fe382237 565 arg_join_controllers = strv_free_free(arg_join_controllers);
0c85a4f3 566
d4ebeb4f
FB
567 for (;;) {
568 _cleanup_free_ char *word = NULL;
569 char **l;
570 int r;
0c85a4f3 571
d4ebeb4f 572 r = extract_first_word(&rvalue, &word, WHITESPACE, EXTRACT_QUOTES);
3875c85b
FB
573 if (r < 0) {
574 log_syntax(unit, LOG_ERR, filename, line, r, "Invalid value for %s: %s", lvalue, whole_rvalue);
d4ebeb4f 575 return r;
3875c85b 576 }
d4ebeb4f
FB
577 if (r == 0)
578 break;
0c85a4f3 579
d4ebeb4f 580 l = strv_split(word, ",");
1592ec21 581 if (!l)
aa8aeac0 582 return log_oom();
0c85a4f3
LP
583 strv_uniq(l);
584
585 if (strv_length(l) <= 1) {
586 strv_free(l);
587 continue;
588 }
589
590 if (!arg_join_controllers) {
591 arg_join_controllers = new(char**, 2);
592 if (!arg_join_controllers) {
593 strv_free(l);
14212119 594 return log_oom();
0c85a4f3
LP
595 }
596
597 arg_join_controllers[0] = l;
598 arg_join_controllers[1] = NULL;
599
600 n = 1;
601 } else {
602 char ***a;
603 char ***t;
604
605 t = new0(char**, n+2);
606 if (!t) {
607 strv_free(l);
14212119 608 return log_oom();
0c85a4f3
LP
609 }
610
611 n = 0;
612
613 for (a = arg_join_controllers; *a; a++) {
614
615 if (strv_overlap(*a, l)) {
e287086b 616 if (strv_extend_strv(&l, *a, false) < 0) {
0c85a4f3
LP
617 strv_free(l);
618 strv_free_free(t);
14212119 619 return log_oom();
0c85a4f3
LP
620 }
621
0c85a4f3
LP
622 } else {
623 char **c;
624
625 c = strv_copy(*a);
626 if (!c) {
627 strv_free(l);
628 strv_free_free(t);
14212119 629 return log_oom();
0c85a4f3
LP
630 }
631
632 t[n++] = c;
633 }
634 }
635
636 t[n++] = strv_uniq(l);
637
638 strv_free_free(arg_join_controllers);
639 arg_join_controllers = t;
640 }
641 }
d4ebeb4f 642 if (!isempty(rvalue))
12ca818f 643 log_syntax(unit, LOG_ERR, filename, line, 0, "Trailing garbage, ignoring.");
0c85a4f3
LP
644
645 return 0;
646}
647
487393e9
LP
648static int parse_config_file(void) {
649
f975e971 650 const ConfigTableItem items[] = {
d3b1c508
LP
651 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
652 { "Manager", "LogTarget", config_parse_target, 0, NULL },
653 { "Manager", "LogColor", config_parse_color, 0, NULL },
654 { "Manager", "LogLocation", config_parse_location, 0, NULL },
655 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
b9e74c39
LP
656 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, NULL },
657 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, NULL },
d3b1c508 658 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
b9e74c39 659 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
d3b1c508 660 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
d3b1c508
LP
661 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, NULL },
662 { "Manager", "JoinControllers", config_parse_join_controllers, 0, &arg_join_controllers },
663 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
664 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_shutdown_watchdog },
a103496c 665 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
89fffa27 666#ifdef HAVE_SECCOMP
d3b1c508 667 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
89fffa27 668#endif
d3b1c508 669 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
bd8f585b 670 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
d3b1c508
LP
671 { "Manager", "DefaultStandardOutput", config_parse_output, 0, &arg_default_std_output },
672 { "Manager", "DefaultStandardError", config_parse_output, 0, &arg_default_std_error },
673 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
674 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
675 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
f0367da7
LP
676 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
677 { "Manager", "DefaultStartLimitIntervalSec",config_parse_sec, 0, &arg_default_start_limit_interval },
d3b1c508
LP
678 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
679 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
d0a7c5f6
LP
680 { "Manager", "DefaultLimitCPU", config_parse_limit, RLIMIT_CPU, arg_default_rlimit },
681 { "Manager", "DefaultLimitFSIZE", config_parse_limit, RLIMIT_FSIZE, arg_default_rlimit },
682 { "Manager", "DefaultLimitDATA", config_parse_limit, RLIMIT_DATA, arg_default_rlimit },
683 { "Manager", "DefaultLimitSTACK", config_parse_limit, RLIMIT_STACK, arg_default_rlimit },
684 { "Manager", "DefaultLimitCORE", config_parse_limit, RLIMIT_CORE, arg_default_rlimit },
685 { "Manager", "DefaultLimitRSS", config_parse_limit, RLIMIT_RSS, arg_default_rlimit },
686 { "Manager", "DefaultLimitNOFILE", config_parse_limit, RLIMIT_NOFILE, arg_default_rlimit },
687 { "Manager", "DefaultLimitAS", config_parse_limit, RLIMIT_AS, arg_default_rlimit },
688 { "Manager", "DefaultLimitNPROC", config_parse_limit, RLIMIT_NPROC, arg_default_rlimit },
689 { "Manager", "DefaultLimitMEMLOCK", config_parse_limit, RLIMIT_MEMLOCK, arg_default_rlimit },
690 { "Manager", "DefaultLimitLOCKS", config_parse_limit, RLIMIT_LOCKS, arg_default_rlimit },
691 { "Manager", "DefaultLimitSIGPENDING", config_parse_limit, RLIMIT_SIGPENDING, arg_default_rlimit },
692 { "Manager", "DefaultLimitMSGQUEUE", config_parse_limit, RLIMIT_MSGQUEUE, arg_default_rlimit },
693 { "Manager", "DefaultLimitNICE", config_parse_limit, RLIMIT_NICE, arg_default_rlimit },
694 { "Manager", "DefaultLimitRTPRIO", config_parse_limit, RLIMIT_RTPRIO, arg_default_rlimit },
695 { "Manager", "DefaultLimitRTTIME", config_parse_limit, RLIMIT_RTTIME, arg_default_rlimit },
085afe36 696 { "Manager", "DefaultCPUAccounting", config_parse_bool, 0, &arg_default_cpu_accounting },
13c31542 697 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
085afe36
LP
698 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
699 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
03a7b521 700 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
0af20ea2 701 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
d3b1c508 702 {}
487393e9
LP
703 };
704
1b907b5c 705 const char *fn, *conf_dirs_nulstr;
487393e9 706
463d0d15 707 fn = arg_system ?
75eb6154
LP
708 PKGSYSCONFDIR "/system.conf" :
709 PKGSYSCONFDIR "/user.conf";
710
463d0d15 711 conf_dirs_nulstr = arg_system ?
75eb6154
LP
712 CONF_PATHS_NULSTR("systemd/system.conf.d") :
713 CONF_PATHS_NULSTR("systemd/user.conf.d");
714
36c16a7c
LP
715 config_parse_many(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, false, NULL);
716
717 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
718 * like everywhere else. */
719 if (arg_default_timeout_start_usec <= 0)
720 arg_default_timeout_start_usec = USEC_INFINITY;
721 if (arg_default_timeout_stop_usec <= 0)
722 arg_default_timeout_stop_usec = USEC_INFINITY;
487393e9 723
487393e9
LP
724 return 0;
725}
726
06af2a04
TB
727static void manager_set_defaults(Manager *m) {
728
729 assert(m);
730
731 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
732 m->default_std_output = arg_default_std_output;
733 m->default_std_error = arg_default_std_error;
734 m->default_timeout_start_usec = arg_default_timeout_start_usec;
735 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
736 m->default_restart_usec = arg_default_restart_usec;
737 m->default_start_limit_interval = arg_default_start_limit_interval;
738 m->default_start_limit_burst = arg_default_start_limit_burst;
739 m->default_cpu_accounting = arg_default_cpu_accounting;
13c31542 740 m->default_io_accounting = arg_default_io_accounting;
06af2a04
TB
741 m->default_blockio_accounting = arg_default_blockio_accounting;
742 m->default_memory_accounting = arg_default_memory_accounting;
03a7b521 743 m->default_tasks_accounting = arg_default_tasks_accounting;
0af20ea2 744 m->default_tasks_max = arg_default_tasks_max;
06af2a04
TB
745
746 manager_set_default_rlimits(m, arg_default_rlimit);
747 manager_environment_add(m, NULL, arg_default_environment);
748}
749
f170852a
LP
750static int parse_argv(int argc, char *argv[]) {
751
752 enum {
753 ARG_LOG_LEVEL = 0x100,
754 ARG_LOG_TARGET,
bbe63281
LP
755 ARG_LOG_COLOR,
756 ARG_LOG_LOCATION,
2f198e2f 757 ARG_UNIT,
edb9aaa8 758 ARG_SYSTEM,
af2d49f7 759 ARG_USER,
e537352b 760 ARG_TEST,
b87c2aa6 761 ARG_NO_PAGER,
9ba0bc4e 762 ARG_VERSION,
80876c20 763 ARG_DUMP_CONFIGURATION_ITEMS,
9e58ff9c 764 ARG_DUMP_CORE,
b9e74c39 765 ARG_CRASH_CHVT,
9e58ff9c 766 ARG_CRASH_SHELL,
b9e74c39 767 ARG_CRASH_REBOOT,
a16e1123 768 ARG_CONFIRM_SPAWN,
9e58ff9c 769 ARG_SHOW_STATUS,
4288f619 770 ARG_DESERIALIZE,
2660882b 771 ARG_SWITCHED_ROOT,
0a494f1f 772 ARG_DEFAULT_STD_OUTPUT,
ee48dbd5
NC
773 ARG_DEFAULT_STD_ERROR,
774 ARG_MACHINE_ID
f170852a
LP
775 };
776
777 static const struct option options[] = {
a16e1123
LP
778 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
779 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
780 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
781 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 782 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 783 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 784 { "user", no_argument, NULL, ARG_USER },
a16e1123 785 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 786 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 787 { "help", no_argument, NULL, 'h' },
9ba0bc4e 788 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 789 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
a5d87bf0 790 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
b9e74c39 791 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
a5d87bf0 792 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
b9e74c39 793 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
a5d87bf0 794 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 795 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 796 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 797 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
798 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
799 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
ee48dbd5 800 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
fb472900 801 {}
f170852a
LP
802 };
803
804 int c, r;
805
806 assert(argc >= 1);
807 assert(argv);
808
b770165a
LP
809 if (getpid() == 1)
810 opterr = 0;
811
099663ff 812 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
813
814 switch (c) {
815
816 case ARG_LOG_LEVEL:
fb472900
ZJS
817 r = log_set_max_level_from_string(optarg);
818 if (r < 0) {
f170852a
LP
819 log_error("Failed to parse log level %s.", optarg);
820 return r;
821 }
822
823 break;
824
825 case ARG_LOG_TARGET:
fb472900
ZJS
826 r = log_set_target_from_string(optarg);
827 if (r < 0) {
f170852a
LP
828 log_error("Failed to parse log target %s.", optarg);
829 return r;
830 }
831
832 break;
833
bbe63281
LP
834 case ARG_LOG_COLOR:
835
d0b170c8 836 if (optarg) {
fb472900
ZJS
837 r = log_show_color_from_string(optarg);
838 if (r < 0) {
d0b170c8
LP
839 log_error("Failed to parse log color setting %s.", optarg);
840 return r;
841 }
842 } else
843 log_show_color(true);
bbe63281
LP
844
845 break;
846
847 case ARG_LOG_LOCATION:
d0b170c8 848 if (optarg) {
fb472900
ZJS
849 r = log_show_location_from_string(optarg);
850 if (r < 0) {
d0b170c8
LP
851 log_error("Failed to parse log location setting %s.", optarg);
852 return r;
853 }
854 } else
855 log_show_location(true);
bbe63281
LP
856
857 break;
858
0a494f1f 859 case ARG_DEFAULT_STD_OUTPUT:
fb472900
ZJS
860 r = exec_output_from_string(optarg);
861 if (r < 0) {
0a494f1f
LP
862 log_error("Failed to parse default standard output setting %s.", optarg);
863 return r;
864 } else
865 arg_default_std_output = r;
866 break;
867
868 case ARG_DEFAULT_STD_ERROR:
fb472900
ZJS
869 r = exec_output_from_string(optarg);
870 if (r < 0) {
0a494f1f
LP
871 log_error("Failed to parse default standard error output setting %s.", optarg);
872 return r;
873 } else
874 arg_default_std_error = r;
875 break;
876
2f198e2f 877 case ARG_UNIT:
f170852a 878
e6e242ad 879 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de
MS
880 if (r < 0)
881 return log_error_errno(r, "Failed to set default unit %s: %m", optarg);
f170852a
LP
882
883 break;
884
edb9aaa8 885 case ARG_SYSTEM:
463d0d15 886 arg_system = true;
edb9aaa8 887 break;
a5dab5ce 888
af2d49f7 889 case ARG_USER:
463d0d15 890 arg_system = false;
a5dab5ce 891 break;
a5dab5ce 892
e965d56d 893 case ARG_TEST:
fa0f4d8a 894 arg_action = ACTION_TEST;
b87c2aa6
ZJS
895 break;
896
897 case ARG_NO_PAGER:
898 arg_no_pager = true;
e965d56d
LP
899 break;
900
9ba0bc4e
ZJS
901 case ARG_VERSION:
902 arg_action = ACTION_VERSION;
903 break;
904
e537352b 905 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 906 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
907 break;
908
9e58ff9c 909 case ARG_DUMP_CORE:
b9e74c39
LP
910 if (!optarg)
911 arg_dump_core = true;
912 else {
913 r = parse_boolean(optarg);
914 if (r < 0)
915 return log_error_errno(r, "Failed to parse dump core boolean: %s", optarg);
916 arg_dump_core = r;
a5d87bf0 917 }
b9e74c39
LP
918 break;
919
920 case ARG_CRASH_CHVT:
921 r = parse_crash_chvt(optarg);
922 if (r < 0)
923 return log_error_errno(r, "Failed to parse crash virtual terminal index: %s", optarg);
9e58ff9c
LP
924 break;
925
926 case ARG_CRASH_SHELL:
b9e74c39
LP
927 if (!optarg)
928 arg_crash_shell = true;
929 else {
930 r = parse_boolean(optarg);
931 if (r < 0)
932 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
933 arg_crash_shell = r;
934 }
935 break;
936
937 case ARG_CRASH_REBOOT:
938 if (!optarg)
939 arg_crash_reboot = true;
940 else {
941 r = parse_boolean(optarg);
942 if (r < 0)
943 return log_error_errno(r, "Failed to parse crash shell boolean: %s", optarg);
944 arg_crash_reboot = r;
a5d87bf0 945 }
9e58ff9c
LP
946 break;
947
80876c20 948 case ARG_CONFIRM_SPAWN:
a5d87bf0
LP
949 r = optarg ? parse_boolean(optarg) : 1;
950 if (r < 0) {
951 log_error("Failed to parse confirm spawn boolean %s.", optarg);
952 return r;
953 }
954 arg_confirm_spawn = r;
80876c20
LP
955 break;
956
9e58ff9c 957 case ARG_SHOW_STATUS:
d450b6f2
ZJS
958 if (optarg) {
959 r = parse_show_status(optarg, &arg_show_status);
960 if (r < 0) {
961 log_error("Failed to parse show status boolean %s.", optarg);
962 return r;
963 }
964 } else
965 arg_show_status = SHOW_STATUS_YES;
6e98720f 966 break;
a5d87bf0 967
a16e1123
LP
968 case ARG_DESERIALIZE: {
969 int fd;
970 FILE *f;
971
01e10de3
LP
972 r = safe_atoi(optarg, &fd);
973 if (r < 0 || fd < 0) {
a16e1123 974 log_error("Failed to parse deserialize option %s.", optarg);
b9e74c39 975 return -EINVAL;
a16e1123
LP
976 }
977
b9e74c39 978 (void) fd_cloexec(fd, true);
01e10de3
LP
979
980 f = fdopen(fd, "r");
4a62c710
MS
981 if (!f)
982 return log_error_errno(errno, "Failed to open serialization fd: %m");
a16e1123 983
74ca738f 984 safe_fclose(arg_serialization);
d3b1c508 985 arg_serialization = f;
a16e1123
LP
986
987 break;
988 }
989
2660882b 990 case ARG_SWITCHED_ROOT:
bf4df7c3 991 arg_switched_root = true;
d03bc1b8
HH
992 break;
993
ee48dbd5
NC
994 case ARG_MACHINE_ID:
995 r = set_machine_id(optarg);
996 if (r < 0) {
997 log_error("MachineID '%s' is not valid.", optarg);
998 return r;
999 }
1000 break;
1001
f170852a 1002 case 'h':
fa0f4d8a 1003 arg_action = ACTION_HELP;
f170852a
LP
1004 break;
1005
1d2e23ab
LP
1006 case 'D':
1007 log_set_max_level(LOG_DEBUG);
1008 break;
1009
099663ff
LP
1010 case 'b':
1011 case 's':
1012 case 'z':
1013 /* Just to eat away the sysvinit kernel
1014 * cmdline args without getopt() error
1015 * messages that we'll parse in
1016 * parse_proc_cmdline_word() or ignore. */
f170852a 1017
099663ff 1018 case '?':
601185b4 1019 if (getpid() != 1)
099663ff 1020 return -EINVAL;
601185b4
ZJS
1021 else
1022 return 0;
099663ff 1023
601185b4
ZJS
1024 default:
1025 assert_not_reached("Unhandled option code.");
f170852a
LP
1026 }
1027
d821e6d6
LP
1028 if (optind < argc && getpid() != 1) {
1029 /* Hmm, when we aren't run as init system
1030 * let's complain about excess arguments */
1031
1032 log_error("Excess arguments.");
1033 return -EINVAL;
1034 }
1035
f170852a
LP
1036 return 0;
1037}
1038
1039static int help(void) {
1040
2e33c433 1041 printf("%s [OPTIONS...]\n\n"
af2d49f7 1042 "Starts up and maintains the system or user services.\n\n"
e537352b 1043 " -h --help Show this help\n"
e537352b 1044 " --test Determine startup sequence, dump it and exit\n"
b87c2aa6 1045 " --no-pager Do not pipe output into a pager\n"
80876c20 1046 " --dump-configuration-items Dump understood unit configuration items\n"
9e58ff9c 1047 " --unit=UNIT Set default unit\n"
edb9aaa8 1048 " --system Run a system instance, even if PID != 1\n"
af2d49f7 1049 " --user Run a user instance\n"
b9e74c39
LP
1050 " --dump-core[=BOOL] Dump core on crash\n"
1051 " --crash-vt=NR Change to specified VT on crash\n"
1052 " --crash-reboot[=BOOL] Reboot on crash\n"
1053 " --crash-shell[=BOOL] Run shell on crash\n"
1054 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1055 " --show-status[=BOOL] Show status updates on the console during bootup\n"
c1dc6153 1056 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
9e58ff9c 1057 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
b9e74c39
LP
1058 " --log-color[=BOOL] Highlight important log messages\n"
1059 " --log-location[=BOOL] Include code location in log messages\n"
0a494f1f
LP
1060 " --default-standard-output= Set default standard output for services\n"
1061 " --default-standard-error= Set default standard error output for services\n",
5b6319dc 1062 program_invocation_short_name);
f170852a
LP
1063
1064 return 0;
1065}
1066
b3680f49 1067static int prepare_reexecute(Manager *m, FILE **_f, FDSet **_fds, bool switching_root) {
48b90859
LP
1068 _cleanup_fdset_free_ FDSet *fds = NULL;
1069 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1070 int r;
1071
1072 assert(m);
1073 assert(_f);
1074 assert(_fds);
1075
6b78f9b4 1076 r = manager_open_serialization(m, &f);
48b90859
LP
1077 if (r < 0)
1078 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1079
71445ae7 1080 /* Make sure nothing is really destructed when we shut down */
313cefa1 1081 m->n_reloading++;
718db961 1082 bus_manager_send_reloading(m, true);
71445ae7 1083
6b78f9b4 1084 fds = fdset_new();
48b90859
LP
1085 if (!fds)
1086 return log_oom();
a16e1123 1087
b3680f49 1088 r = manager_serialize(m, f, fds, switching_root);
48b90859
LP
1089 if (r < 0)
1090 return log_error_errno(r, "Failed to serialize state: %m");
a16e1123 1091
48b90859
LP
1092 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1093 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1094
6b78f9b4 1095 r = fd_cloexec(fileno(f), false);
48b90859
LP
1096 if (r < 0)
1097 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1098
6b78f9b4 1099 r = fdset_cloexec(fds, false);
48b90859
LP
1100 if (r < 0)
1101 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123
LP
1102
1103 *_f = f;
1104 *_fds = fds;
1105
48b90859
LP
1106 f = NULL;
1107 fds = NULL;
a16e1123 1108
48b90859 1109 return 0;
a16e1123
LP
1110}
1111
4096d6f5
LP
1112static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
1113 struct rlimit nl;
1114 int r;
1115
1116 assert(saved_rlimit);
1117
1118 /* Save the original RLIMIT_NOFILE so that we can reset it
1119 * later when transitioning from the initrd to the main
1120 * systemd or suchlike. */
4a62c710
MS
1121 if (getrlimit(RLIMIT_NOFILE, saved_rlimit) < 0)
1122 return log_error_errno(errno, "Reading RLIMIT_NOFILE failed: %m");
4096d6f5
LP
1123
1124 /* Make sure forked processes get the default kernel setting */
1125 if (!arg_default_rlimit[RLIMIT_NOFILE]) {
1126 struct rlimit *rl;
1127
1128 rl = newdup(struct rlimit, saved_rlimit, 1);
1129 if (!rl)
1130 return log_oom();
1131
1132 arg_default_rlimit[RLIMIT_NOFILE] = rl;
1133 }
1134
1135 /* Bump up the resource limit for ourselves substantially */
1136 nl.rlim_cur = nl.rlim_max = 64*1024;
1137 r = setrlimit_closest(RLIMIT_NOFILE, &nl);
23bbb0de
MS
1138 if (r < 0)
1139 return log_error_errno(r, "Setting RLIMIT_NOFILE failed: %m");
4096d6f5
LP
1140
1141 return 0;
1142}
1143
80758717 1144static void test_usr(void) {
80758717 1145
ed1c99fc 1146 /* Check that /usr is not a separate fs */
80758717 1147
871c44a7
LP
1148 if (dir_is_empty("/usr") <= 0)
1149 return;
1150
8b173b5e 1151 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1152 "Some things will probably break (sometimes even silently) in mysterious ways. "
1153 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1154}
1155
a07fdfa3
LP
1156static int initialize_join_controllers(void) {
1157 /* By default, mount "cpu" + "cpuacct" together, and "net_cls"
1158 * + "net_prio". We'd like to add "cpuset" to the mix, but
f131770b 1159 * "cpuset" doesn't really work for groups with no initialized
a07fdfa3
LP
1160 * attributes. */
1161
1162 arg_join_controllers = new(char**, 3);
1163 if (!arg_join_controllers)
1164 return -ENOMEM;
1165
1166 arg_join_controllers[0] = strv_new("cpu", "cpuacct", NULL);
fe382237
LP
1167 if (!arg_join_controllers[0])
1168 goto oom;
a6b26d90 1169
fe382237
LP
1170 arg_join_controllers[1] = strv_new("net_cls", "net_prio", NULL);
1171 if (!arg_join_controllers[1])
1172 goto oom;
a07fdfa3 1173
fe382237 1174 arg_join_controllers[2] = NULL;
a07fdfa3 1175 return 0;
fe382237
LP
1176
1177oom:
1178 arg_join_controllers = strv_free_free(arg_join_controllers);
1179 return -ENOMEM;
a07fdfa3
LP
1180}
1181
d3b1c508
LP
1182static int enforce_syscall_archs(Set *archs) {
1183#ifdef HAVE_SECCOMP
1184 scmp_filter_ctx *seccomp;
1185 Iterator i;
1186 void *id;
1187 int r;
1188
1189 seccomp = seccomp_init(SCMP_ACT_ALLOW);
1190 if (!seccomp)
1191 return log_oom();
1192
1193 SET_FOREACH(id, arg_syscall_archs, i) {
1194 r = seccomp_arch_add(seccomp, PTR_TO_UINT32(id) - 1);
1195 if (r == -EEXIST)
1196 continue;
1197 if (r < 0) {
da927ba9 1198 log_error_errno(r, "Failed to add architecture to seccomp: %m");
d3b1c508
LP
1199 goto finish;
1200 }
1201 }
1202
8a8bf3c0
LP
1203 r = seccomp_attr_set(seccomp, SCMP_FLTATR_CTL_NNP, 0);
1204 if (r < 0) {
da927ba9 1205 log_error_errno(r, "Failed to unset NO_NEW_PRIVS: %m");
8a8bf3c0
LP
1206 goto finish;
1207 }
1208
d3b1c508
LP
1209 r = seccomp_load(seccomp);
1210 if (r < 0)
da927ba9 1211 log_error_errno(r, "Failed to add install architecture seccomp: %m");
d3b1c508
LP
1212
1213finish:
1214 seccomp_release(seccomp);
1215 return r;
1216#else
1217 return 0;
1218#endif
1219}
1220
b6e2f329
LP
1221static int status_welcome(void) {
1222 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1223 int r;
1224
1225 r = parse_env_file("/etc/os-release", NEWLINE,
1226 "PRETTY_NAME", &pretty_name,
1227 "ANSI_COLOR", &ansi_color,
1228 NULL);
ece174c5 1229 if (r == -ENOENT)
5ae4d543
LP
1230 r = parse_env_file("/usr/lib/os-release", NEWLINE,
1231 "PRETTY_NAME", &pretty_name,
1232 "ANSI_COLOR", &ansi_color,
1233 NULL);
b6e2f329
LP
1234
1235 if (r < 0 && r != -ENOENT)
da927ba9 1236 log_warning_errno(r, "Failed to read os-release file: %m");
b6e2f329 1237
dc9b5816
ZJS
1238 if (log_get_show_color())
1239 return status_printf(NULL, false, false,
1240 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1241 isempty(ansi_color) ? "1" : ansi_color,
1242 isempty(pretty_name) ? "Linux" : pretty_name);
1243 else
1244 return status_printf(NULL, false, false,
1245 "\nWelcome to %s!\n",
1246 isempty(pretty_name) ? "Linux" : pretty_name);
b6e2f329
LP
1247}
1248
fdd25311
LP
1249static int write_container_id(void) {
1250 const char *c;
19854865 1251 int r;
fdd25311
LP
1252
1253 c = getenv("container");
1254 if (isempty(c))
1255 return 0;
1256
8612da97
LP
1257 RUN_WITH_UMASK(0022)
1258 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1259 if (r < 0)
f1f849b0 1260 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1261
1262 return 1;
1263}
1264
1265static int bump_unix_max_dgram_qlen(void) {
1266 _cleanup_free_ char *qlen = NULL;
1267 unsigned long v;
1268 int r;
1269
1270 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel
1271 * default of 16 is simply too low. We set the value really
1272 * really early during boot, so that it is actually applied to
1273 * all our sockets, including the $NOTIFY_SOCKET one. */
1274
1275 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1276 if (r < 0)
1277 return log_warning_errno(r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1278
1279 r = safe_atolu(qlen, &v);
1280 if (r < 0)
1281 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length, ignoring: %m");
1282
1283 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1284 return 0;
1285
1286 qlen = mfree(qlen);
1287 if (asprintf(&qlen, "%lu\n", DEFAULT_UNIX_MAX_DGRAM_QLEN) < 0)
1288 return log_oom();
1289
1290 r = write_string_file("/proc/sys/net/unix/max_dgram_qlen", qlen, 0);
1291 if (r < 0)
1292 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1293 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1294
1295 return 1;
fdd25311
LP
1296}
1297
32391275
FB
1298static int fixup_environment(void) {
1299 _cleanup_free_ char *term = NULL;
1300 int r;
1301
84af7821
LP
1302 /* We expect the environment to be set correctly
1303 * if run inside a container. */
1304 if (detect_container() > 0)
1305 return 0;
1306
32391275
FB
1307 /* When started as PID1, the kernel uses /dev/console
1308 * for our stdios and uses TERM=linux whatever the
1309 * backend device used by the console. We try to make
1310 * a better guess here since some consoles might not
1311 * have support for color mode for example.
1312 *
1313 * However if TERM was configured through the kernel
1314 * command line then leave it alone. */
1315
1316 r = get_proc_cmdline_key("TERM=", &term);
1317 if (r < 0)
1318 return r;
1319
1320 if (r == 0) {
6af760f3 1321 term = strdup(default_term_for_tty("/dev/console"));
32391275 1322 if (!term)
84af7821 1323 return -ENOMEM;
32391275
FB
1324 }
1325
1326 if (setenv("TERM", term, 1) < 0)
1327 return -errno;
1328
1329 return 0;
1330}
1331
60918275
LP
1332int main(int argc, char *argv[]) {
1333 Manager *m = NULL;
22f4096c 1334 int r, retval = EXIT_FAILURE;
9d76d730
LP
1335 usec_t before_startup, after_startup;
1336 char timespan[FORMAT_TIMESPAN_MAX];
a16e1123
LP
1337 FDSet *fds = NULL;
1338 bool reexecute = false;
b9080b03 1339 const char *shutdown_verb = NULL;
86caf095
LP
1340 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL;
1341 dual_timestamp userspace_timestamp = DUAL_TIMESTAMP_NULL;
1342 dual_timestamp kernel_timestamp = DUAL_TIMESTAMP_NULL;
1343 dual_timestamp security_start_timestamp = DUAL_TIMESTAMP_NULL;
1344 dual_timestamp security_finish_timestamp = DUAL_TIMESTAMP_NULL;
5d6b1584 1345 static char systemd[] = "systemd";
2660882b 1346 bool skip_setup = false;
d3b1c508 1347 unsigned j;
0b3325e7 1348 bool loaded_policy = false;
e96d6be7 1349 bool arm_reboot_watchdog = false;
bf4df7c3 1350 bool queue_default_job = false;
5f5c2f38 1351 bool empty_etc = false;
41669317 1352 char *switch_root_dir = NULL, *switch_root_init = NULL;
86caf095 1353 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0);
cb6531be 1354 const char *error_message = NULL;
27b14a22 1355
058dc6f3 1356#ifdef HAVE_SYSV_COMPAT
2cb1a60d 1357 if (getpid() != 1 && strstr(program_invocation_short_name, "init")) {
35b8ca3a 1358 /* This is compatibility support for SysV, where
2cb1a60d
LP
1359 * calling init as a user is identical to telinit. */
1360
2cb1a60d 1361 execv(SYSTEMCTL_BINARY_PATH, argv);
56f64d95 1362 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
2cb1a60d
LP
1363 return 1;
1364 }
058dc6f3 1365#endif
2cb1a60d 1366
c3a170f3
HH
1367 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
1368 dual_timestamp_get(&userspace_timestamp);
1369
0b3325e7
LP
1370 /* Determine if this is a reexecution or normal bootup. We do
1371 * the full command line parsing much later, so let's just
1372 * have a quick peek here. */
db813c2a
LP
1373 if (strv_find(argv+1, "--deserialize"))
1374 skip_setup = true;
0b3325e7 1375
2660882b
LP
1376 /* If we have switched root, do all the special setup
1377 * things */
db813c2a
LP
1378 if (strv_find(argv+1, "--switched-root"))
1379 skip_setup = false;
d03bc1b8 1380
f3b6a3ed
LP
1381 /* If we get started via the /sbin/init symlink then we are
1382 called 'init'. After a subsequent reexecution we are then
1383 called 'systemd'. That is confusing, hence let's call us
1384 systemd right-away. */
f3b6a3ed
LP
1385 program_invocation_short_name = systemd;
1386 prctl(PR_SET_NAME, systemd);
5d6b1584 1387
9a0e6896
LP
1388 saved_argv = argv;
1389 saved_argc = argc;
f3b6a3ed 1390
c1dc6153 1391 log_set_upgrade_syslog_to_journal(true);
bbe63281 1392
90dc8c2e
MG
1393 /* Disable the umask logic */
1394 if (getpid() == 1)
1395 umask(0);
1396
75f86906 1397 if (getpid() == 1 && detect_container() <= 0) {
4f8d551f 1398
a866073d 1399 /* Running outside of a container as PID 1 */
463d0d15 1400 arg_system = true;
a866073d
LP
1401 log_set_target(LOG_TARGET_KMSG);
1402 log_open();
1403
21bf2ab0 1404 if (in_initrd())
c3a170f3 1405 initrd_timestamp = userspace_timestamp;
c3ba6250 1406
2660882b 1407 if (!skip_setup) {
d723cd65
AK
1408 r = mount_setup_early();
1409 if (r < 0) {
1410 error_message = "Failed to early mount API filesystems";
1411 goto finish;
1412 }
c2e0d600 1413 dual_timestamp_get(&security_start_timestamp);
cb6531be
ZJS
1414 if (mac_selinux_setup(&loaded_policy) < 0) {
1415 error_message = "Failed to load SELinux policy";
0b3325e7 1416 goto finish;
cb6531be
ZJS
1417 } else if (mac_smack_setup(&loaded_policy) < 0) {
1418 error_message = "Failed to load SMACK policy";
ffbd2c4d 1419 goto finish;
96694e99
IP
1420 } else if (ima_setup() < 0) {
1421 error_message = "Failed to load IMA policy";
1422 goto finish;
cb6531be 1423 }
c2e0d600 1424 dual_timestamp_get(&security_finish_timestamp);
81611586 1425 }
0b3325e7 1426
c3dacc8b 1427 if (mac_selinux_init() < 0) {
cb6531be 1428 error_message = "Failed to initialize SELinux policy";
0ff4cdd9 1429 goto finish;
cb6531be 1430 }
7948c4df 1431
72edcff5 1432 if (!skip_setup) {
6369641d 1433 if (clock_is_localtime(NULL) > 0) {
0b3325e7 1434 int min;
7948c4df 1435
c264aeab
KS
1436 /*
1437 * The very first call of settimeofday() also does a time warp in the kernel.
1438 *
1439 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on
1440 * external tools to take care of maintaining the RTC and do all adjustments.
1441 * This matches the behavior of Windows, which leaves the RTC alone if the
1442 * registry tells that the RTC runs in UTC.
1443 */
24efb112 1444 r = clock_set_timezone(&min);
0b3325e7 1445 if (r < 0)
da927ba9 1446 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
0b3325e7
LP
1447 else
1448 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
19e65613
KS
1449 } else if (!in_initrd()) {
1450 /*
c264aeab 1451 * Do a dummy very first call to seal the kernel's time warp magic.
19e65613 1452 *
61233823 1453 * Do not call this from inside the initrd. The initrd might not
19e65613
KS
1454 * carry /etc/adjtime with LOCAL, but the real system could be set up
1455 * that way. In such case, we need to delay the time-warp or the sealing
1456 * until we reach the real system.
c264aeab
KS
1457 *
1458 * Do no set the kernel's timezone. The concept of local time cannot
1459 * be supported reliably, the time will jump or be incorrect at every daylight
1460 * saving time change. All kernel local time concepts will be treated
1461 * as UTC that way.
19e65613 1462 */
021dd87b 1463 (void) clock_reset_timewarp();
72edcff5 1464 }
021dd87b
LP
1465
1466 r = clock_apply_epoch();
1467 if (r < 0)
1468 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1469 else if (r > 0)
1470 log_info("System time before build time, advancing clock.");
72edcff5 1471 }
a866073d
LP
1472
1473 /* Set the default for later on, but don't actually
1474 * open the logs like this for now. Note that if we
1475 * are transitioning from the initrd there might still
1476 * be journal fd open, and we shouldn't attempt
1477 * opening that before we parsed /proc/cmdline which
1478 * might redirect output elsewhere. */
1479 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
1480
1481 } else if (getpid() == 1) {
a866073d 1482 /* Running inside a container, as PID 1 */
463d0d15 1483 arg_system = true;
a866073d 1484 log_set_target(LOG_TARGET_CONSOLE);
99f09825 1485 log_close_console(); /* force reopen of /dev/console */
a866073d
LP
1486 log_open();
1487
1488 /* For the later on, see above... */
1489 log_set_target(LOG_TARGET_JOURNAL);
1490
c3a170f3
HH
1491 /* clear the kernel timestamp,
1492 * because we are in a container */
0f5f63c3 1493 kernel_timestamp = DUAL_TIMESTAMP_NULL;
c3a170f3 1494 } else {
a866073d 1495 /* Running as user instance */
463d0d15 1496 arg_system = false;
eeecf6e6 1497 log_set_target(LOG_TARGET_AUTO);
871e5809 1498 log_open();
c3a170f3
HH
1499
1500 /* clear the kernel timestamp,
1501 * because we are not PID 1 */
6513d561 1502 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 1503 }
a5dab5ce 1504
15a90032
LP
1505 if (getpid() == 1) {
1506 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1507 * will process core dumps for system services by default. */
206fc4b2
ZJS
1508 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1509 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
15a90032
LP
1510
1511 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1512 * until the systemd-coredump tool is enabled via sysctl. */
1513 if (!skip_setup)
1514 (void) write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", 0);
1515 }
1516
6edefe0b 1517 if (arg_system) {
84af7821
LP
1518 if (fixup_environment() < 0) {
1519 error_message = "Failed to fix up PID1 environment";
1520 goto finish;
1521 }
32391275 1522
3a18b604
FB
1523 /* Try to figure out if we can use colors with the console. No
1524 * need to do that for user instances since they never log
1525 * into the console. */
1526 log_show_color(colors_enabled());
1527 make_null_stdio();
1528 }
1529
0c85a4f3 1530 /* Initialize default unit */
e6e242ad 1531 r = free_and_strdup(&arg_default_unit, SPECIAL_DEFAULT_TARGET);
6afa301b 1532 if (r < 0) {
da927ba9 1533 log_emergency_errno(r, "Failed to set default unit %s: %m", SPECIAL_DEFAULT_TARGET);
cb6531be 1534 error_message = "Failed to set default unit";
f170852a 1535 goto finish;
14212119 1536 }
60918275 1537
a07fdfa3 1538 r = initialize_join_controllers();
cb6531be 1539 if (r < 0) {
ff9b60f3 1540 error_message = "Failed to initialize cgroup controllers";
0c85a4f3 1541 goto finish;
cb6531be 1542 }
0c85a4f3 1543
f170852a
LP
1544 /* Mount /proc, /sys and friends, so that /proc/cmdline and
1545 * /proc/$PID/fd is available. */
c1dae1b3 1546 if (getpid() == 1) {
f84f9974
LP
1547
1548 /* Load the kernel modules early, so that we kdbus.ko is loaded before kdbusfs shall be mounted */
2e75e2a8
DM
1549 if (!skip_setup)
1550 kmod_setup();
2e75e2a8 1551
0c85a4f3 1552 r = mount_setup(loaded_policy);
cb6531be
ZJS
1553 if (r < 0) {
1554 error_message = "Failed to mount API filesystems";
8efe3c01 1555 goto finish;
cb6531be 1556 }
0c85a4f3 1557 }
4ade7963
LP
1558
1559 /* Reset all signal handlers. */
ce30c8dc
LP
1560 (void) reset_all_signal_handlers();
1561 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 1562
f5058264 1563 arg_default_tasks_max = system_tasks_max_scale(DEFAULT_TASKS_MAX_PERCENTAGE, 100U);
79baeeb9 1564
cb6531be
ZJS
1565 if (parse_config_file() < 0) {
1566 error_message = "Failed to parse config file";
487393e9 1567 goto finish;
cb6531be 1568 }
487393e9 1569
463d0d15 1570 if (arg_system) {
b5884878
LP
1571 r = parse_proc_cmdline(parse_proc_cmdline_item);
1572 if (r < 0)
da927ba9 1573 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
b5884878 1574 }
f170852a 1575
1de1c9c3
LP
1576 /* Note that this also parses bits from the kernel command
1577 * line, including "debug". */
f170852a
LP
1578 log_parse_environment();
1579
cb6531be
ZJS
1580 if (parse_argv(argc, argv) < 0) {
1581 error_message = "Failed to parse commandline arguments";
f170852a 1582 goto finish;
cb6531be 1583 }
f170852a 1584
6bae23a0
TB
1585 if (arg_action == ACTION_TEST &&
1586 geteuid() == 0) {
b5c6cf87
LP
1587 log_error("Don't run test mode as root.");
1588 goto finish;
1589 }
1590
463d0d15 1591 if (!arg_system &&
6bae23a0
TB
1592 arg_action == ACTION_RUN &&
1593 sd_booted() <= 0) {
1594 log_error("Trying to run as user instance, but the system has not been booted with systemd.");
1595 goto finish;
1596 }
1597
463d0d15 1598 if (arg_system &&
fe783b03
LP
1599 arg_action == ACTION_RUN &&
1600 running_in_chroot() > 0) {
1601 log_error("Cannot be run in a chroot() environment.");
1602 goto finish;
1603 }
1604
0d8c31ff
ZJS
1605 if (arg_action == ACTION_TEST)
1606 skip_setup = true;
1607
ea4b98e6
AK
1608 if (arg_action == ACTION_TEST || arg_action == ACTION_HELP)
1609 pager_open(arg_no_pager, false);
b87c2aa6 1610
fa0f4d8a 1611 if (arg_action == ACTION_HELP) {
f170852a
LP
1612 retval = help();
1613 goto finish;
9ba0bc4e
ZJS
1614 } else if (arg_action == ACTION_VERSION) {
1615 retval = version();
1616 goto finish;
fa0f4d8a 1617 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
13811bf9 1618 pager_open(arg_no_pager, false);
e537352b 1619 unit_dump_config_items(stdout);
22f4096c 1620 retval = EXIT_SUCCESS;
e537352b 1621 goto finish;
f170852a
LP
1622 }
1623
463d0d15 1624 if (!arg_system &&
8be28fb1
KS
1625 !getenv("XDG_RUNTIME_DIR")) {
1626 log_error("Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
1627 goto finish;
1628 }
1629
fa0f4d8a 1630 assert_se(arg_action == ACTION_RUN || arg_action == ACTION_TEST);
f170852a 1631
871e5809
LP
1632 /* Close logging fds, in order not to confuse fdset below */
1633 log_close();
1634
a16e1123 1635 /* Remember open file descriptors for later deserialization */
01e10de3
LP
1636 r = fdset_new_fill(&fds);
1637 if (r < 0) {
da927ba9 1638 log_emergency_errno(r, "Failed to allocate fd set: %m");
cb6531be 1639 error_message = "Failed to allocate fd set";
01e10de3
LP
1640 goto finish;
1641 } else
1642 fdset_cloexec(fds, true);
a16e1123 1643
d3b1c508
LP
1644 if (arg_serialization)
1645 assert_se(fdset_remove(fds, fileno(arg_serialization)) >= 0);
a16e1123 1646
463d0d15 1647 if (arg_system)
80876c20
LP
1648 /* Become a session leader if we aren't one yet. */
1649 setsid();
4ade7963 1650
befb5b6a 1651 /* Move out of the way, so that we won't block unmounts */
d250afe7 1652 assert_se(chdir("/") == 0);
befb5b6a 1653
2146621b
LP
1654 /* Reset the console, but only if this is really init and we
1655 * are freshly booted */
463d0d15 1656 if (arg_system && arg_action == ACTION_RUN) {
56d96fc0
LP
1657
1658 /* If we are init, we connect stdin/stdout/stderr to
1659 * /dev/null and make sure we don't have a controlling
1660 * tty. */
1661 release_terminal();
1662
1663 if (getpid() == 1 && !skip_setup)
1664 console_setup();
1665 }
4ade7963 1666
18149b9f 1667 /* Open the logging devices, if possible and necessary */
843d2643 1668 log_open();
4ade7963 1669
b6e2f329
LP
1670 if (arg_show_status == _SHOW_STATUS_UNSET)
1671 arg_show_status = SHOW_STATUS_YES;
1672
5373d602
LP
1673 /* Make sure we leave a core dump without panicing the
1674 * kernel. */
ab422445 1675 if (getpid() == 1) {
4fc935ca 1676 install_crash_handler();
97c4f35c 1677
0c85a4f3
LP
1678 r = mount_cgroup_controllers(arg_join_controllers);
1679 if (r < 0)
1680 goto finish;
1681 }
1682
463d0d15 1683 if (arg_system) {
75f86906 1684 int v;
c20f5ac7 1685
0d8c31ff
ZJS
1686 log_info(PACKAGE_STRING " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
1687 arg_action == ACTION_TEST ? "test " : "" );
c20f5ac7 1688
75f86906
LP
1689 v = detect_virtualization();
1690 if (v > 0)
1691 log_info("Detected virtualization %s.", virtualization_to_string(v));
c20f5ac7 1692
fdd25311
LP
1693 write_container_id();
1694
d3f86679 1695 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
d9d93745 1696
26a1efdf
LP
1697 if (in_initrd())
1698 log_info("Running in initial RAM disk.");
1699
3408ba01
LP
1700 /* Let's check whether /etc is already populated. We
1701 * don't actually really check for that, but use
1702 * /etc/machine-id as flag file. This allows container
1703 * managers and installers to provision a couple of
1704 * files already. If the container manager wants to
1705 * provision the machine ID itself it should pass
ee33e53a 1706 * $container_uuid to PID 1. */
3408ba01 1707
baa1bdf7 1708 empty_etc = access("/etc/machine-id", F_OK) < 0;
5f5c2f38
LP
1709 if (empty_etc)
1710 log_info("Running with unpopulated /etc.");
d8160f21 1711 } else {
1f97091d
LP
1712 _cleanup_free_ char *t;
1713
1714 t = uid_to_name(getuid());
0d8c31ff
ZJS
1715 log_debug(PACKAGE_STRING " running in %suser mode for user "UID_FMT"/%s. (" SYSTEMD_FEATURES ")",
1716 arg_action == ACTION_TEST ? " test" : "", getuid(), t);
d8160f21 1717 }
a5dab5ce 1718
463d0d15 1719 if (arg_system && !skip_setup) {
031886ed 1720 if (arg_show_status > 0)
888c6216
LP
1721 status_welcome();
1722
888c6216 1723 hostname_setup();
4b1afed0 1724 machine_id_setup(NULL, arg_machine_id, NULL);
888c6216 1725 loopback_setup();
19854865 1726 bump_unix_max_dgram_qlen();
490aed58 1727
80758717 1728 test_usr();
af5bc85d 1729 }
302e8c4c 1730
463d0d15 1731 if (arg_system && arg_runtime_watchdog > 0 && arg_runtime_watchdog != USEC_INFINITY)
e96d6be7
LP
1732 watchdog_set_timeout(&arg_runtime_watchdog);
1733
3a43da28 1734 if (arg_timer_slack_nsec != NSEC_INFINITY)
aa0f64ac 1735 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
56f64d95 1736 log_error_errno(errno, "Failed to adjust timer slack: %m");
aa0f64ac 1737
a103496c
IP
1738 if (!cap_test_all(arg_capability_bounding_set)) {
1739 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
ec8927ca 1740 if (r < 0) {
da927ba9 1741 log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
cb6531be 1742 error_message = "Failed to drop capability bounding set of usermode helpers";
ec8927ca
LP
1743 goto finish;
1744 }
a103496c 1745 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
939b8f14 1746 if (r < 0) {
da927ba9 1747 log_emergency_errno(r, "Failed to drop capability bounding set: %m");
cb6531be 1748 error_message = "Failed to drop capability bounding set";
939b8f14
LP
1749 goto finish;
1750 }
ec8927ca
LP
1751 }
1752
d3b1c508
LP
1753 if (arg_syscall_archs) {
1754 r = enforce_syscall_archs(arg_syscall_archs);
cb6531be
ZJS
1755 if (r < 0) {
1756 error_message = "Failed to set syscall architectures";
d3b1c508 1757 goto finish;
cb6531be 1758 }
d3b1c508
LP
1759 }
1760
463d0d15 1761 if (!arg_system)
d4447f4d 1762 /* Become reaper of our children */
61b9b203 1763 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
56f64d95 1764 log_warning_errno(errno, "Failed to make us a subreaper: %m");
d4447f4d 1765
463d0d15 1766 if (arg_system) {
4096d6f5
LP
1767 bump_rlimit_nofile(&saved_rlimit_nofile);
1768
5f5c2f38 1769 if (empty_etc) {
304b3079 1770 r = unit_file_preset_all(UNIT_FILE_SYSTEM, false, NULL, UNIT_FILE_PRESET_ENABLE_ONLY, false, NULL, 0);
5f5c2f38 1771 if (r < 0)
287a0de4 1772 log_full_errno(r == -EEXIST ? LOG_NOTICE : LOG_WARNING, r, "Failed to populate /etc with preset unit settings, ignoring: %m");
5f5c2f38
LP
1773 else
1774 log_info("Populated /etc with preset unit settings.");
1775 }
1776 }
1777
463d0d15 1778 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER, arg_action == ACTION_TEST, &m);
e96d6be7 1779 if (r < 0) {
da927ba9 1780 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 1781 error_message = "Failed to allocate manager object";
60918275
LP
1782 goto finish;
1783 }
1784
9e58ff9c 1785 m->confirm_spawn = arg_confirm_spawn;
e96d6be7
LP
1786 m->runtime_watchdog = arg_runtime_watchdog;
1787 m->shutdown_watchdog = arg_shutdown_watchdog;
c3a170f3
HH
1788 m->userspace_timestamp = userspace_timestamp;
1789 m->kernel_timestamp = kernel_timestamp;
c3a170f3 1790 m->initrd_timestamp = initrd_timestamp;
c2e0d600
TA
1791 m->security_start_timestamp = security_start_timestamp;
1792 m->security_finish_timestamp = security_finish_timestamp;
9e58ff9c 1793
06af2a04 1794 manager_set_defaults(m);
27d340c7 1795 manager_set_show_status(m, arg_show_status);
e2680723 1796 manager_set_first_boot(m, empty_etc);
27d340c7 1797
bf4df7c3 1798 /* Remember whether we should queue the default job */
d3b1c508 1799 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 1800
9d76d730
LP
1801 before_startup = now(CLOCK_MONOTONIC);
1802
d3b1c508 1803 r = manager_startup(m, arg_serialization, fds);
e96d6be7 1804 if (r < 0)
da927ba9 1805 log_error_errno(r, "Failed to fully start up daemon: %m");
a16e1123 1806
bf4df7c3
LP
1807 /* This will close all file descriptors that were opened, but
1808 * not claimed by any unit. */
2feceb5e 1809 fds = fdset_free(fds);
f50e0a01 1810
74ca738f 1811 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
1812
1813 if (queue_default_job) {
4afd3348 1814 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1c27d3f3 1815 Unit *target = NULL;
bacbccb7 1816 Job *default_unit_job;
398ef8ba 1817
fa0f4d8a 1818 log_debug("Activating default unit: %s", arg_default_unit);
a16e1123 1819
e96d6be7 1820 r = manager_load_unit(m, arg_default_unit, NULL, &error, &target);
718db961
LP
1821 if (r < 0)
1822 log_error("Failed to load default target: %s", bus_error_message(&error, r));
1823 else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND)
c33b3297 1824 log_error_errno(target->load_error, "Failed to load default target: %m");
ac155bb8 1825 else if (target->load_state == UNIT_MASKED)
6daf4f90 1826 log_error("Default target masked.");
27b14a22 1827
ac155bb8 1828 if (!target || target->load_state != UNIT_LOADED) {
a16e1123 1829 log_info("Trying to load rescue target...");
1c27d3f3 1830
e96d6be7
LP
1831 r = manager_load_unit(m, SPECIAL_RESCUE_TARGET, NULL, &error, &target);
1832 if (r < 0) {
4104970e 1833 log_emergency("Failed to load rescue target: %s", bus_error_message(&error, r));
cb6531be 1834 error_message = "Failed to load rescue target";
a16e1123 1835 goto finish;
11ddb6f4 1836 } else if (target->load_state == UNIT_ERROR || target->load_state == UNIT_NOT_FOUND) {
c33b3297 1837 log_emergency_errno(target->load_error, "Failed to load rescue target: %m");
cb6531be 1838 error_message = "Failed to load rescue target";
1c27d3f3 1839 goto finish;
ac155bb8 1840 } else if (target->load_state == UNIT_MASKED) {
4104970e 1841 log_emergency("Rescue target masked.");
cb6531be 1842 error_message = "Rescue target masked";
00dc5d76 1843 goto finish;
a16e1123
LP
1844 }
1845 }
37d88da7 1846
ac155bb8 1847 assert(target->load_state == UNIT_LOADED);
00dc5d76 1848
fa0f4d8a 1849 if (arg_action == ACTION_TEST) {
40d50879 1850 printf("-> By units:\n");
a16e1123
LP
1851 manager_dump_units(m, stdout, "\t");
1852 }
1853
4bd29fe5 1854 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, &error, &default_unit_job);
ab17a050 1855 if (r == -EPERM) {
718db961 1856 log_debug("Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
ab17a050 1857
5022ce71
LP
1858 sd_bus_error_free(&error);
1859
4bd29fe5 1860 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, &error, &default_unit_job);
ab17a050 1861 if (r < 0) {
4104970e 1862 log_emergency("Failed to start default target: %s", bus_error_message(&error, r));
cb6531be 1863 error_message = "Failed to start default target";
ab17a050
LP
1864 goto finish;
1865 }
1866 } else if (r < 0) {
4104970e 1867 log_emergency("Failed to isolate default target: %s", bus_error_message(&error, r));
cb6531be 1868 error_message = "Failed to isolate default target";
37d88da7
LP
1869 goto finish;
1870 }
ab17a050 1871
bacbccb7 1872 m->default_unit_job_id = default_unit_job->id;
60918275 1873
07672f49
LP
1874 after_startup = now(CLOCK_MONOTONIC);
1875 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
1876 "Loaded units and determined initial transaction in %s.",
fdb14b7e 1877 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 1878
fa0f4d8a 1879 if (arg_action == ACTION_TEST) {
40d50879 1880 printf("-> By jobs:\n");
a16e1123 1881 manager_dump_jobs(m, stdout, "\t");
22f4096c 1882 retval = EXIT_SUCCESS;
a16e1123
LP
1883 goto finish;
1884 }
e965d56d 1885 }
d46de8a1 1886
a16e1123 1887 for (;;) {
e96d6be7
LP
1888 r = manager_loop(m);
1889 if (r < 0) {
da927ba9 1890 log_emergency_errno(r, "Failed to run main loop: %m");
cb6531be 1891 error_message = "Failed to run main loop";
a16e1123
LP
1892 goto finish;
1893 }
11dd41ce 1894
a16e1123 1895 switch (m->exit_code) {
e965d56d 1896
a16e1123 1897 case MANAGER_RELOAD:
e015090f 1898 log_info("Reloading.");
06af2a04
TB
1899
1900 r = parse_config_file();
1901 if (r < 0)
1902 log_error("Failed to parse config file.");
1903
1904 manager_set_defaults(m);
1905
e96d6be7
LP
1906 r = manager_reload(m);
1907 if (r < 0)
da927ba9 1908 log_error_errno(r, "Failed to reload: %m");
a16e1123 1909 break;
cea8e32e 1910
a16e1123 1911 case MANAGER_REEXECUTE:
664f88a7 1912
cb6531be 1913 if (prepare_reexecute(m, &arg_serialization, &fds, false) < 0) {
6b9af963 1914 error_message = "Failed to prepare for reexecution";
a16e1123 1915 goto finish;
cb6531be 1916 }
60918275 1917
a16e1123 1918 reexecute = true;
e015090f 1919 log_notice("Reexecuting.");
a16e1123
LP
1920 goto finish;
1921
664f88a7
LP
1922 case MANAGER_SWITCH_ROOT:
1923 /* Steal the switch root parameters */
41669317 1924 switch_root_dir = m->switch_root;
664f88a7
LP
1925 switch_root_init = m->switch_root_init;
1926 m->switch_root = m->switch_root_init = NULL;
1927
1928 if (!switch_root_init)
cb6531be 1929 if (prepare_reexecute(m, &arg_serialization, &fds, true) < 0) {
6b9af963 1930 error_message = "Failed to prepare for reexecution";
664f88a7 1931 goto finish;
cb6531be 1932 }
664f88a7
LP
1933
1934 reexecute = true;
1935 log_notice("Switching root.");
1936 goto finish;
1937
287419c1 1938 case MANAGER_EXIT:
97792515
LP
1939 retval = m->return_value;
1940
463d0d15 1941 if (MANAGER_IS_USER(m)) {
8ebfe0cb
DH
1942 log_debug("Exit.");
1943 goto finish;
1944 }
1945
1946 /* fallthrough */
b9080b03
FF
1947 case MANAGER_REBOOT:
1948 case MANAGER_POWEROFF:
1949 case MANAGER_HALT:
1950 case MANAGER_KEXEC: {
1951 static const char * const table[_MANAGER_EXIT_CODE_MAX] = {
287419c1 1952 [MANAGER_EXIT] = "exit",
b9080b03
FF
1953 [MANAGER_REBOOT] = "reboot",
1954 [MANAGER_POWEROFF] = "poweroff",
1955 [MANAGER_HALT] = "halt",
1956 [MANAGER_KEXEC] = "kexec"
1957 };
1958
1959 assert_se(shutdown_verb = table[m->exit_code]);
e96d6be7 1960 arm_reboot_watchdog = m->exit_code == MANAGER_REBOOT;
b9080b03
FF
1961
1962 log_notice("Shutting down.");
1963 goto finish;
1964 }
1965
a16e1123
LP
1966 default:
1967 assert_not_reached("Unknown exit code.");
1968 }
1969 }
f170852a 1970
60918275 1971finish:
b87c2aa6
ZJS
1972 pager_close();
1973
97792515 1974 if (m)
81f5fc2d 1975 arg_shutdown_watchdog = m->shutdown_watchdog;
fe382237 1976
06d8d842 1977 m = manager_free(m);
60918275 1978
1f6b4113 1979 for (j = 0; j < ELEMENTSOF(arg_default_rlimit); j++)
a1e58e8e 1980 arg_default_rlimit[j] = mfree(arg_default_rlimit[j]);
c93ff2e9 1981
97b11eed 1982 arg_default_unit = mfree(arg_default_unit);
fe382237 1983 arg_join_controllers = strv_free_free(arg_join_controllers);
97b11eed 1984 arg_default_environment = strv_free(arg_default_environment);
525d3cc7 1985 arg_syscall_archs = set_free(arg_syscall_archs);
d3b1c508 1986
cc56fafe 1987 mac_selinux_finish();
b2bb3dbe 1988
a16e1123 1989 if (reexecute) {
664f88a7 1990 const char **args;
e564a982 1991 unsigned i, args_size;
a16e1123 1992
664f88a7
LP
1993 /* Close and disarm the watchdog, so that the new
1994 * instance can reinitialize it, but doesn't get
1995 * rebooted while we do that */
1996 watchdog_close(true);
a16e1123 1997
4096d6f5
LP
1998 /* Reset the RLIMIT_NOFILE to the kernel default, so
1999 * that the new systemd can pass the kernel default to
2000 * its child processes */
2001 if (saved_rlimit_nofile.rlim_cur > 0)
92ca4cac 2002 (void) setrlimit(RLIMIT_NOFILE, &saved_rlimit_nofile);
4096d6f5 2003
41669317 2004 if (switch_root_dir) {
cee530bb
LP
2005 /* Kill all remaining processes from the
2006 * initrd, but don't wait for them, so that we
2007 * can handle the SIGCHLD for them after
2008 * deserializing. */
0bee65f0 2009 broadcast_signal(SIGTERM, false, true);
bd3fa1d2 2010
5a4bf02f
HH
2011 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
2012 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
41669317 2013 if (r < 0)
da927ba9 2014 log_error_errno(r, "Failed to switch root, trying to continue: %m");
41669317 2015 }
a16e1123 2016
d03bc1b8 2017 args_size = MAX(6, argc+1);
e564a982 2018 args = newa(const char*, args_size);
a16e1123 2019
664f88a7 2020 if (!switch_root_init) {
5ffa8c81 2021 char sfd[DECIMAL_STR_MAX(int) + 1];
a16e1123 2022
664f88a7
LP
2023 /* First try to spawn ourselves with the right
2024 * path, and with full serialization. We do
2025 * this only if the user didn't specify an
2026 * explicit init to spawn. */
edb9aaa8 2027
d3b1c508 2028 assert(arg_serialization);
664f88a7 2029 assert(fds);
edb9aaa8 2030
5ffa8c81 2031 xsprintf(sfd, "%i", fileno(arg_serialization));
edb9aaa8 2032
664f88a7
LP
2033 i = 0;
2034 args[i++] = SYSTEMD_BINARY_PATH;
41669317 2035 if (switch_root_dir)
2660882b 2036 args[i++] = "--switched-root";
463d0d15 2037 args[i++] = arg_system ? "--system" : "--user";
664f88a7
LP
2038 args[i++] = "--deserialize";
2039 args[i++] = sfd;
2040 args[i++] = NULL;
edb9aaa8 2041
e564a982 2042 assert(i <= args_size);
dcadc967
EV
2043
2044 /*
2045 * We want valgrind to print its memory usage summary before reexecution.
2046 * Valgrind won't do this is on its own on exec(), but it will do it on exit().
2047 * Hence, to ensure we get a summary here, fork() off a child, let it exit() cleanly,
2048 * so that it prints the summary, and wait() for it in the parent, before proceeding into the exec().
2049 */
2050 valgrind_summary_hack();
2051
92ca4cac 2052 (void) execv(args[0], (char* const*) args);
664f88a7 2053 }
6e98720f 2054
664f88a7
LP
2055 /* Try the fallback, if there is any, without any
2056 * serialization. We pass the original argv[] and
2057 * envp[]. (Well, modulo the ordering changes due to
2058 * getopt() in argv[], and some cleanups in envp[],
2059 * but let's hope that doesn't matter.) */
a16e1123 2060
74ca738f 2061 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2062 fds = fdset_free(fds);
a16e1123 2063
bd64d82c
ZJS
2064 /* Reopen the console */
2065 (void) make_console_stdio();
2066
d3b1c508 2067 for (j = 1, i = 1; j < (unsigned) argc; j++)
664f88a7 2068 args[i++] = argv[j];
a16e1123 2069 args[i++] = NULL;
e564a982 2070 assert(i <= args_size);
b8f83232 2071
1b6d7fa7 2072 /* Reenable any blocked signals, especially important
5a85ca1c 2073 * if we switch from initial ramdisk to init=... */
ce30c8dc
LP
2074 (void) reset_all_signal_handlers();
2075 (void) reset_signal_mask();
5a85ca1c 2076
b8f83232
LP
2077 if (switch_root_init) {
2078 args[0] = switch_root_init;
92ca4cac 2079 (void) execv(args[0], (char* const*) args);
56f64d95 2080 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
b8f83232
LP
2081 }
2082
2083 args[0] = "/sbin/init";
92ca4cac 2084 (void) execv(args[0], (char* const*) args);
a16e1123 2085
745e2fb7
KS
2086 if (errno == ENOENT) {
2087 log_warning("No /sbin/init, trying fallback");
b8f83232 2088
745e2fb7
KS
2089 args[0] = "/bin/sh";
2090 args[1] = NULL;
92ca4cac 2091 (void) execv(args[0], (char* const*) args);
56f64d95 2092 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
745e2fb7 2093 } else
56f64d95 2094 log_warning_errno(errno, "Failed to execute /sbin/init, giving up: %m");
a16e1123
LP
2095 }
2096
74ca738f 2097 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2098 fds = fdset_free(fds);
a16e1123 2099
54b434b1
LP
2100#ifdef HAVE_VALGRIND_VALGRIND_H
2101 /* If we are PID 1 and running under valgrind, then let's exit
2102 * here explicitly. valgrind will only generate nice output on
2103 * exit(), not on exec(), hence let's do the former not the
2104 * latter here. */
2105 if (getpid() == 1 && RUNNING_ON_VALGRIND)
2106 return 0;
2107#endif
2108
b9080b03 2109 if (shutdown_verb) {
b1e90ec5 2110 char log_level[DECIMAL_STR_MAX(int) + 1];
287419c1
AC
2111 char exit_code[DECIMAL_STR_MAX(uint8_t) + 1];
2112 const char* command_line[11] = {
b9080b03
FF
2113 SYSTEMD_SHUTDOWN_BINARY_PATH,
2114 shutdown_verb,
b1e90ec5
ZJS
2115 "--log-level", log_level,
2116 "--log-target",
b9080b03 2117 };
b1e90ec5 2118 unsigned pos = 5;
e3e45d4f 2119 _cleanup_strv_free_ char **env_block = NULL;
15bd5aee
LP
2120
2121 assert(command_line[pos] == NULL);
e3e45d4f 2122 env_block = strv_copy(environ);
b9080b03 2123
5ffa8c81 2124 xsprintf(log_level, "%d", log_get_max_level());
b1e90ec5
ZJS
2125
2126 switch (log_get_target()) {
92ca4cac 2127
b1e90ec5
ZJS
2128 case LOG_TARGET_KMSG:
2129 case LOG_TARGET_JOURNAL_OR_KMSG:
2130 case LOG_TARGET_SYSLOG_OR_KMSG:
2131 command_line[pos++] = "kmsg";
2132 break;
2133
10f00ff1
ILG
2134 case LOG_TARGET_NULL:
2135 command_line[pos++] = "null";
2136 break;
2137
b1e90ec5
ZJS
2138 case LOG_TARGET_CONSOLE:
2139 default:
2140 command_line[pos++] = "console";
2141 break;
2142 };
2143
2144 if (log_get_show_color())
2145 command_line[pos++] = "--log-color";
2146
2147 if (log_get_show_location())
2148 command_line[pos++] = "--log-location";
2149
287419c1
AC
2150 if (streq(shutdown_verb, "exit")) {
2151 command_line[pos++] = "--exit-code";
2152 command_line[pos++] = exit_code;
97792515 2153 xsprintf(exit_code, "%d", retval);
287419c1
AC
2154 }
2155
26abdc73 2156 assert(pos < ELEMENTSOF(command_line));
b1e90ec5 2157
5146c619 2158 if (arm_reboot_watchdog && arg_shutdown_watchdog > 0 && arg_shutdown_watchdog != USEC_INFINITY) {
e3e45d4f 2159 char *e;
d18f337c 2160
e96d6be7
LP
2161 /* If we reboot let's set the shutdown
2162 * watchdog and tell the shutdown binary to
2163 * repeatedly ping it */
c2cc6b9a
LP
2164 r = watchdog_set_timeout(&arg_shutdown_watchdog);
2165 watchdog_close(r < 0);
e96d6be7 2166
e3e45d4f
SP
2167 /* Tell the binary how often to ping, ignore failure */
2168 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, arg_shutdown_watchdog) > 0)
92ca4cac 2169 (void) strv_push(&env_block, e);
e3e45d4f 2170 } else
e96d6be7
LP
2171 watchdog_close(true);
2172
66713f77
LP
2173 /* Avoid the creation of new processes forked by the
2174 * kernel; at this point, we will not listen to the
2175 * signals anyway */
75f86906 2176 if (detect_container() <= 0)
e155a0aa 2177 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
ad929bcc 2178
d18f337c 2179 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
56f64d95 2180 log_error_errno(errno, "Failed to execute shutdown binary, %s: %m",
b1e90ec5 2181 getpid() == 1 ? "freezing" : "quitting");
b9080b03
FF
2182 }
2183
cb6531be
ZJS
2184 if (getpid() == 1) {
2185 if (error_message)
2186 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 2187 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
cb6531be 2188 "%s, freezing.", error_message);
b9e74c39 2189 freeze_or_reboot();
cb6531be 2190 }
c3b3c274 2191
60918275
LP
2192 return retval;
2193}