]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
pid1: when showing error status, do not switch to status=temporary
[thirdparty/systemd.git] / src / core / main.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
a7334b09 2
60918275 3#include <errno.h>
3dfc9763 4#include <fcntl.h>
f170852a 5#include <getopt.h>
664f88a7 6#include <sys/mount.h>
3dfc9763 7#include <sys/prctl.h>
b9e74c39 8#include <sys/reboot.h>
3dfc9763 9#include <unistd.h>
349cc4a5 10#if HAVE_SECCOMP
b64a3d86
LP
11#include <seccomp.h>
12#endif
349cc4a5 13#if HAVE_VALGRIND_VALGRIND_H
3dfc9763
LP
14#include <valgrind/valgrind.h>
15#endif
54b434b1 16
718db961 17#include "sd-bus.h"
cf0fbc49 18#include "sd-daemon.h"
b2e7486c 19#include "sd-messages.h"
3dfc9763 20
b5efdb8a 21#include "alloc-util.h"
d9d93745 22#include "architecture.h"
3dfc9763
LP
23#include "build.h"
24#include "bus-error.h"
25#include "bus-util.h"
430f0182 26#include "capability-util.h"
a88c5b8a 27#include "cgroup-util.h"
24efb112 28#include "clock-util.h"
3dfc9763 29#include "conf-parser.h"
618234a5 30#include "cpu-set-util.h"
3dfc9763 31#include "dbus-manager.h"
c18ecf03 32#include "dbus.h"
3dfc9763 33#include "def.h"
c18ecf03 34#include "efi-random.h"
eee8b7ab 35#include "emergency-action.h"
3dfc9763 36#include "env-util.h"
57b7a260 37#include "exit-status.h"
3ffd4af2 38#include "fd-util.h"
3dfc9763 39#include "fdset.h"
718db961 40#include "fileio.h"
f97b34a6 41#include "format-util.h"
f4f15635 42#include "fs-util.h"
3dfc9763
LP
43#include "hostname-setup.h"
44#include "ima-setup.h"
45#include "killall.h"
46#include "kmod-setup.h"
eefc66aa 47#include "limits-util.h"
d7b8eec7 48#include "load-fragment.h"
3dfc9763 49#include "log.h"
b6e66135 50#include "loopback-setup.h"
b6e66135 51#include "machine-id-setup.h"
3dfc9763 52#include "manager.h"
3dfc9763 53#include "mount-setup.h"
d58ad743 54#include "os-util.h"
3dfc9763 55#include "pager.h"
6bedfcbb 56#include "parse-util.h"
7d5ceb64 57#include "path-util.h"
294bf0c3 58#include "pretty-print.h"
4e731273 59#include "proc-cmdline.h"
3dfc9763 60#include "process-util.h"
8869a0b4 61#include "raw-clone.h"
78f22b97 62#include "rlimit-util.h"
349cc4a5 63#if HAVE_SECCOMP
83f12b27
FS
64#include "seccomp-util.h"
65#endif
b6e66135 66#include "selinux-setup.h"
3dfc9763
LP
67#include "selinux-util.h"
68#include "signal-util.h"
ffbd2c4d 69#include "smack-setup.h"
3dfc9763 70#include "special.h"
8fcde012 71#include "stat-util.h"
15a5e950 72#include "stdio-util.h"
3dfc9763
LP
73#include "strv.h"
74#include "switch-root.h"
a8b627aa 75#include "sysctl-util.h"
3dfc9763 76#include "terminal-util.h"
8612da97 77#include "umask-util.h"
b1d4f8e1 78#include "user-util.h"
9ce17593 79#include "util.h"
3dfc9763
LP
80#include "virt.h"
81#include "watchdog.h"
b6e66135 82
7e11a95e
EV
83#if HAS_FEATURE_ADDRESS_SANITIZER
84#include <sanitizer/lsan_interface.h>
85#endif
86
3a0f06c4
ZJS
87#define DEFAULT_TASKS_MAX ((TasksMax) { 15U, 100U }) /* 15% */
88
f170852a
LP
89static enum {
90 ACTION_RUN,
e965d56d 91 ACTION_HELP,
9ba0bc4e 92 ACTION_VERSION,
e537352b 93 ACTION_TEST,
bbc1acab
YW
94 ACTION_DUMP_CONFIGURATION_ITEMS,
95 ACTION_DUMP_BUS_PROPERTIES,
fa0f4d8a 96} arg_action = ACTION_RUN;
fb39af4c
ZJS
97
98/* Those variables are initalized to 0 automatically, so we avoid uninitialized memory access.
99 * Real defaults are assigned in reset_arguments() below. */
100static char *arg_default_unit;
101static bool arg_system;
102static bool arg_dump_core;
103static int arg_crash_chvt;
104static bool arg_crash_shell;
105static bool arg_crash_reboot;
106static char *arg_confirm_spawn;
107static ShowStatus arg_show_status;
36cf4507 108static StatusUnitFormat arg_status_unit_format;
fb39af4c
ZJS
109static bool arg_switched_root;
110static PagerFlags arg_pager_flags;
111static bool arg_service_watchdogs;
112static ExecOutput arg_default_std_output;
113static ExecOutput arg_default_std_error;
114static usec_t arg_default_restart_usec;
115static usec_t arg_default_timeout_start_usec;
116static usec_t arg_default_timeout_stop_usec;
117static usec_t arg_default_timeout_abort_usec;
118static bool arg_default_timeout_abort_set;
119static usec_t arg_default_start_limit_interval;
120static unsigned arg_default_start_limit_burst;
121static usec_t arg_runtime_watchdog;
65224c1d 122static usec_t arg_reboot_watchdog;
acafd7d8 123static usec_t arg_kexec_watchdog;
fb39af4c
ZJS
124static char *arg_early_core_pattern;
125static char *arg_watchdog_device;
126static char **arg_default_environment;
127static struct rlimit *arg_default_rlimit[_RLIMIT_MAX];
128static uint64_t arg_capability_bounding_set;
129static bool arg_no_new_privs;
130static nsec_t arg_timer_slack_nsec;
131static usec_t arg_default_timer_accuracy_usec;
132static Set* arg_syscall_archs;
133static FILE* arg_serialization;
134static int arg_default_cpu_accounting;
135static bool arg_default_io_accounting;
136static bool arg_default_ip_accounting;
137static bool arg_default_blockio_accounting;
138static bool arg_default_memory_accounting;
139static bool arg_default_tasks_accounting;
3a0f06c4 140static TasksMax arg_default_tasks_max;
fb39af4c
ZJS
141static sd_id128_t arg_machine_id;
142static EmergencyAction arg_cad_burst_action;
143static OOMPolicy arg_default_oom_policy;
144static CPUSet arg_cpu_affinity;
b070c7c0 145static NUMAPolicy arg_numa_policy;
61fbbac1 146
0e06a031
LP
147/* A copy of the original environment block */
148static char **saved_env = NULL;
149
a9fd4cd1
FB
150static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
151 const struct rlimit *saved_rlimit_memlock);
4fc935ca 152
bb259772
LP
153_noreturn_ static void freeze_or_exit_or_reboot(void) {
154
c3b6a348
LP
155 /* If we are running in a container, let's prefer exiting, after all we can propagate an exit code to
156 * the container manager, and thus inform it that something went wrong. */
bb259772
LP
157 if (detect_container() > 0) {
158 log_emergency("Exiting PID 1...");
c3b6a348 159 _exit(EXIT_EXCEPTION);
bb259772 160 }
b9e74c39
LP
161
162 if (arg_crash_reboot) {
163 log_notice("Rebooting in 10s...");
164 (void) sleep(10);
165
166 log_notice("Rebooting now...");
167 (void) reboot(RB_AUTOBOOT);
168 log_emergency_errno(errno, "Failed to reboot: %m");
169 }
170
171 log_emergency("Freezing execution.");
172 freeze();
173}
174
848e863a 175_noreturn_ static void crash(int sig) {
7d06dad9
MS
176 struct sigaction sa;
177 pid_t pid;
97c4f35c 178
df0ff127 179 if (getpid_cached() != 1)
abb26902 180 /* Pass this on immediately, if this is not PID 1 */
92ca4cac 181 (void) raise(sig);
abb26902 182 else if (!arg_dump_core)
4104970e 183 log_emergency("Caught <%s>, not dumping core.", signal_to_string(sig));
97c4f35c 184 else {
7d06dad9 185 sa = (struct sigaction) {
189d5bac 186 .sa_handler = nop_signal_handler,
b92bea5d
ZJS
187 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
188 };
97c4f35c 189
6f5e3f35 190 /* We want to wait for the core process, hence let's enable SIGCHLD */
92ca4cac 191 (void) sigaction(SIGCHLD, &sa, NULL);
6f5e3f35 192
8869a0b4 193 pid = raw_clone(SIGCHLD);
e62d8c39 194 if (pid < 0)
56f64d95 195 log_emergency_errno(errno, "Caught <%s>, cannot fork for core dump: %m", signal_to_string(sig));
97c4f35c 196 else if (pid == 0) {
97c4f35c 197 /* Enable default signal handler for core dump */
15a90032 198
92ca4cac
LP
199 sa = (struct sigaction) {
200 .sa_handler = SIG_DFL,
201 };
202 (void) sigaction(sig, &sa, NULL);
97c4f35c 203
15a90032
LP
204 /* Don't limit the coredump size */
205 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY));
97c4f35c
LP
206
207 /* Just to be sure... */
e62d9b81 208 (void) chdir("/");
97c4f35c
LP
209
210 /* Raise the signal again */
ee05e779 211 pid = raw_getpid();
92ca4cac 212 (void) kill(pid, sig); /* raise() would kill the parent */
97c4f35c
LP
213
214 assert_not_reached("We shouldn't be here...");
bb85a582 215 _exit(EXIT_EXCEPTION);
4fc935ca 216 } else {
8e12a6ae
LP
217 siginfo_t status;
218 int r;
4fc935ca
LP
219
220 /* Order things nicely. */
e62d8c39
ZJS
221 r = wait_for_terminate(pid, &status);
222 if (r < 0)
da927ba9 223 log_emergency_errno(r, "Caught <%s>, waitpid() failed: %m", signal_to_string(sig));
e1714f02
ZJS
224 else if (status.si_code != CLD_DUMPED) {
225 const char *s = status.si_code == CLD_EXITED
e04ed6db 226 ? exit_status_to_string(status.si_status, EXIT_STATUS_LIBC)
e1714f02
ZJS
227 : signal_to_string(status.si_status);
228
ee05e779
ZJS
229 log_emergency("Caught <%s>, core dump failed (child "PID_FMT", code=%s, status=%i/%s).",
230 signal_to_string(sig),
e1714f02
ZJS
231 pid,
232 sigchld_code_to_string(status.si_code),
233 status.si_status, strna(s));
234 } else
235 log_emergency("Caught <%s>, dumped core as pid "PID_FMT".",
236 signal_to_string(sig), pid);
97c4f35c
LP
237 }
238 }
239
b9e74c39 240 if (arg_crash_chvt >= 0)
92ca4cac 241 (void) chvt(arg_crash_chvt);
601f6a1e 242
7d06dad9
MS
243 sa = (struct sigaction) {
244 .sa_handler = SIG_IGN,
245 .sa_flags = SA_NOCLDSTOP|SA_NOCLDWAIT|SA_RESTART,
246 };
247
248 /* Let the kernel reap children for us */
249 (void) sigaction(SIGCHLD, &sa, NULL);
8c43883a 250
7d06dad9 251 if (arg_crash_shell) {
b9e74c39 252 log_notice("Executing crash shell in 10s...");
92ca4cac 253 (void) sleep(10);
4fc935ca 254
8869a0b4 255 pid = raw_clone(SIGCHLD);
cd3bd60a 256 if (pid < 0)
56f64d95 257 log_emergency_errno(errno, "Failed to fork off crash shell: %m");
6f5e3f35 258 else if (pid == 0) {
b9e74c39 259 (void) setsid();
92ca4cac 260 (void) make_console_stdio();
595225af 261 (void) rlimit_nofile_safe();
92ca4cac 262 (void) execle("/bin/sh", "/bin/sh", NULL, environ);
6f5e3f35 263
ee05e779 264 log_emergency_errno(errno, "execle() failed: %m");
bb85a582 265 _exit(EXIT_EXCEPTION);
b9e74c39
LP
266 } else {
267 log_info("Spawned crash shell as PID "PID_FMT".", pid);
4cf0b03b 268 (void) wait_for_terminate(pid, NULL);
b9e74c39 269 }
4fc935ca
LP
270 }
271
bb259772 272 freeze_or_exit_or_reboot();
97c4f35c
LP
273}
274
275static void install_crash_handler(void) {
297d563d 276 static const struct sigaction sa = {
b92bea5d 277 .sa_handler = crash,
297d563d 278 .sa_flags = SA_NODEFER, /* So that we can raise the signal again from the signal handler */
b92bea5d 279 };
297d563d 280 int r;
97c4f35c 281
297d563d
LP
282 /* We ignore the return value here, since, we don't mind if we
283 * cannot set up a crash handler */
284 r = sigaction_many(&sa, SIGNALS_CRASH_HANDLER, -1);
285 if (r < 0)
286 log_debug_errno(r, "I had trouble setting up the crash handler, ignoring: %m");
97c4f35c 287}
f170852a 288
56d96fc0
LP
289static int console_setup(void) {
290 _cleanup_close_ int tty_fd = -1;
291 int r;
80876c20 292
512947d4 293 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
294 if (tty_fd < 0)
295 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 296
56d96fc0
LP
297 /* We don't want to force text mode. plymouth may be showing
298 * pictures already from initrd. */
512947d4 299 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
300 if (r < 0)
301 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 302
56d96fc0 303 return 0;
80876c20
LP
304}
305
ee48dbd5 306static int set_machine_id(const char *m) {
e042eab7 307 sd_id128_t t;
8b26cdbd 308 assert(m);
ee48dbd5 309
e042eab7 310 if (sd_id128_from_string(m, &t) < 0)
ee48dbd5
NC
311 return -EINVAL;
312
e042eab7 313 if (sd_id128_is_null(t))
ee48dbd5
NC
314 return -EINVAL;
315
e042eab7 316 arg_machine_id = t;
ee48dbd5
NC
317 return 0;
318}
319
96287a49 320static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
f170852a 321
059cb385 322 int r;
f170852a 323
059cb385 324 assert(key);
5192bd19 325
1d84ad94 326 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
bf4df7c3 327
1d84ad94
LP
328 if (proc_cmdline_value_missing(key, value))
329 return 0;
bf4df7c3 330
1d84ad94
LP
331 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
332 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
333 else if (in_initrd() == !!startswith(key, "rd.")) {
334 if (free_and_strdup(&arg_default_unit, value) < 0)
335 return log_oom();
336 }
f170852a 337
1d84ad94 338 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
4fc935ca 339
1d84ad94 340 r = value ? parse_boolean(value) : true;
fb472900 341 if (r < 0)
5e1ee764 342 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
4fc935ca 343 else
fa0f4d8a 344 arg_dump_core = r;
4fc935ca 345
c6885f5f
FB
346 } else if (proc_cmdline_key_streq(key, "systemd.early_core_pattern")) {
347
348 if (proc_cmdline_value_missing(key, value))
349 return 0;
350
351 if (path_is_absolute(value))
352 (void) parse_path_argument_and_warn(value, false, &arg_early_core_pattern);
353 else
354 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
355
1d84ad94 356 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
b9e74c39 357
1d84ad94
LP
358 if (!value)
359 arg_crash_chvt = 0; /* turn on */
5e1ee764 360 else {
a07a7324 361 r = parse_crash_chvt(value, &arg_crash_chvt);
5e1ee764
YW
362 if (r < 0)
363 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
364 }
b9e74c39 365
1d84ad94 366 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
4fc935ca 367
1d84ad94 368 r = value ? parse_boolean(value) : true;
fb472900 369 if (r < 0)
5e1ee764 370 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
4fc935ca 371 else
fa0f4d8a 372 arg_crash_shell = r;
5e7ee61c 373
1d84ad94 374 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
5e7ee61c 375
1d84ad94 376 r = value ? parse_boolean(value) : true;
b9e74c39 377 if (r < 0)
5e1ee764 378 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
5e7ee61c 379 else
b9e74c39 380 arg_crash_reboot = r;
5e7ee61c 381
1d84ad94
LP
382 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
383 char *s;
7d5ceb64 384
1d84ad94 385 r = parse_confirm_spawn(value, &s);
059cb385 386 if (r < 0)
5e1ee764
YW
387 log_warning_errno(r, "Failed to parse confirm_spawn switch %s, ignoring: %m", value);
388 else
389 free_and_replace(arg_confirm_spawn, s);
601f6a1e 390
2a12e32e
JK
391 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
392
393 r = value ? parse_boolean(value) : true;
394 if (r < 0)
5e1ee764 395 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
2a12e32e
JK
396 else
397 arg_service_watchdogs = r;
398
1d84ad94 399 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
9e58ff9c 400
1d84ad94
LP
401 if (value) {
402 r = parse_show_status(value, &arg_show_status);
403 if (r < 0)
5e1ee764 404 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
1d84ad94
LP
405 } else
406 arg_show_status = SHOW_STATUS_YES;
059cb385 407
36cf4507
ZJS
408 } else if (proc_cmdline_key_streq(key, "systemd.status_unit_format")) {
409
410 if (proc_cmdline_value_missing(key, value))
411 return 0;
412
413 r = status_unit_format_from_string(value);
414 if (r < 0)
415 log_warning_errno(r, "Failed to parse %s=%s, ignoring: %m", key, value);
416 else
417 arg_status_unit_format = r;
418
1d84ad94
LP
419 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
420
421 if (proc_cmdline_value_missing(key, value))
422 return 0;
0a494f1f 423
059cb385 424 r = exec_output_from_string(value);
fb472900 425 if (r < 0)
5e1ee764 426 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
0a494f1f
LP
427 else
428 arg_default_std_output = r;
0a494f1f 429
1d84ad94
LP
430 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
431
432 if (proc_cmdline_value_missing(key, value))
433 return 0;
059cb385
LP
434
435 r = exec_output_from_string(value);
fb472900 436 if (r < 0)
5e1ee764 437 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
0a494f1f
LP
438 else
439 arg_default_std_error = r;
9e7c5357 440
1d84ad94
LP
441 } else if (streq(key, "systemd.setenv")) {
442
443 if (proc_cmdline_value_missing(key, value))
444 return 0;
059cb385
LP
445
446 if (env_assignment_is_valid(value)) {
e21fea24
KS
447 char **env;
448
059cb385 449 env = strv_env_set(arg_default_environment, value);
1d84ad94
LP
450 if (!env)
451 return log_oom();
452
453 arg_default_environment = env;
e21fea24 454 } else
059cb385 455 log_warning("Environment variable name '%s' is not valid. Ignoring.", value);
9e58ff9c 456
1d84ad94
LP
457 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
458
459 if (proc_cmdline_value_missing(key, value))
460 return 0;
461
462 r = set_machine_id(value);
463 if (r < 0)
5e1ee764 464 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
ee48dbd5 465
1d84ad94
LP
466 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
467
468 if (proc_cmdline_value_missing(key, value))
469 return 0;
470
471 r = parse_sec(value, &arg_default_timeout_start_usec);
472 if (r < 0)
5e1ee764 473 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
1d84ad94
LP
474
475 if (arg_default_timeout_start_usec <= 0)
476 arg_default_timeout_start_usec = USEC_INFINITY;
ee48dbd5 477
68d58f38
LP
478 } else if (proc_cmdline_key_streq(key, "systemd.cpu_affinity")) {
479
480 if (proc_cmdline_value_missing(key, value))
481 return 0;
482
483 r = parse_cpu_set(value, &arg_cpu_affinity);
484 if (r < 0)
485 log_warning_errno(r, "Faile to parse CPU affinity mask '%s', ignoring: %m", value);
486
8a2c1fbf
EJ
487 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
488
489 if (proc_cmdline_value_missing(key, value))
490 return 0;
491
c6885f5f 492 (void) parse_path_argument_and_warn(value, false, &arg_watchdog_device);
8a2c1fbf 493
059cb385 494 } else if (streq(key, "quiet") && !value) {
d7b15e0a 495
7a293242 496 if (arg_show_status == _SHOW_STATUS_INVALID)
d450b6f2 497 arg_show_status = SHOW_STATUS_AUTO;
059cb385
LP
498
499 } else if (streq(key, "debug") && !value) {
d7b15e0a 500
1de1c9c3
LP
501 /* Note that log_parse_environment() handles 'debug'
502 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 503
75f86906 504 if (detect_container() > 0)
b2103dcc 505 log_set_target(LOG_TARGET_CONSOLE);
059cb385 506
dcd61450 507 } else if (!value) {
e2c9a131 508 const char *target;
f170852a
LP
509
510 /* SysV compatibility */
e2c9a131
EV
511 target = runlevel_to_target(key);
512 if (target)
513 return free_and_strdup(&arg_default_unit, target);
f170852a
LP
514 }
515
516 return 0;
517}
518
e8e581bf
ZJS
519#define DEFINE_SETTER(name, func, descr) \
520 static int name(const char *unit, \
521 const char *filename, \
522 unsigned line, \
523 const char *section, \
71a61510 524 unsigned section_line, \
e8e581bf
ZJS
525 const char *lvalue, \
526 int ltype, \
527 const char *rvalue, \
528 void *data, \
529 void *userdata) { \
530 \
531 int r; \
532 \
533 assert(filename); \
534 assert(lvalue); \
535 assert(rvalue); \
536 \
537 r = func(rvalue); \
538 if (r < 0) \
d1cefe0a
LP
539 log_syntax(unit, LOG_ERR, filename, line, r, \
540 "Invalid " descr "'%s': %m", \
541 rvalue); \
e8e581bf
ZJS
542 \
543 return 0; \
544 }
487393e9 545
a6ecbf83
FB
546DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
547DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
548DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color" );
549DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
487393e9 550
a61d6874
ZJS
551static int config_parse_default_timeout_abort(
552 const char *unit,
553 const char *filename,
554 unsigned line,
555 const char *section,
556 unsigned section_line,
557 const char *lvalue,
558 int ltype,
559 const char *rvalue,
560 void *data,
561 void *userdata) {
562 int r;
563
564 r = config_parse_timeout_abort(unit, filename, line, section, section_line, lvalue, ltype, rvalue,
565 &arg_default_timeout_abort_usec, userdata);
566 if (r >= 0)
567 arg_default_timeout_abort_set = r;
568 return 0;
569}
487393e9 570
a61d6874 571static int parse_config_file(void) {
f975e971 572 const ConfigTableItem items[] = {
a61d6874
ZJS
573 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
574 { "Manager", "LogTarget", config_parse_target, 0, NULL },
575 { "Manager", "LogColor", config_parse_color, 0, NULL },
576 { "Manager", "LogLocation", config_parse_location, 0, NULL },
577 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
578 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, &arg_crash_chvt },
579 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, &arg_crash_chvt },
580 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
581 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
582 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
583 { "Manager", "StatusUnitFormat", config_parse_status_unit_format, 0, &arg_status_unit_format },
584 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, &arg_cpu_affinity },
585 { "Manager", "NUMAPolicy", config_parse_numa_policy, 0, &arg_numa_policy.type },
586 { "Manager", "NUMAMask", config_parse_numa_mask, 0, &arg_numa_policy },
587 { "Manager", "JoinControllers", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
588 { "Manager", "RuntimeWatchdogSec", config_parse_sec, 0, &arg_runtime_watchdog },
589 { "Manager", "RebootWatchdogSec", config_parse_sec, 0, &arg_reboot_watchdog },
590 { "Manager", "ShutdownWatchdogSec", config_parse_sec, 0, &arg_reboot_watchdog }, /* obsolete alias */
591 { "Manager", "KExecWatchdogSec", config_parse_sec, 0, &arg_kexec_watchdog },
592 { "Manager", "WatchdogDevice", config_parse_path, 0, &arg_watchdog_device },
593 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
594 { "Manager", "NoNewPrivileges", config_parse_bool, 0, &arg_no_new_privs },
349cc4a5 595#if HAVE_SECCOMP
a61d6874 596 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
89fffa27 597#endif
a61d6874
ZJS
598 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
599 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_default_timer_accuracy_usec },
600 { "Manager", "DefaultStandardOutput", config_parse_output_restricted, 0, &arg_default_std_output },
601 { "Manager", "DefaultStandardError", config_parse_output_restricted, 0, &arg_default_std_error },
602 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_default_timeout_start_usec },
603 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_default_timeout_stop_usec },
604 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort, 0, NULL },
605 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_default_restart_usec },
606 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_default_start_limit_interval }, /* obsolete alias */
607 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec, 0, &arg_default_start_limit_interval },
608 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_default_start_limit_burst },
609 { "Manager", "DefaultEnvironment", config_parse_environ, 0, &arg_default_environment },
610 { "Manager", "DefaultLimitCPU", config_parse_rlimit, RLIMIT_CPU, arg_default_rlimit },
611 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit, RLIMIT_FSIZE, arg_default_rlimit },
612 { "Manager", "DefaultLimitDATA", config_parse_rlimit, RLIMIT_DATA, arg_default_rlimit },
613 { "Manager", "DefaultLimitSTACK", config_parse_rlimit, RLIMIT_STACK, arg_default_rlimit },
614 { "Manager", "DefaultLimitCORE", config_parse_rlimit, RLIMIT_CORE, arg_default_rlimit },
615 { "Manager", "DefaultLimitRSS", config_parse_rlimit, RLIMIT_RSS, arg_default_rlimit },
616 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit, RLIMIT_NOFILE, arg_default_rlimit },
617 { "Manager", "DefaultLimitAS", config_parse_rlimit, RLIMIT_AS, arg_default_rlimit },
618 { "Manager", "DefaultLimitNPROC", config_parse_rlimit, RLIMIT_NPROC, arg_default_rlimit },
619 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit, RLIMIT_MEMLOCK, arg_default_rlimit },
620 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit, RLIMIT_LOCKS, arg_default_rlimit },
621 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit, RLIMIT_SIGPENDING, arg_default_rlimit },
622 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit, RLIMIT_MSGQUEUE, arg_default_rlimit },
623 { "Manager", "DefaultLimitNICE", config_parse_rlimit, RLIMIT_NICE, arg_default_rlimit },
624 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit, RLIMIT_RTPRIO, arg_default_rlimit },
625 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit, RLIMIT_RTTIME, arg_default_rlimit },
626 { "Manager", "DefaultCPUAccounting", config_parse_tristate, 0, &arg_default_cpu_accounting },
627 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_default_io_accounting },
628 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_default_ip_accounting },
629 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_default_blockio_accounting },
630 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_default_memory_accounting },
631 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_default_tasks_accounting },
632 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_default_tasks_max },
633 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, 0, &arg_cad_burst_action },
634 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy, 0, &arg_default_oom_policy },
d3b1c508 635 {}
487393e9
LP
636 };
637
1b907b5c 638 const char *fn, *conf_dirs_nulstr;
487393e9 639
463d0d15 640 fn = arg_system ?
75eb6154
LP
641 PKGSYSCONFDIR "/system.conf" :
642 PKGSYSCONFDIR "/user.conf";
643
463d0d15 644 conf_dirs_nulstr = arg_system ?
75eb6154
LP
645 CONF_PATHS_NULSTR("systemd/system.conf.d") :
646 CONF_PATHS_NULSTR("systemd/user.conf.d");
647
bcde742e 648 (void) config_parse_many_nulstr(fn, conf_dirs_nulstr, "Manager\0", config_item_table_lookup, items, CONFIG_PARSE_WARN, NULL);
36c16a7c
LP
649
650 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we used USEC_INFINITY
651 * like everywhere else. */
652 if (arg_default_timeout_start_usec <= 0)
653 arg_default_timeout_start_usec = USEC_INFINITY;
654 if (arg_default_timeout_stop_usec <= 0)
655 arg_default_timeout_stop_usec = USEC_INFINITY;
487393e9 656
487393e9
LP
657 return 0;
658}
659
85cb4151 660static void set_manager_defaults(Manager *m) {
06af2a04
TB
661
662 assert(m);
663
5b65ae15
LP
664 /* Propagates the various default unit property settings into the manager object, i.e. properties that do not
665 * affect the manager itself, but are just what newly allocated units will have set if they haven't set
666 * anything else. (Also see set_manager_settings() for the settings that affect the manager's own behaviour) */
667
06af2a04
TB
668 m->default_timer_accuracy_usec = arg_default_timer_accuracy_usec;
669 m->default_std_output = arg_default_std_output;
670 m->default_std_error = arg_default_std_error;
671 m->default_timeout_start_usec = arg_default_timeout_start_usec;
672 m->default_timeout_stop_usec = arg_default_timeout_stop_usec;
dc653bf4
JK
673 m->default_timeout_abort_usec = arg_default_timeout_abort_usec;
674 m->default_timeout_abort_set = arg_default_timeout_abort_set;
06af2a04
TB
675 m->default_restart_usec = arg_default_restart_usec;
676 m->default_start_limit_interval = arg_default_start_limit_interval;
677 m->default_start_limit_burst = arg_default_start_limit_burst;
a88c5b8a
CD
678
679 /* On 4.15+ with unified hierarchy, CPU accounting is essentially free as it doesn't require the CPU
680 * controller to be enabled, so the default is to enable it unless we got told otherwise. */
681 if (arg_default_cpu_accounting >= 0)
682 m->default_cpu_accounting = arg_default_cpu_accounting;
683 else
684 m->default_cpu_accounting = cpu_accounting_is_cheap();
685
13c31542 686 m->default_io_accounting = arg_default_io_accounting;
377bfd2d 687 m->default_ip_accounting = arg_default_ip_accounting;
06af2a04
TB
688 m->default_blockio_accounting = arg_default_blockio_accounting;
689 m->default_memory_accounting = arg_default_memory_accounting;
03a7b521 690 m->default_tasks_accounting = arg_default_tasks_accounting;
0af20ea2 691 m->default_tasks_max = arg_default_tasks_max;
afcfaa69 692 m->default_oom_policy = arg_default_oom_policy;
06af2a04 693
79a224c4
LP
694 (void) manager_set_default_rlimits(m, arg_default_rlimit);
695
696 (void) manager_default_environment(m);
697 (void) manager_transient_environment_add(m, arg_default_environment);
06af2a04
TB
698}
699
7b46fc6a
LP
700static void set_manager_settings(Manager *m) {
701
702 assert(m);
703
5b65ae15
LP
704 /* Propagates the various manager settings into the manager object, i.e. properties that effect the manager
705 * itself (as opposed to just being inherited into newly allocated units, see set_manager_defaults() above). */
706
7b46fc6a 707 m->confirm_spawn = arg_confirm_spawn;
2a12e32e 708 m->service_watchdogs = arg_service_watchdogs;
7b46fc6a 709 m->runtime_watchdog = arg_runtime_watchdog;
65224c1d 710 m->reboot_watchdog = arg_reboot_watchdog;
acafd7d8 711 m->kexec_watchdog = arg_kexec_watchdog;
7b46fc6a
LP
712 m->cad_burst_action = arg_cad_burst_action;
713
7365a296 714 manager_set_show_status(m, arg_show_status, "commandline");
36cf4507 715 m->status_unit_format = arg_status_unit_format;
7b46fc6a
LP
716}
717
f170852a 718static int parse_argv(int argc, char *argv[]) {
f170852a
LP
719 enum {
720 ARG_LOG_LEVEL = 0x100,
721 ARG_LOG_TARGET,
bbe63281
LP
722 ARG_LOG_COLOR,
723 ARG_LOG_LOCATION,
2f198e2f 724 ARG_UNIT,
edb9aaa8 725 ARG_SYSTEM,
af2d49f7 726 ARG_USER,
e537352b 727 ARG_TEST,
b87c2aa6 728 ARG_NO_PAGER,
9ba0bc4e 729 ARG_VERSION,
80876c20 730 ARG_DUMP_CONFIGURATION_ITEMS,
bbc1acab 731 ARG_DUMP_BUS_PROPERTIES,
9e58ff9c 732 ARG_DUMP_CORE,
b9e74c39 733 ARG_CRASH_CHVT,
9e58ff9c 734 ARG_CRASH_SHELL,
b9e74c39 735 ARG_CRASH_REBOOT,
a16e1123 736 ARG_CONFIRM_SPAWN,
9e58ff9c 737 ARG_SHOW_STATUS,
4288f619 738 ARG_DESERIALIZE,
2660882b 739 ARG_SWITCHED_ROOT,
0a494f1f 740 ARG_DEFAULT_STD_OUTPUT,
ee48dbd5 741 ARG_DEFAULT_STD_ERROR,
2a12e32e
JK
742 ARG_MACHINE_ID,
743 ARG_SERVICE_WATCHDOGS,
f170852a
LP
744 };
745
746 static const struct option options[] = {
a16e1123
LP
747 { "log-level", required_argument, NULL, ARG_LOG_LEVEL },
748 { "log-target", required_argument, NULL, ARG_LOG_TARGET },
bbe63281
LP
749 { "log-color", optional_argument, NULL, ARG_LOG_COLOR },
750 { "log-location", optional_argument, NULL, ARG_LOG_LOCATION },
2f198e2f 751 { "unit", required_argument, NULL, ARG_UNIT },
edb9aaa8 752 { "system", no_argument, NULL, ARG_SYSTEM },
af2d49f7 753 { "user", no_argument, NULL, ARG_USER },
a16e1123 754 { "test", no_argument, NULL, ARG_TEST },
b87c2aa6 755 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
a16e1123 756 { "help", no_argument, NULL, 'h' },
9ba0bc4e 757 { "version", no_argument, NULL, ARG_VERSION },
a16e1123 758 { "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS },
bbc1acab 759 { "dump-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES },
a5d87bf0 760 { "dump-core", optional_argument, NULL, ARG_DUMP_CORE },
b9e74c39 761 { "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT },
a5d87bf0 762 { "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL },
b9e74c39 763 { "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT },
a5d87bf0 764 { "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN },
6e98720f 765 { "show-status", optional_argument, NULL, ARG_SHOW_STATUS },
a16e1123 766 { "deserialize", required_argument, NULL, ARG_DESERIALIZE },
2660882b 767 { "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT },
0a494f1f
LP
768 { "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, },
769 { "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, },
ee48dbd5 770 { "machine-id", required_argument, NULL, ARG_MACHINE_ID },
2a12e32e 771 { "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS },
fb472900 772 {}
f170852a
LP
773 };
774
775 int c, r;
776
777 assert(argc >= 1);
778 assert(argv);
779
df0ff127 780 if (getpid_cached() == 1)
b770165a
LP
781 opterr = 0;
782
099663ff 783 while ((c = getopt_long(argc, argv, "hDbsz:", options, NULL)) >= 0)
f170852a
LP
784
785 switch (c) {
786
787 case ARG_LOG_LEVEL:
fb472900 788 r = log_set_max_level_from_string(optarg);
2b5107e1
ZJS
789 if (r < 0)
790 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
f170852a
LP
791
792 break;
793
794 case ARG_LOG_TARGET:
fb472900 795 r = log_set_target_from_string(optarg);
2b5107e1
ZJS
796 if (r < 0)
797 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
f170852a
LP
798
799 break;
800
bbe63281
LP
801 case ARG_LOG_COLOR:
802
d0b170c8 803 if (optarg) {
fb472900 804 r = log_show_color_from_string(optarg);
2b5107e1
ZJS
805 if (r < 0)
806 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
807 optarg);
d0b170c8
LP
808 } else
809 log_show_color(true);
bbe63281
LP
810
811 break;
812
813 case ARG_LOG_LOCATION:
d0b170c8 814 if (optarg) {
fb472900 815 r = log_show_location_from_string(optarg);
2b5107e1
ZJS
816 if (r < 0)
817 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
818 optarg);
d0b170c8
LP
819 } else
820 log_show_location(true);
bbe63281
LP
821
822 break;
823
0a494f1f 824 case ARG_DEFAULT_STD_OUTPUT:
fb472900 825 r = exec_output_from_string(optarg);
2b5107e1
ZJS
826 if (r < 0)
827 return log_error_errno(r, "Failed to parse default standard output setting \"%s\": %m",
828 optarg);
829 arg_default_std_output = r;
0a494f1f
LP
830 break;
831
832 case ARG_DEFAULT_STD_ERROR:
fb472900 833 r = exec_output_from_string(optarg);
2b5107e1
ZJS
834 if (r < 0)
835 return log_error_errno(r, "Failed to parse default standard error output setting \"%s\": %m",
836 optarg);
837 arg_default_std_error = r;
0a494f1f
LP
838 break;
839
2f198e2f 840 case ARG_UNIT:
e6e242ad 841 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de 842 if (r < 0)
2b5107e1 843 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
f170852a
LP
844
845 break;
846
edb9aaa8 847 case ARG_SYSTEM:
463d0d15 848 arg_system = true;
edb9aaa8 849 break;
a5dab5ce 850
af2d49f7 851 case ARG_USER:
463d0d15 852 arg_system = false;
a5dab5ce 853 break;
a5dab5ce 854
e965d56d 855 case ARG_TEST:
fa0f4d8a 856 arg_action = ACTION_TEST;
b87c2aa6
ZJS
857 break;
858
859 case ARG_NO_PAGER:
0221d68a 860 arg_pager_flags |= PAGER_DISABLE;
e965d56d
LP
861 break;
862
9ba0bc4e
ZJS
863 case ARG_VERSION:
864 arg_action = ACTION_VERSION;
865 break;
866
e537352b 867 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 868 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
869 break;
870
bbc1acab
YW
871 case ARG_DUMP_BUS_PROPERTIES:
872 arg_action = ACTION_DUMP_BUS_PROPERTIES;
873 break;
874
9e58ff9c 875 case ARG_DUMP_CORE:
b9e74c39
LP
876 if (!optarg)
877 arg_dump_core = true;
878 else {
879 r = parse_boolean(optarg);
880 if (r < 0)
2b5107e1
ZJS
881 return log_error_errno(r, "Failed to parse dump core boolean: \"%s\": %m",
882 optarg);
b9e74c39 883 arg_dump_core = r;
a5d87bf0 884 }
b9e74c39
LP
885 break;
886
887 case ARG_CRASH_CHVT:
a07a7324 888 r = parse_crash_chvt(optarg, &arg_crash_chvt);
b9e74c39 889 if (r < 0)
2b5107e1
ZJS
890 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
891 optarg);
9e58ff9c
LP
892 break;
893
894 case ARG_CRASH_SHELL:
b9e74c39
LP
895 if (!optarg)
896 arg_crash_shell = true;
897 else {
898 r = parse_boolean(optarg);
899 if (r < 0)
2b5107e1
ZJS
900 return log_error_errno(r, "Failed to parse crash shell boolean: \"%s\": %m",
901 optarg);
b9e74c39
LP
902 arg_crash_shell = r;
903 }
904 break;
905
906 case ARG_CRASH_REBOOT:
907 if (!optarg)
908 arg_crash_reboot = true;
909 else {
910 r = parse_boolean(optarg);
911 if (r < 0)
2b5107e1
ZJS
912 return log_error_errno(r, "Failed to parse crash shell boolean: \"%s\": %m",
913 optarg);
b9e74c39 914 arg_crash_reboot = r;
a5d87bf0 915 }
9e58ff9c
LP
916 break;
917
80876c20 918 case ARG_CONFIRM_SPAWN:
7d5ceb64
FB
919 arg_confirm_spawn = mfree(arg_confirm_spawn);
920
921 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
922 if (r < 0)
2b5107e1
ZJS
923 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
924 optarg);
80876c20
LP
925 break;
926
2a12e32e
JK
927 case ARG_SERVICE_WATCHDOGS:
928 r = parse_boolean(optarg);
929 if (r < 0)
2b5107e1
ZJS
930 return log_error_errno(r, "Failed to parse service watchdogs boolean: \"%s\": %m",
931 optarg);
2a12e32e
JK
932 arg_service_watchdogs = r;
933 break;
934
9e58ff9c 935 case ARG_SHOW_STATUS:
d450b6f2
ZJS
936 if (optarg) {
937 r = parse_show_status(optarg, &arg_show_status);
ac7ec288 938 if (r < 0)
2b5107e1
ZJS
939 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
940 optarg);
d450b6f2
ZJS
941 } else
942 arg_show_status = SHOW_STATUS_YES;
6e98720f 943 break;
a5d87bf0 944
a16e1123
LP
945 case ARG_DESERIALIZE: {
946 int fd;
947 FILE *f;
948
01e10de3 949 r = safe_atoi(optarg, &fd);
2b5107e1
ZJS
950 if (r < 0)
951 log_error_errno(r, "Failed to parse deserialize option \"%s\": %m", optarg);
baaa35ad
ZJS
952 if (fd < 0)
953 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
954 "Invalid deserialize fd: %d",
955 fd);
a16e1123 956
b9e74c39 957 (void) fd_cloexec(fd, true);
01e10de3
LP
958
959 f = fdopen(fd, "r");
4a62c710 960 if (!f)
2b5107e1 961 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
a16e1123 962
74ca738f 963 safe_fclose(arg_serialization);
d3b1c508 964 arg_serialization = f;
a16e1123
LP
965
966 break;
967 }
968
2660882b 969 case ARG_SWITCHED_ROOT:
bf4df7c3 970 arg_switched_root = true;
d03bc1b8
HH
971 break;
972
ee48dbd5
NC
973 case ARG_MACHINE_ID:
974 r = set_machine_id(optarg);
54500613 975 if (r < 0)
2b5107e1 976 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
ee48dbd5
NC
977 break;
978
f170852a 979 case 'h':
fa0f4d8a 980 arg_action = ACTION_HELP;
f170852a
LP
981 break;
982
1d2e23ab
LP
983 case 'D':
984 log_set_max_level(LOG_DEBUG);
985 break;
986
099663ff
LP
987 case 'b':
988 case 's':
989 case 'z':
990 /* Just to eat away the sysvinit kernel
991 * cmdline args without getopt() error
992 * messages that we'll parse in
993 * parse_proc_cmdline_word() or ignore. */
f170852a 994
099663ff 995 case '?':
df0ff127 996 if (getpid_cached() != 1)
099663ff 997 return -EINVAL;
601185b4
ZJS
998 else
999 return 0;
099663ff 1000
601185b4
ZJS
1001 default:
1002 assert_not_reached("Unhandled option code.");
f170852a
LP
1003 }
1004
df0ff127 1005 if (optind < argc && getpid_cached() != 1) {
d821e6d6
LP
1006 /* Hmm, when we aren't run as init system
1007 * let's complain about excess arguments */
1008
baaa35ad
ZJS
1009 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1010 "Excess arguments.");
d821e6d6
LP
1011 }
1012
f170852a
LP
1013 return 0;
1014}
1015
1016static int help(void) {
37ec0fdd
LP
1017 _cleanup_free_ char *link = NULL;
1018 int r;
1019
1020 r = terminal_urlify_man("systemd", "1", &link);
1021 if (r < 0)
1022 return log_oom();
f170852a 1023
2e33c433 1024 printf("%s [OPTIONS...]\n\n"
af2d49f7 1025 "Starts up and maintains the system or user services.\n\n"
e537352b 1026 " -h --help Show this help\n"
cb4069d9 1027 " --version Show version\n"
cd69e88b
LP
1028 " --test Determine initial transaction, dump it and exit\n"
1029 " --system In combination with --test: operate as system service manager\n"
1030 " --user In combination with --test: operate as per-user service manager\n"
b87c2aa6 1031 " --no-pager Do not pipe output into a pager\n"
80876c20 1032 " --dump-configuration-items Dump understood unit configuration items\n"
bbc1acab 1033 " --dump-bus-properties Dump exposed bus properties\n"
9e58ff9c 1034 " --unit=UNIT Set default unit\n"
b9e74c39
LP
1035 " --dump-core[=BOOL] Dump core on crash\n"
1036 " --crash-vt=NR Change to specified VT on crash\n"
1037 " --crash-reboot[=BOOL] Reboot on crash\n"
1038 " --crash-shell[=BOOL] Run shell on crash\n"
1039 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1040 " --show-status[=BOOL] Show status updates on the console during bootup\n"
c1dc6153 1041 " --log-target=TARGET Set log target (console, journal, kmsg, journal-or-kmsg, null)\n"
9e58ff9c 1042 " --log-level=LEVEL Set log level (debug, info, notice, warning, err, crit, alert, emerg)\n"
b9e74c39
LP
1043 " --log-color[=BOOL] Highlight important log messages\n"
1044 " --log-location[=BOOL] Include code location in log messages\n"
0a494f1f 1045 " --default-standard-output= Set default standard output for services\n"
37ec0fdd
LP
1046 " --default-standard-error= Set default standard error output for services\n"
1047 "\nSee the %s for details.\n"
1048 , program_invocation_short_name
1049 , link
1050 );
f170852a
LP
1051
1052 return 0;
1053}
1054
2cc856ac
LP
1055static int prepare_reexecute(
1056 Manager *m,
1057 FILE **ret_f,
1058 FDSet **ret_fds,
1059 bool switching_root) {
1060
48b90859
LP
1061 _cleanup_fdset_free_ FDSet *fds = NULL;
1062 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1063 int r;
1064
1065 assert(m);
2cc856ac
LP
1066 assert(ret_f);
1067 assert(ret_fds);
a16e1123 1068
6b78f9b4 1069 r = manager_open_serialization(m, &f);
48b90859
LP
1070 if (r < 0)
1071 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1072
71445ae7 1073 /* Make sure nothing is really destructed when we shut down */
313cefa1 1074 m->n_reloading++;
718db961 1075 bus_manager_send_reloading(m, true);
71445ae7 1076
6b78f9b4 1077 fds = fdset_new();
48b90859
LP
1078 if (!fds)
1079 return log_oom();
a16e1123 1080
b3680f49 1081 r = manager_serialize(m, f, fds, switching_root);
48b90859 1082 if (r < 0)
d68c645b 1083 return r;
a16e1123 1084
48b90859
LP
1085 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1086 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1087
6b78f9b4 1088 r = fd_cloexec(fileno(f), false);
48b90859
LP
1089 if (r < 0)
1090 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1091
6b78f9b4 1092 r = fdset_cloexec(fds, false);
48b90859
LP
1093 if (r < 0)
1094 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123 1095
2cc856ac
LP
1096 *ret_f = TAKE_PTR(f);
1097 *ret_fds = TAKE_PTR(fds);
a16e1123 1098
48b90859 1099 return 0;
a16e1123
LP
1100}
1101
a8b627aa
LP
1102static void bump_file_max_and_nr_open(void) {
1103
1104 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large numbers of file
1105 * descriptors are no longer a performance problem and their memory is properly tracked by memcg, thus counting
1106 * them and limiting them in another two layers of limits is unnecessary and just complicates things. This
1107 * function hence turns off 2 of the 4 levels of limits on file descriptors, and makes RLIMIT_NOLIMIT (soft +
1108 * hard) the only ones that really matter. */
1109
1110#if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
a8b627aa
LP
1111 int r;
1112#endif
1113
1114#if BUMP_PROC_SYS_FS_FILE_MAX
6e2f7894
LP
1115 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously thing where
1116 * different but the operation would fail silently.) */
56e8419a 1117 r = sysctl_writef("fs/file-max", "%li\n", LONG_MAX);
a8b627aa
LP
1118 if (r < 0)
1119 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.file-max, ignoring: %m");
1120#endif
1121
a8b627aa
LP
1122#if BUMP_PROC_SYS_FS_NR_OPEN
1123 int v = INT_MAX;
1124
1125 /* Arg! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know what they
1126 * are. The expression by which the maximum is determined is dependent on the architecture, and is something we
1127 * don't really want to copy to userspace, as it is dependent on implementation details of the kernel. Since
1128 * the kernel doesn't expose the maximum value to us, we can only try and hope. Hence, let's start with
1129 * INT_MAX, and then keep halving the value until we find one that works. Ugly? Yes, absolutely, but kernel
1130 * APIs are kernel APIs, so what do can we do... 🤯 */
1131
1132 for (;;) {
1133 int k;
1134
1135 v &= ~(__SIZEOF_POINTER__ - 1); /* Round down to next multiple of the pointer size */
1136 if (v < 1024) {
1137 log_warning("Can't bump fs.nr_open, value too small.");
1138 break;
1139 }
1140
1141 k = read_nr_open();
1142 if (k < 0) {
1143 log_error_errno(k, "Failed to read fs.nr_open: %m");
1144 break;
1145 }
1146 if (k >= v) { /* Already larger */
1147 log_debug("Skipping bump, value is already larger.");
1148 break;
1149 }
1150
56e8419a 1151 r = sysctl_writef("fs/nr_open", "%i\n", v);
a8b627aa
LP
1152 if (r == -EINVAL) {
1153 log_debug("Couldn't write fs.nr_open as %i, halving it.", v);
1154 v /= 2;
1155 continue;
1156 }
1157 if (r < 0) {
1158 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.nr_open, ignoring: %m");
1159 break;
1160 }
1161
1162 log_debug("Successfully bumped fs.nr_open to %i", v);
1163 break;
1164 }
1165#endif
1166}
1167
4096d6f5 1168static int bump_rlimit_nofile(struct rlimit *saved_rlimit) {
cda7faa9 1169 struct rlimit new_rlimit;
9264cc39 1170 int r, nr;
4096d6f5 1171
52d62075
LP
1172 /* Get the underlying absolute limit the kernel enforces */
1173 nr = read_nr_open();
1174
cda7faa9
LP
1175 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1176 new_rlimit = (struct rlimit) {
1177 .rlim_cur = MAX((rlim_t) nr, saved_rlimit->rlim_cur),
1178 .rlim_max = MAX((rlim_t) nr, saved_rlimit->rlim_max),
1179 };
1180
1181 /* Shortcut if nothing changes. */
1182 if (saved_rlimit->rlim_max >= new_rlimit.rlim_max &&
1183 saved_rlimit->rlim_cur >= new_rlimit.rlim_cur) {
1184 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1185 return 0;
1186 }
1187
52d62075
LP
1188 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1189 * both hard and soft. */
cda7faa9 1190 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
23bbb0de 1191 if (r < 0)
3ce40911 1192 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1193
1194 return 0;
1195}
1196
fb3ae275 1197static int bump_rlimit_memlock(struct rlimit *saved_rlimit) {
cda7faa9 1198 struct rlimit new_rlimit;
fb3ae275
LP
1199 int r;
1200
a17c1712 1201 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK which should
6e3c443b 1202 * normally disable such checks. We need them to implement IPAddressAllow= and IPAddressDeny=, hence let's bump
a17c1712 1203 * the value high enough for our user. */
fb3ae275 1204
cda7faa9
LP
1205 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1206 * must be unsigned, hence this is a given, but let's make this clear here. */
1207 assert_cc(RLIM_INFINITY > 0);
1208
1209 new_rlimit = (struct rlimit) {
1210 .rlim_cur = MAX(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur),
1211 .rlim_max = MAX(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max),
1212 };
1213
1214 if (saved_rlimit->rlim_max >= new_rlimit.rlim_cur &&
1215 saved_rlimit->rlim_cur >= new_rlimit.rlim_max) {
1216 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1217 return 0;
1218 }
1219
1220 r = setrlimit_closest(RLIMIT_MEMLOCK, &new_rlimit);
fb3ae275
LP
1221 if (r < 0)
1222 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1223
1224 return 0;
1225}
1226
80758717 1227static void test_usr(void) {
80758717 1228
796ac4c1 1229 /* Check that /usr is either on the same file system as / or mounted already. */
80758717 1230
871c44a7
LP
1231 if (dir_is_empty("/usr") <= 0)
1232 return;
1233
8b173b5e 1234 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7
LP
1235 "Some things will probably break (sometimes even silently) in mysterious ways. "
1236 "Consult http://freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1237}
1238
d3b1c508 1239static int enforce_syscall_archs(Set *archs) {
349cc4a5 1240#if HAVE_SECCOMP
d3b1c508
LP
1241 int r;
1242
83f12b27
FS
1243 if (!is_seccomp_available())
1244 return 0;
1245
469830d1 1246 r = seccomp_restrict_archs(arg_syscall_archs);
d3b1c508 1247 if (r < 0)
469830d1 1248 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
d3b1c508 1249#endif
469830d1 1250 return 0;
d3b1c508
LP
1251}
1252
b6e2f329
LP
1253static int status_welcome(void) {
1254 _cleanup_free_ char *pretty_name = NULL, *ansi_color = NULL;
1255 int r;
1256
5ca02bfc 1257 if (!show_status_on(arg_show_status))
fd8c85c6
LP
1258 return 0;
1259
d58ad743
LP
1260 r = parse_os_release(NULL,
1261 "PRETTY_NAME", &pretty_name,
1262 "ANSI_COLOR", &ansi_color,
1263 NULL);
1264 if (r < 0)
1265 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1266 "Failed to read os-release file, ignoring: %m");
b6e2f329 1267
dc9b5816 1268 if (log_get_show_color())
a885727a 1269 return status_printf(NULL, 0,
dc9b5816
ZJS
1270 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1271 isempty(ansi_color) ? "1" : ansi_color,
1272 isempty(pretty_name) ? "Linux" : pretty_name);
1273 else
a885727a 1274 return status_printf(NULL, 0,
dc9b5816
ZJS
1275 "\nWelcome to %s!\n",
1276 isempty(pretty_name) ? "Linux" : pretty_name);
b6e2f329
LP
1277}
1278
fdd25311
LP
1279static int write_container_id(void) {
1280 const char *c;
19854865 1281 int r;
fdd25311
LP
1282
1283 c = getenv("container");
1284 if (isempty(c))
1285 return 0;
1286
8612da97
LP
1287 RUN_WITH_UMASK(0022)
1288 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1289 if (r < 0)
f1f849b0 1290 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1291
1292 return 1;
1293}
1294
1295static int bump_unix_max_dgram_qlen(void) {
1296 _cleanup_free_ char *qlen = NULL;
1297 unsigned long v;
1298 int r;
1299
3130fca5
LP
1300 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set the value
1301 * really really early during boot, so that it is actually applied to all our sockets, including the
1302 * $NOTIFY_SOCKET one. */
19854865
LP
1303
1304 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1305 if (r < 0)
875622c3 1306 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r, "Failed to read AF_UNIX datagram queue length, ignoring: %m");
19854865
LP
1307
1308 r = safe_atolu(qlen, &v);
1309 if (r < 0)
3130fca5 1310 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
19854865
LP
1311
1312 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1313 return 0;
1314
57512c89 1315 r = write_string_filef("/proc/sys/net/unix/max_dgram_qlen", WRITE_STRING_FILE_DISABLE_BUFFER, "%lu", DEFAULT_UNIX_MAX_DGRAM_QLEN);
19854865
LP
1316 if (r < 0)
1317 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1318 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1319
1320 return 1;
fdd25311
LP
1321}
1322
32391275
FB
1323static int fixup_environment(void) {
1324 _cleanup_free_ char *term = NULL;
4dc63c4b 1325 const char *t;
32391275
FB
1326 int r;
1327
43db615b
LP
1328 /* Only fix up the environment when we are started as PID 1 */
1329 if (getpid_cached() != 1)
1330 return 0;
1331
1332 /* We expect the environment to be set correctly if run inside a container. */
84af7821
LP
1333 if (detect_container() > 0)
1334 return 0;
1335
43db615b
LP
1336 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the backend
1337 * device used by the console. We try to make a better guess here since some consoles might not have support
1338 * for color mode for example.
32391275 1339 *
43db615b 1340 * However if TERM was configured through the kernel command line then leave it alone. */
1d84ad94 1341 r = proc_cmdline_get_key("TERM", 0, &term);
32391275
FB
1342 if (r < 0)
1343 return r;
32391275 1344
4dc63c4b
LP
1345 t = term ?: default_term_for_tty("/dev/console");
1346
1347 if (setenv("TERM", t, 1) < 0)
32391275
FB
1348 return -errno;
1349
9d48671c
ZJS
1350 /* The kernels sets HOME=/ for init. Let's undo this. */
1351 if (path_equal_ptr(getenv("HOME"), "/") &&
1352 unsetenv("HOME") < 0)
1353 log_warning_errno(errno, "Failed to unset $HOME: %m");
1354
32391275
FB
1355 return 0;
1356}
1357
6808a0bc
LP
1358static void redirect_telinit(int argc, char *argv[]) {
1359
1360 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1361
1362#if HAVE_SYSV_COMPAT
1363 if (getpid_cached() == 1)
1364 return;
1365
1366 if (!strstr(program_invocation_short_name, "init"))
1367 return;
1368
1369 execv(SYSTEMCTL_BINARY_PATH, argv);
1370 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
a45d7127 1371 exit(EXIT_FAILURE);
6808a0bc
LP
1372#endif
1373}
1374
4a36297c
LP
1375static int become_shutdown(
1376 const char *shutdown_verb,
7eb35049 1377 int retval) {
4a36297c
LP
1378
1379 char log_level[DECIMAL_STR_MAX(int) + 1],
e73c54b8
JK
1380 exit_code[DECIMAL_STR_MAX(uint8_t) + 1],
1381 timeout[DECIMAL_STR_MAX(usec_t) + 1];
4a36297c 1382
e73c54b8 1383 const char* command_line[13] = {
4a36297c
LP
1384 SYSTEMD_SHUTDOWN_BINARY_PATH,
1385 shutdown_verb,
e73c54b8 1386 "--timeout", timeout,
4a36297c
LP
1387 "--log-level", log_level,
1388 "--log-target",
1389 };
1390
1391 _cleanup_strv_free_ char **env_block = NULL;
e73c54b8 1392 size_t pos = 7;
4a36297c 1393 int r;
acafd7d8 1394 usec_t watchdog_timer = 0;
4a36297c 1395
7eb35049 1396 assert(shutdown_verb);
234519ae 1397 assert(!command_line[pos]);
4a36297c
LP
1398 env_block = strv_copy(environ);
1399
1400 xsprintf(log_level, "%d", log_get_max_level());
e73c54b8 1401 xsprintf(timeout, "%" PRI_USEC "us", arg_default_timeout_stop_usec);
4a36297c
LP
1402
1403 switch (log_get_target()) {
1404
1405 case LOG_TARGET_KMSG:
1406 case LOG_TARGET_JOURNAL_OR_KMSG:
1407 case LOG_TARGET_SYSLOG_OR_KMSG:
1408 command_line[pos++] = "kmsg";
1409 break;
1410
1411 case LOG_TARGET_NULL:
1412 command_line[pos++] = "null";
1413 break;
1414
1415 case LOG_TARGET_CONSOLE:
1416 default:
1417 command_line[pos++] = "console";
1418 break;
1419 };
1420
1421 if (log_get_show_color())
1422 command_line[pos++] = "--log-color";
1423
1424 if (log_get_show_location())
1425 command_line[pos++] = "--log-location";
1426
1427 if (streq(shutdown_verb, "exit")) {
1428 command_line[pos++] = "--exit-code";
1429 command_line[pos++] = exit_code;
1430 xsprintf(exit_code, "%d", retval);
1431 }
1432
1433 assert(pos < ELEMENTSOF(command_line));
1434
acafd7d8 1435 if (streq(shutdown_verb, "reboot"))
65224c1d 1436 watchdog_timer = arg_reboot_watchdog;
acafd7d8
LB
1437 else if (streq(shutdown_verb, "kexec"))
1438 watchdog_timer = arg_kexec_watchdog;
1439
1440 if (watchdog_timer > 0 && watchdog_timer != USEC_INFINITY) {
7eb35049 1441
4a36297c
LP
1442 char *e;
1443
acafd7d8 1444 /* If we reboot or kexec let's set the shutdown
4a36297c
LP
1445 * watchdog and tell the shutdown binary to
1446 * repeatedly ping it */
acafd7d8 1447 r = watchdog_set_timeout(&watchdog_timer);
4a36297c
LP
1448 watchdog_close(r < 0);
1449
1450 /* Tell the binary how often to ping, ignore failure */
acafd7d8 1451 if (asprintf(&e, "WATCHDOG_USEC="USEC_FMT, watchdog_timer) > 0)
8a2c1fbf
EJ
1452 (void) strv_consume(&env_block, e);
1453
1454 if (arg_watchdog_device &&
1455 asprintf(&e, "WATCHDOG_DEVICE=%s", arg_watchdog_device) > 0)
1456 (void) strv_consume(&env_block, e);
4a36297c
LP
1457 } else
1458 watchdog_close(true);
1459
1460 /* Avoid the creation of new processes forked by the
1461 * kernel; at this point, we will not listen to the
1462 * signals anyway */
1463 if (detect_container() <= 0)
1464 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
1465
1466 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1467 return -errno;
1468}
1469
e839bafd
LP
1470static void initialize_clock(void) {
1471 int r;
1472
1473 if (clock_is_localtime(NULL) > 0) {
1474 int min;
1475
1476 /*
1477 * The very first call of settimeofday() also does a time warp in the kernel.
1478 *
1479 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to take care
1480 * of maintaining the RTC and do all adjustments. This matches the behavior of Windows, which leaves
1481 * the RTC alone if the registry tells that the RTC runs in UTC.
1482 */
1483 r = clock_set_timezone(&min);
1484 if (r < 0)
1485 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1486 else
1487 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1488
1489 } else if (!in_initrd()) {
1490 /*
1491 * Do a dummy very first call to seal the kernel's time warp magic.
1492 *
1493 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with LOCAL, but the
1494 * real system could be set up that way. In such case, we need to delay the time-warp or the sealing
1495 * until we reach the real system.
1496 *
1497 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably, the time
1498 * will jump or be incorrect at every daylight saving time change. All kernel local time concepts will
1499 * be treated as UTC that way.
1500 */
1501 (void) clock_reset_timewarp();
1502 }
1503
1504 r = clock_apply_epoch();
1505 if (r < 0)
1506 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1507 else if (r > 0)
1508 log_info("System time before build time, advancing clock.");
1509}
1510
1e41242e 1511static void initialize_coredump(bool skip_setup) {
752bcb77 1512#if ENABLE_COREDUMP
1e41242e
LP
1513 if (getpid_cached() != 1)
1514 return;
1515
1516 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour the limit)
1517 * will process core dumps for system services by default. */
1518 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1519 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1520
c6885f5f
FB
1521 /* But at the same time, turn off the core_pattern logic by default, so that no
1522 * coredumps are stored until the systemd-coredump tool is enabled via
1523 * sysctl. However it can be changed via the kernel command line later so core
1524 * dumps can still be generated during early startup and in initramfs. */
1e41242e 1525 if (!skip_setup)
e557b1a6 1526 disable_coredumps();
752bcb77 1527#endif
1e41242e
LP
1528}
1529
c6885f5f
FB
1530static void initialize_core_pattern(bool skip_setup) {
1531 int r;
1532
1533 if (skip_setup || !arg_early_core_pattern)
1534 return;
1535
1536 if (getpid_cached() != 1)
1537 return;
1538
57512c89 1539 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
c6885f5f
FB
1540 if (r < 0)
1541 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m", arg_early_core_pattern);
1542}
1543
61fbbac1
ZJS
1544static void update_cpu_affinity(bool skip_setup) {
1545 _cleanup_free_ char *mask = NULL;
1546
1547 if (skip_setup || !arg_cpu_affinity.set)
1548 return;
1549
1550 assert(arg_cpu_affinity.allocated > 0);
1551
1552 mask = cpu_set_to_string(&arg_cpu_affinity);
1553 log_debug("Setting CPU affinity to %s.", strnull(mask));
1554
1555 if (sched_setaffinity(0, arg_cpu_affinity.allocated, arg_cpu_affinity.set) < 0)
1556 log_warning_errno(errno, "Failed to set CPU affinity: %m");
1557}
1558
b070c7c0
MS
1559static void update_numa_policy(bool skip_setup) {
1560 int r;
1561 _cleanup_free_ char *nodes = NULL;
1562 const char * policy = NULL;
1563
1564 if (skip_setup || !mpol_is_valid(numa_policy_get_type(&arg_numa_policy)))
1565 return;
1566
1567 if (DEBUG_LOGGING) {
1568 policy = mpol_to_string(numa_policy_get_type(&arg_numa_policy));
1569 nodes = cpu_set_to_range_string(&arg_numa_policy.nodes);
1570 log_debug("Setting NUMA policy to %s, with nodes %s.", strnull(policy), strnull(nodes));
1571 }
1572
1573 r = apply_numa_policy(&arg_numa_policy);
1574 if (r == -EOPNOTSUPP)
1575 log_debug_errno(r, "NUMA support not available, ignoring.");
1576 else if (r < 0)
1577 log_warning_errno(r, "Failed to set NUMA memory policy: %m");
1578}
1579
3c7878f9
LP
1580static void do_reexecute(
1581 int argc,
1582 char *argv[],
1583 const struct rlimit *saved_rlimit_nofile,
1584 const struct rlimit *saved_rlimit_memlock,
1585 FDSet *fds,
1586 const char *switch_root_dir,
1587 const char *switch_root_init,
1588 const char **ret_error_message) {
1589
1590 unsigned i, j, args_size;
1591 const char **args;
1592 int r;
1593
1594 assert(saved_rlimit_nofile);
1595 assert(saved_rlimit_memlock);
1596 assert(ret_error_message);
1597
1598 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get rebooted while
1599 * we do that */
1600 watchdog_close(true);
1601
ddfa8b0b
LP
1602 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1603 * the kernel default to its child processes */
1604 if (saved_rlimit_nofile->rlim_cur != 0)
3c7878f9 1605 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
ddfa8b0b 1606 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
3c7878f9
LP
1607 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1608
1609 if (switch_root_dir) {
1610 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1611 * SIGCHLD for them after deserializing. */
e73c54b8 1612 broadcast_signal(SIGTERM, false, true, arg_default_timeout_stop_usec);
3c7878f9
LP
1613
1614 /* And switch root with MS_MOVE, because we remove the old directory afterwards and detach it. */
1615 r = switch_root(switch_root_dir, "/mnt", true, MS_MOVE);
1616 if (r < 0)
1617 log_error_errno(r, "Failed to switch root, trying to continue: %m");
1618 }
1619
1620 args_size = MAX(6, argc+1);
1621 args = newa(const char*, args_size);
1622
1623 if (!switch_root_init) {
1624 char sfd[DECIMAL_STR_MAX(int) + 1];
1625
1626 /* First try to spawn ourselves with the right path, and with full serialization. We do this only if
1627 * the user didn't specify an explicit init to spawn. */
1628
1629 assert(arg_serialization);
1630 assert(fds);
1631
1632 xsprintf(sfd, "%i", fileno(arg_serialization));
1633
1634 i = 0;
1635 args[i++] = SYSTEMD_BINARY_PATH;
1636 if (switch_root_dir)
1637 args[i++] = "--switched-root";
1638 args[i++] = arg_system ? "--system" : "--user";
1639 args[i++] = "--deserialize";
1640 args[i++] = sfd;
1641 args[i++] = NULL;
1642
1643 assert(i <= args_size);
1644
1645 /*
1646 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do this is on
1647 * its own on exec(), but it will do it on exit(). Hence, to ensure we get a summary here, fork() off
1648 * a child, let it exit() cleanly, so that it prints the summary, and wait() for it in the parent,
1649 * before proceeding into the exec().
1650 */
1651 valgrind_summary_hack();
1652
1653 (void) execv(args[0], (char* const*) args);
1654 log_debug_errno(errno, "Failed to execute our own binary, trying fallback: %m");
1655 }
1656
1657 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and envp[]. (Well,
1658 * modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[], but let's hope that
1659 * doesn't matter.) */
1660
1661 arg_serialization = safe_fclose(arg_serialization);
1662 fds = fdset_free(fds);
1663
1664 /* Reopen the console */
1665 (void) make_console_stdio();
1666
1667 for (j = 1, i = 1; j < (unsigned) argc; j++)
1668 args[i++] = argv[j];
1669 args[i++] = NULL;
1670 assert(i <= args_size);
1671
5238e957 1672 /* Re-enable any blocked signals, especially important if we switch from initial ramdisk to init=... */
3c7878f9
LP
1673 (void) reset_all_signal_handlers();
1674 (void) reset_signal_mask();
595225af 1675 (void) rlimit_nofile_safe();
3c7878f9
LP
1676
1677 if (switch_root_init) {
1678 args[0] = switch_root_init;
a5cede8c 1679 (void) execve(args[0], (char* const*) args, saved_env);
3c7878f9
LP
1680 log_warning_errno(errno, "Failed to execute configured init, trying fallback: %m");
1681 }
1682
1683 args[0] = "/sbin/init";
1684 (void) execv(args[0], (char* const*) args);
1685 r = -errno;
1686
1687 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1688 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
1689 "Failed to execute /sbin/init");
1690
1691 if (r == -ENOENT) {
1692 log_warning("No /sbin/init, trying fallback");
1693
1694 args[0] = "/bin/sh";
1695 args[1] = NULL;
a5cede8c 1696 (void) execve(args[0], (char* const*) args, saved_env);
3c7878f9
LP
1697 log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
1698 } else
1699 log_warning_errno(r, "Failed to execute /sbin/init, giving up: %m");
1700
1701 *ret_error_message = "Failed to execute fallback shell";
1702}
1703
7eb35049
LP
1704static int invoke_main_loop(
1705 Manager *m,
a9fd4cd1
FB
1706 const struct rlimit *saved_rlimit_nofile,
1707 const struct rlimit *saved_rlimit_memlock,
7eb35049
LP
1708 bool *ret_reexecute,
1709 int *ret_retval, /* Return parameters relevant for shutting down */
1710 const char **ret_shutdown_verb, /* … */
1711 FDSet **ret_fds, /* Return parameters for reexecuting */
1712 char **ret_switch_root_dir, /* … */
1713 char **ret_switch_root_init, /* … */
1714 const char **ret_error_message) {
1715
1716 int r;
1717
1718 assert(m);
a9fd4cd1
FB
1719 assert(saved_rlimit_nofile);
1720 assert(saved_rlimit_memlock);
7eb35049
LP
1721 assert(ret_reexecute);
1722 assert(ret_retval);
1723 assert(ret_shutdown_verb);
1724 assert(ret_fds);
1725 assert(ret_switch_root_dir);
1726 assert(ret_switch_root_init);
1727 assert(ret_error_message);
1728
1729 for (;;) {
1730 r = manager_loop(m);
1731 if (r < 0) {
1732 *ret_error_message = "Failed to run main loop";
1733 return log_emergency_errno(r, "Failed to run main loop: %m");
1734 }
1735
3ca4d0b3 1736 switch ((ManagerObjective) r) {
7eb35049 1737
a6ecbf83 1738 case MANAGER_RELOAD: {
bda7d78b 1739 LogTarget saved_log_target;
a6ecbf83
FB
1740 int saved_log_level;
1741
7eb35049
LP
1742 log_info("Reloading.");
1743
3fe91079 1744 /* First, save any overridden log level/target, then parse the configuration file, which might
bda7d78b
FB
1745 * change the log level to new settings. */
1746
a6ecbf83 1747 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
bda7d78b 1748 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
a6ecbf83 1749
a9dfac21
CG
1750 mac_selinux_reload();
1751
a9fd4cd1 1752 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
7eb35049
LP
1753
1754 set_manager_defaults(m);
1755
61fbbac1 1756 update_cpu_affinity(false);
b070c7c0 1757 update_numa_policy(false);
61fbbac1 1758
a6ecbf83
FB
1759 if (saved_log_level >= 0)
1760 manager_override_log_level(m, saved_log_level);
bda7d78b
FB
1761 if (saved_log_target >= 0)
1762 manager_override_log_target(m, saved_log_target);
a6ecbf83 1763
7eb35049
LP
1764 r = manager_reload(m);
1765 if (r < 0)
7a35fa24
LP
1766 /* Reloading failed before the point of no return. Let's continue running as if nothing happened. */
1767 m->objective = MANAGER_OK;
7eb35049
LP
1768
1769 break;
a6ecbf83 1770 }
7eb35049
LP
1771
1772 case MANAGER_REEXECUTE:
1773
1774 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
1775 if (r < 0) {
1776 *ret_error_message = "Failed to prepare for reexecution";
1777 return r;
1778 }
1779
1780 log_notice("Reexecuting.");
1781
1782 *ret_reexecute = true;
1783 *ret_retval = EXIT_SUCCESS;
1784 *ret_shutdown_verb = NULL;
1785 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1786
1787 return 0;
1788
1789 case MANAGER_SWITCH_ROOT:
1790 if (!m->switch_root_init) {
1791 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
1792 if (r < 0) {
1793 *ret_error_message = "Failed to prepare for reexecution";
1794 return r;
1795 }
1796 } else
1797 *ret_fds = NULL;
1798
1799 log_notice("Switching root.");
1800
1801 *ret_reexecute = true;
1802 *ret_retval = EXIT_SUCCESS;
1803 *ret_shutdown_verb = NULL;
1804
1805 /* Steal the switch root parameters */
49052946
YW
1806 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1807 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
7eb35049
LP
1808
1809 return 0;
1810
1811 case MANAGER_EXIT:
1812
1813 if (MANAGER_IS_USER(m)) {
1814 log_debug("Exit.");
1815
1816 *ret_reexecute = false;
1817 *ret_retval = m->return_value;
1818 *ret_shutdown_verb = NULL;
1819 *ret_fds = NULL;
1820 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1821
1822 return 0;
1823 }
1824
1825 _fallthrough_;
1826 case MANAGER_REBOOT:
1827 case MANAGER_POWEROFF:
1828 case MANAGER_HALT:
1829 case MANAGER_KEXEC: {
af41e508
LP
1830 static const char * const table[_MANAGER_OBJECTIVE_MAX] = {
1831 [MANAGER_EXIT] = "exit",
1832 [MANAGER_REBOOT] = "reboot",
7eb35049 1833 [MANAGER_POWEROFF] = "poweroff",
af41e508
LP
1834 [MANAGER_HALT] = "halt",
1835 [MANAGER_KEXEC] = "kexec",
7eb35049
LP
1836 };
1837
1838 log_notice("Shutting down.");
1839
1840 *ret_reexecute = false;
1841 *ret_retval = m->return_value;
af41e508 1842 assert_se(*ret_shutdown_verb = table[m->objective]);
7eb35049
LP
1843 *ret_fds = NULL;
1844 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1845
1846 return 0;
1847 }
1848
1849 default:
af41e508 1850 assert_not_reached("Unknown or unexpected manager objective.");
7eb35049
LP
1851 }
1852 }
1853}
1854
31aef7ff
LP
1855static void log_execution_mode(bool *ret_first_boot) {
1856 assert(ret_first_boot);
1857
1858 if (arg_system) {
1859 int v;
1860
681bd2c5 1861 log_info("systemd " GIT_VERSION " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
31aef7ff
LP
1862 arg_action == ACTION_TEST ? "test " : "" );
1863
1864 v = detect_virtualization();
1865 if (v > 0)
1866 log_info("Detected virtualization %s.", virtualization_to_string(v));
1867
1868 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1869
1870 if (in_initrd()) {
1871 *ret_first_boot = false;
1872 log_info("Running in initial RAM disk.");
1873 } else {
1874 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1875 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1876 * doesn't it's unpopulated. This allows container managers and installers to provision a
1877 * couple of files already. If the container manager wants to provision the machine ID itself
1878 * it should pass $container_uuid to PID 1. */
1879
1880 *ret_first_boot = access("/etc/machine-id", F_OK) < 0;
1881 if (*ret_first_boot)
1882 log_info("Running with unpopulated /etc.");
1883 }
1884 } else {
b9e90f3a
LP
1885 if (DEBUG_LOGGING) {
1886 _cleanup_free_ char *t;
31aef7ff 1887
b9e90f3a 1888 t = uid_to_name(getuid());
681bd2c5 1889 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (" SYSTEMD_FEATURES ")",
b9e90f3a
LP
1890 arg_action == ACTION_TEST ? " test" : "", getuid(), strna(t));
1891 }
31aef7ff
LP
1892
1893 *ret_first_boot = false;
1894 }
1895}
1896
5afbaa36
LP
1897static int initialize_runtime(
1898 bool skip_setup,
1899 struct rlimit *saved_rlimit_nofile,
1900 struct rlimit *saved_rlimit_memlock,
1901 const char **ret_error_message) {
5afbaa36
LP
1902 int r;
1903
1904 assert(ret_error_message);
1905
1906 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
1907 *
1908 * - Some only apply to --system instances
1909 * - Some only apply to --user instances
1910 * - Some only apply when we first start up, but not when we reexecute
1911 */
1912
2d776038
LP
1913 if (arg_action != ACTION_RUN)
1914 return 0;
1915
61fbbac1 1916 update_cpu_affinity(skip_setup);
b070c7c0 1917 update_numa_policy(skip_setup);
61fbbac1 1918
3c3c6cb9 1919 if (arg_system) {
5238e957 1920 /* Make sure we leave a core dump without panicking the kernel. */
3c3c6cb9 1921 install_crash_handler();
5afbaa36 1922
3c3c6cb9 1923 if (!skip_setup) {
143fadf3 1924 r = mount_cgroup_controllers();
3c3c6cb9
LP
1925 if (r < 0) {
1926 *ret_error_message = "Failed to mount cgroup hierarchies";
1927 return r;
1928 }
1929
1930 status_welcome();
1931 hostname_setup();
1932 machine_id_setup(NULL, arg_machine_id, NULL);
1933 loopback_setup();
1934 bump_unix_max_dgram_qlen();
a8b627aa 1935 bump_file_max_and_nr_open();
3c3c6cb9
LP
1936 test_usr();
1937 write_container_id();
1938 }
8a2c1fbf 1939
3c3c6cb9
LP
1940 if (arg_watchdog_device) {
1941 r = watchdog_set_device(arg_watchdog_device);
1942 if (r < 0)
1943 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
1944 }
1945
1f65fd49 1946 if (timestamp_is_set(arg_runtime_watchdog))
3c3c6cb9
LP
1947 watchdog_set_timeout(&arg_runtime_watchdog);
1948 }
5afbaa36
LP
1949
1950 if (arg_timer_slack_nsec != NSEC_INFINITY)
1951 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
3a671cd1 1952 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
5afbaa36
LP
1953
1954 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
1955 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
1956 if (r < 0) {
1957 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
1958 return log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
1959 }
1960
1961 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
1962 if (r < 0) {
1963 *ret_error_message = "Failed to drop capability bounding set";
1964 return log_emergency_errno(r, "Failed to drop capability bounding set: %m");
1965 }
1966 }
1967
39362f6f
JB
1968 if (arg_system && arg_no_new_privs) {
1969 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1970 *ret_error_message = "Failed to disable new privileges";
1971 return log_emergency_errno(errno, "Failed to disable new privileges: %m");
1972 }
1973 }
1974
5afbaa36
LP
1975 if (arg_syscall_archs) {
1976 r = enforce_syscall_archs(arg_syscall_archs);
1977 if (r < 0) {
1978 *ret_error_message = "Failed to set syscall architectures";
1979 return r;
1980 }
1981 }
1982
1983 if (!arg_system)
1984 /* Become reaper of our children */
1985 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
1986 log_warning_errno(errno, "Failed to make us a subreaper: %m");
1987
a17c1712
LP
1988 /* Bump up RLIMIT_NOFILE for systemd itself */
1989 (void) bump_rlimit_nofile(saved_rlimit_nofile);
1990 (void) bump_rlimit_memlock(saved_rlimit_memlock);
5afbaa36
LP
1991
1992 return 0;
1993}
1994
6acca5fc
LP
1995static int do_queue_default_job(
1996 Manager *m,
1997 const char **ret_error_message) {
1998
1999 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
8755dbad 2000 const char* default_unit;
6acca5fc
LP
2001 Job *default_unit_job;
2002 Unit *target = NULL;
2003 int r;
2004
8755dbad
ZJS
2005 if (arg_default_unit)
2006 default_unit = arg_default_unit;
2007 else if (in_initrd())
2008 default_unit = SPECIAL_INITRD_TARGET;
2009 else
2010 default_unit = SPECIAL_DEFAULT_TARGET;
2011
2012 log_debug("Activating default unit: %s", default_unit);
2013
2014 r = manager_load_startable_unit_or_warn(m, default_unit, NULL, &target);
2015 if (r < 0 && in_initrd() && !arg_default_unit) {
2016 /* Fall back to default.target, which we used to always use by default. Only do this if no
2017 * explicit configuration was given. */
2018
2019 log_info("Falling back to " SPECIAL_DEFAULT_TARGET ".");
6acca5fc 2020
8755dbad
ZJS
2021 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2022 }
4109ede7 2023 if (r < 0) {
8755dbad 2024 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
6acca5fc 2025
4109ede7 2026 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
6acca5fc 2027 if (r < 0) {
8755dbad
ZJS
2028 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2029 : "Failed to load " SPECIAL_RESCUE_TARGET;
4109ede7 2030 return r;
6acca5fc
LP
2031 }
2032 }
2033
2034 assert(target->load_state == UNIT_LOADED);
2035
50cbaba4 2036 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &default_unit_job);
6acca5fc
LP
2037 if (r == -EPERM) {
2038 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2039
2040 sd_bus_error_free(&error);
2041
50cbaba4 2042 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &default_unit_job);
6acca5fc
LP
2043 if (r < 0) {
2044 *ret_error_message = "Failed to start default target";
2045 return log_emergency_errno(r, "Failed to start default target: %s", bus_error_message(&error, r));
2046 }
2047
2048 } else if (r < 0) {
2049 *ret_error_message = "Failed to isolate default target";
2050 return log_emergency_errno(r, "Failed to isolate default target: %s", bus_error_message(&error, r));
2051 }
2052
2053 m->default_unit_job_id = default_unit_job->id;
2054
2055 return 0;
2056}
2057
a9fd4cd1
FB
2058static void save_rlimits(struct rlimit *saved_rlimit_nofile,
2059 struct rlimit *saved_rlimit_memlock) {
2060
2061 assert(saved_rlimit_nofile);
2062 assert(saved_rlimit_memlock);
2063
2064 if (getrlimit(RLIMIT_NOFILE, saved_rlimit_nofile) < 0)
2065 log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2066
2067 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock) < 0)
2068 log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2069}
2070
2071static void fallback_rlimit_nofile(const struct rlimit *saved_rlimit_nofile) {
2072 struct rlimit *rl;
2073
2074 if (arg_default_rlimit[RLIMIT_NOFILE])
2075 return;
2076
2077 /* Make sure forked processes get limits based on the original kernel setting */
2078
2079 rl = newdup(struct rlimit, saved_rlimit_nofile, 1);
2080 if (!rl) {
2081 log_oom();
2082 return;
2083 }
2084
2085 /* Bump the hard limit for system services to a substantially higher value. The default
2086 * hard limit current kernels set is pretty low (4K), mostly for historical
2087 * reasons. According to kernel developers, the fd handling in recent kernels has been
2088 * optimized substantially enough, so that we can bump the limit now, without paying too
2089 * high a price in memory or performance. Note however that we only bump the hard limit,
2090 * not the soft limit. That's because select() works the way it works, and chokes on fds
2091 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2092 * unexpecting programs that they get fds higher than what they can process using
2093 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2094 * this pitfall: programs that are written by folks aware of the select() problem in mind
2095 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2096 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2097 * we pass. */
2098 if (arg_system) {
2099 int nr;
2100
2101 /* Get the underlying absolute limit the kernel enforces */
2102 nr = read_nr_open();
2103
2104 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
2105 }
2106
2107 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2108 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2109 * instance), then lower what we pass on to not confuse our children */
2110 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
2111
2112 arg_default_rlimit[RLIMIT_NOFILE] = rl;
2113}
2114
2115static void fallback_rlimit_memlock(const struct rlimit *saved_rlimit_memlock) {
2116 struct rlimit *rl;
2117
2118 /* Pass the original value down to invoked processes */
2119
2120 if (arg_default_rlimit[RLIMIT_MEMLOCK])
2121 return;
2122
2123 rl = newdup(struct rlimit, saved_rlimit_memlock, 1);
2124 if (!rl) {
2125 log_oom();
2126 return;
2127 }
2128
2129 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
2130}
2131
fb39af4c
ZJS
2132static void reset_arguments(void) {
2133 /* Frees/resets arg_* variables, with a few exceptions commented below. */
970777b5
LP
2134
2135 arg_default_unit = mfree(arg_default_unit);
fb39af4c
ZJS
2136
2137 /* arg_system — ignore */
2138
2139 arg_dump_core = true;
2140 arg_crash_chvt = -1;
2141 arg_crash_shell = false;
2142 arg_crash_reboot = false;
970777b5 2143 arg_confirm_spawn = mfree(arg_confirm_spawn);
fb39af4c 2144 arg_show_status = _SHOW_STATUS_INVALID;
36cf4507 2145 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
fb39af4c
ZJS
2146 arg_switched_root = false;
2147 arg_pager_flags = 0;
2148 arg_service_watchdogs = true;
2149 arg_default_std_output = EXEC_OUTPUT_JOURNAL;
2150 arg_default_std_error = EXEC_OUTPUT_INHERIT;
2151 arg_default_restart_usec = DEFAULT_RESTART_USEC;
2152 arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
2153 arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
2154 arg_default_timeout_abort_usec = DEFAULT_TIMEOUT_USEC;
2155 arg_default_timeout_abort_set = false;
2156 arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
2157 arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
2158 arg_runtime_watchdog = 0;
65224c1d 2159 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
acafd7d8 2160 arg_kexec_watchdog = 0;
fb39af4c
ZJS
2161 arg_early_core_pattern = NULL;
2162 arg_watchdog_device = NULL;
2163
970777b5 2164 arg_default_environment = strv_free(arg_default_environment);
fb39af4c
ZJS
2165 rlimit_free_all(arg_default_rlimit);
2166
2167 arg_capability_bounding_set = CAP_ALL;
2168 arg_no_new_privs = false;
2169 arg_timer_slack_nsec = NSEC_INFINITY;
2170 arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
2171
970777b5 2172 arg_syscall_archs = set_free(arg_syscall_archs);
61fbbac1 2173
fb39af4c
ZJS
2174 /* arg_serialization — ignore */
2175
2176 arg_default_cpu_accounting = -1;
2177 arg_default_io_accounting = false;
2178 arg_default_ip_accounting = false;
2179 arg_default_blockio_accounting = false;
2180 arg_default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT;
2181 arg_default_tasks_accounting = true;
3a0f06c4 2182 arg_default_tasks_max = DEFAULT_TASKS_MAX;
fb39af4c
ZJS
2183 arg_machine_id = (sd_id128_t) {};
2184 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
2185 arg_default_oom_policy = OOM_STOP;
2186
61fbbac1 2187 cpu_set_reset(&arg_cpu_affinity);
b070c7c0 2188 numa_policy_reset(&arg_numa_policy);
970777b5
LP
2189}
2190
a9fd4cd1
FB
2191static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2192 const struct rlimit *saved_rlimit_memlock) {
97d1fb94
LP
2193 int r;
2194
a9fd4cd1
FB
2195 assert(saved_rlimit_nofile);
2196 assert(saved_rlimit_memlock);
2197
fb39af4c
ZJS
2198 /* Assign configuration defaults */
2199 reset_arguments();
2200
97d1fb94 2201 r = parse_config_file();
470a5e6d
ZJS
2202 if (r < 0)
2203 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
97d1fb94
LP
2204
2205 if (arg_system) {
2206 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2207 if (r < 0)
2208 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2209 }
2210
a9fd4cd1
FB
2211 /* Initialize some default rlimits for services if they haven't been configured */
2212 fallback_rlimit_nofile(saved_rlimit_nofile);
2213 fallback_rlimit_memlock(saved_rlimit_memlock);
2214
97d1fb94
LP
2215 /* Note that this also parses bits from the kernel command line, including "debug". */
2216 log_parse_environment();
2217
470a5e6d
ZJS
2218 return 0;
2219}
2220
a9fd4cd1
FB
2221static int load_configuration(
2222 int argc,
2223 char **argv,
2224 const struct rlimit *saved_rlimit_nofile,
2225 const struct rlimit *saved_rlimit_memlock,
2226 const char **ret_error_message) {
470a5e6d
ZJS
2227 int r;
2228
a9fd4cd1
FB
2229 assert(saved_rlimit_nofile);
2230 assert(saved_rlimit_memlock);
470a5e6d
ZJS
2231 assert(ret_error_message);
2232
a9fd4cd1 2233 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
470a5e6d 2234
97d1fb94
LP
2235 r = parse_argv(argc, argv);
2236 if (r < 0) {
2237 *ret_error_message = "Failed to parse commandline arguments";
2238 return r;
2239 }
2240
db33214b 2241 /* Initialize the show status setting if it hasn't been set explicitly yet */
7a293242 2242 if (arg_show_status == _SHOW_STATUS_INVALID)
db33214b
LP
2243 arg_show_status = SHOW_STATUS_YES;
2244
97d1fb94
LP
2245 return 0;
2246}
2247
b0d7c989
LP
2248static int safety_checks(void) {
2249
febf46a4 2250 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2251 arg_action != ACTION_RUN)
2252 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2253 "Unsupported execution mode while PID 1.");
febf46a4
LP
2254
2255 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2256 !arg_system)
2257 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2258 "Can't run --user mode as PID 1.");
febf46a4
LP
2259
2260 if (arg_action == ACTION_RUN &&
2261 arg_system &&
baaa35ad
ZJS
2262 getpid_cached() != 1)
2263 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2264 "Can't run system mode unless PID 1.");
febf46a4 2265
b0d7c989 2266 if (arg_action == ACTION_TEST &&
baaa35ad
ZJS
2267 geteuid() == 0)
2268 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2269 "Don't run test mode as root.");
b0d7c989
LP
2270
2271 if (!arg_system &&
2272 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2273 sd_booted() <= 0)
2274 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2275 "Trying to run as user instance, but the system has not been booted with systemd.");
b0d7c989
LP
2276
2277 if (!arg_system &&
2278 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2279 !getenv("XDG_RUNTIME_DIR"))
2280 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2281 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
b0d7c989
LP
2282
2283 if (arg_system &&
2284 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2285 running_in_chroot() > 0)
2286 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2287 "Cannot be run in a chroot() environment.");
b0d7c989
LP
2288
2289 return 0;
2290}
2291
74da609f
LP
2292static int initialize_security(
2293 bool *loaded_policy,
2294 dual_timestamp *security_start_timestamp,
2295 dual_timestamp *security_finish_timestamp,
2296 const char **ret_error_message) {
2297
2298 int r;
2299
2300 assert(loaded_policy);
2301 assert(security_start_timestamp);
2302 assert(security_finish_timestamp);
2303 assert(ret_error_message);
2304
2305 dual_timestamp_get(security_start_timestamp);
2306
97149f40 2307 r = mac_selinux_setup(loaded_policy);
74da609f
LP
2308 if (r < 0) {
2309 *ret_error_message = "Failed to load SELinux policy";
2310 return r;
2311 }
2312
2313 r = mac_smack_setup(loaded_policy);
2314 if (r < 0) {
2315 *ret_error_message = "Failed to load SMACK policy";
2316 return r;
2317 }
2318
2319 r = ima_setup();
2320 if (r < 0) {
2321 *ret_error_message = "Failed to load IMA policy";
2322 return r;
2323 }
2324
2325 dual_timestamp_get(security_finish_timestamp);
2326 return 0;
2327}
2328
263162da
LP
2329static void test_summary(Manager *m) {
2330 assert(m);
2331
2332 printf("-> By units:\n");
2333 manager_dump_units(m, stdout, "\t");
2334
2335 printf("-> By jobs:\n");
2336 manager_dump_jobs(m, stdout, "\t");
2337}
2338
efeb853f
LP
2339static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2340 int r;
2341
2342 assert(ret_fds);
2343 assert(ret_error_message);
2344
2345 r = fdset_new_fill(ret_fds);
2346 if (r < 0) {
2347 *ret_error_message = "Failed to allocate fd set";
2348 return log_emergency_errno(r, "Failed to allocate fd set: %m");
2349 }
2350
2351 fdset_cloexec(*ret_fds, true);
2352
2353 if (arg_serialization)
2354 assert_se(fdset_remove(*ret_fds, fileno(arg_serialization)) >= 0);
2355
2356 return 0;
2357}
2358
2e51b31c
LP
2359static void setup_console_terminal(bool skip_setup) {
2360
2361 if (!arg_system)
2362 return;
2363
2364 /* Become a session leader if we aren't one yet. */
2365 (void) setsid();
2366
2367 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a controlling
2368 * tty. */
2369 (void) release_terminal();
2370
2371 /* Reset the console, but only if this is really init and we are freshly booted */
2372 if (getpid_cached() == 1 && !skip_setup)
2373 (void) console_setup();
2374}
2375
aa40ff07
LP
2376static bool early_skip_setup_check(int argc, char *argv[]) {
2377 bool found_deserialize = false;
2378 int i;
2379
2380 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much later, so
2381 * let's just have a quick peek here. Note that if we have switched root, do all the special setup things
2382 * anyway, even if in that case we also do deserialization. */
2383
2384 for (i = 1; i < argc; i++) {
aa40ff07
LP
2385 if (streq(argv[i], "--switched-root"))
2386 return false; /* If we switched root, don't skip the setup. */
2387 else if (streq(argv[i], "--deserialize"))
2388 found_deserialize = true;
2389 }
2390
2391 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2392}
2393
0e06a031
LP
2394static int save_env(void) {
2395 char **l;
2396
2397 l = strv_copy(environ);
2398 if (!l)
2399 return -ENOMEM;
2400
2401 strv_free_and_replace(saved_env, l);
2402 return 0;
2403}
2404
60918275 2405int main(int argc, char *argv[]) {
625e8690
LP
2406
2407 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL, userspace_timestamp = DUAL_TIMESTAMP_NULL, kernel_timestamp = DUAL_TIMESTAMP_NULL,
2408 security_start_timestamp = DUAL_TIMESTAMP_NULL, security_finish_timestamp = DUAL_TIMESTAMP_NULL;
ddfa8b0b
LP
2409 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2410 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2411 * in. Note we use different values
2412 * for the two that indicate whether
2413 * these fields are initialized! */
625e8690
LP
2414 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false, reexecute = false;
2415 char *switch_root_dir = NULL, *switch_root_init = NULL;
9d76d730 2416 usec_t before_startup, after_startup;
625e8690 2417 static char systemd[] = "systemd";
9d76d730 2418 char timespan[FORMAT_TIMESPAN_MAX];
625e8690
LP
2419 const char *shutdown_verb = NULL, *error_message = NULL;
2420 int r, retval = EXIT_FAILURE;
2421 Manager *m = NULL;
a16e1123 2422 FDSet *fds = NULL;
27b14a22 2423
d72a8f10 2424 /* SysV compatibility: redirect init → telinit */
6808a0bc 2425 redirect_telinit(argc, argv);
2cb1a60d 2426
d72a8f10 2427 /* Take timestamps early on */
c3a170f3
HH
2428 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2429 dual_timestamp_get(&userspace_timestamp);
2430
d72a8f10
LP
2431 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2432 * reexecuting */
aa40ff07 2433 skip_setup = early_skip_setup_check(argc, argv);
d03bc1b8 2434
d72a8f10
LP
2435 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent reexecution we
2436 * are then called 'systemd'. That is confusing, hence let's call us systemd right-away. */
f3b6a3ed 2437 program_invocation_short_name = systemd;
eee8b7ab 2438 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 2439
d72a8f10 2440 /* Save the original command line */
36fea155 2441 save_argc_argv(argc, argv);
f3b6a3ed 2442
0e06a031
LP
2443 /* Save the original environment as we might need to restore it if we're requested to execute another
2444 * system manager later. */
2445 r = save_env();
2446 if (r < 0) {
2447 error_message = "Failed to copy environment block";
2448 goto finish;
2449 }
a5cede8c 2450
6fdb8de4 2451 /* Make sure that if the user says "syslog" we actually log to the journal. */
c1dc6153 2452 log_set_upgrade_syslog_to_journal(true);
bbe63281 2453
df0ff127 2454 if (getpid_cached() == 1) {
b5752d23
LP
2455 /* When we run as PID 1 force system mode */
2456 arg_system = true;
2457
48a601fe 2458 /* Disable the umask logic */
90dc8c2e
MG
2459 umask(0);
2460
92890452
LP
2461 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might not be
2462 * activated yet (even though the log socket for it exists). */
d075092f
LP
2463 log_set_prohibit_ipc(true);
2464
48a601fe
LP
2465 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
2466 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
2467 * child process right before execve()'ing the actual binary, at a point in time where socket
2468 * activation stderr/stdout area already set up. */
2469 log_set_always_reopen_console(true);
48a601fe 2470
92890452 2471 if (detect_container() <= 0) {
4f8d551f 2472
92890452 2473 /* Running outside of a container as PID 1 */
92890452
LP
2474 log_set_target(LOG_TARGET_KMSG);
2475 log_open();
a866073d 2476
92890452
LP
2477 if (in_initrd())
2478 initrd_timestamp = userspace_timestamp;
c3ba6250 2479
92890452
LP
2480 if (!skip_setup) {
2481 r = mount_setup_early();
2482 if (r < 0) {
2483 error_message = "Failed to mount early API filesystems";
2484 goto finish;
2485 }
2486
0a2eef1e
LP
2487 /* Let's open the log backend a second time, in case the first time didn't
2488 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2489 * available, and it previously wasn't. */
2490 log_open();
2491
6123dfaa
ZJS
2492 disable_printk_ratelimit();
2493
92890452
LP
2494 r = initialize_security(
2495 &loaded_policy,
2496 &security_start_timestamp,
2497 &security_finish_timestamp,
2498 &error_message);
2499 if (r < 0)
2500 goto finish;
d723cd65 2501 }
eee8b7ab 2502
92890452
LP
2503 if (mac_selinux_init() < 0) {
2504 error_message = "Failed to initialize SELinux policy";
96694e99 2505 goto finish;
92890452 2506 }
0b3325e7 2507
92890452
LP
2508 if (!skip_setup)
2509 initialize_clock();
2510
2511 /* Set the default for later on, but don't actually open the logs like this for now. Note that
2512 * if we are transitioning from the initrd there might still be journal fd open, and we
2513 * shouldn't attempt opening that before we parsed /proc/cmdline which might redirect output
2514 * elsewhere. */
2515 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2516
2517 } else {
2518 /* Running inside a container, as PID 1 */
92890452
LP
2519 log_set_target(LOG_TARGET_CONSOLE);
2520 log_open();
2521
2522 /* For later on, see above... */
2523 log_set_target(LOG_TARGET_JOURNAL);
2524
2525 /* clear the kernel timestamp,
2526 * because we are in a container */
2527 kernel_timestamp = DUAL_TIMESTAMP_NULL;
cb6531be 2528 }
7948c4df 2529
92890452 2530 initialize_coredump(skip_setup);
a866073d 2531
92890452
LP
2532 r = fixup_environment();
2533 if (r < 0) {
2534 log_emergency_errno(r, "Failed to fix up PID 1 environment: %m");
2535 error_message = "Failed to fix up PID1 environment";
2536 goto finish;
2537 }
a866073d 2538
c3a170f3 2539 } else {
a866073d 2540 /* Running as user instance */
463d0d15 2541 arg_system = false;
eeecf6e6 2542 log_set_target(LOG_TARGET_AUTO);
871e5809 2543 log_open();
c3a170f3
HH
2544
2545 /* clear the kernel timestamp,
2546 * because we are not PID 1 */
6513d561 2547 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 2548 }
a5dab5ce 2549
6edefe0b 2550 if (arg_system) {
92890452
LP
2551 /* Try to figure out if we can use colors with the console. No need to do that for user instances since
2552 * they never log into the console. */
3a18b604 2553 log_show_color(colors_enabled());
92890452 2554
c76cf844
AK
2555 r = make_null_stdio();
2556 if (r < 0)
92890452 2557 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
3a18b604
FB
2558 }
2559
f170852a
LP
2560 /* Mount /proc, /sys and friends, so that /proc/cmdline and
2561 * /proc/$PID/fd is available. */
df0ff127 2562 if (getpid_cached() == 1) {
f84f9974 2563
a132bef0 2564 /* Load the kernel modules early. */
2e75e2a8
DM
2565 if (!skip_setup)
2566 kmod_setup();
2e75e2a8 2567
0c85a4f3 2568 r = mount_setup(loaded_policy);
cb6531be
ZJS
2569 if (r < 0) {
2570 error_message = "Failed to mount API filesystems";
8efe3c01 2571 goto finish;
cb6531be 2572 }
c18ecf03
LP
2573
2574 /* The efivarfs is now mounted, let's read the random seed off it */
2575 (void) efi_take_random_seed();
0c85a4f3 2576 }
4ade7963 2577
a9fd4cd1
FB
2578 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2579 * transitioning from the initrd to the main systemd or suchlike. */
2580 save_rlimits(&saved_rlimit_nofile, &saved_rlimit_memlock);
2581
4ade7963 2582 /* Reset all signal handlers. */
ce30c8dc
LP
2583 (void) reset_all_signal_handlers();
2584 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 2585
a9fd4cd1 2586 r = load_configuration(argc, argv, &saved_rlimit_nofile, &saved_rlimit_memlock, &error_message);
97d1fb94 2587 if (r < 0)
f170852a 2588 goto finish;
10c961b9 2589
b0d7c989
LP
2590 r = safety_checks();
2591 if (r < 0)
fe783b03 2592 goto finish;
fe783b03 2593
bbc1acab 2594 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES))
0221d68a 2595 (void) pager_open(arg_pager_flags);
b0d7c989
LP
2596
2597 if (arg_action != ACTION_RUN)
74e7579c 2598 skip_setup = true;
b87c2aa6 2599
fa0f4d8a 2600 if (arg_action == ACTION_HELP) {
37ec0fdd 2601 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
f170852a 2602 goto finish;
9ba0bc4e
ZJS
2603 } else if (arg_action == ACTION_VERSION) {
2604 retval = version();
2605 goto finish;
fa0f4d8a 2606 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 2607 unit_dump_config_items(stdout);
22f4096c 2608 retval = EXIT_SUCCESS;
e537352b 2609 goto finish;
bbc1acab
YW
2610 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2611 dump_bus_properties(stdout);
2612 retval = EXIT_SUCCESS;
2613 goto finish;
f170852a
LP
2614 }
2615
4c701096 2616 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
f170852a 2617
5a2e0c62
LP
2618 /* Move out of the way, so that we won't block unmounts */
2619 assert_se(chdir("/") == 0);
2620
dea374e8 2621 if (arg_action == ACTION_RUN) {
a70c72a0 2622
c6885f5f
FB
2623 /* A core pattern might have been specified via the cmdline. */
2624 initialize_core_pattern(skip_setup);
2625
efeb853f 2626 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
a70c72a0
LP
2627 log_close();
2628
2629 /* Remember open file descriptors for later deserialization */
efeb853f
LP
2630 r = collect_fds(&fds, &error_message);
2631 if (r < 0)
dea374e8 2632 goto finish;
a16e1123 2633
2e51b31c
LP
2634 /* Give up any control of the console, but make sure its initialized. */
2635 setup_console_terminal(skip_setup);
56d96fc0 2636
a70c72a0
LP
2637 /* Open the logging devices, if possible and necessary */
2638 log_open();
56d96fc0 2639 }
4ade7963 2640
31aef7ff 2641 log_execution_mode(&first_boot);
a5dab5ce 2642
2d776038
LP
2643 r = initialize_runtime(skip_setup,
2644 &saved_rlimit_nofile,
2645 &saved_rlimit_memlock,
2646 &error_message);
2647 if (r < 0)
2648 goto finish;
4096d6f5 2649
e0a3da1f
ZJS
2650 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2651 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2652 &m);
e96d6be7 2653 if (r < 0) {
da927ba9 2654 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 2655 error_message = "Failed to allocate manager object";
60918275
LP
2656 goto finish;
2657 }
2658
9f9f0342
LP
2659 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2660 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2661 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
d4ee7bd8
YW
2662 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
2663 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
9e58ff9c 2664
85cb4151 2665 set_manager_defaults(m);
7b46fc6a 2666 set_manager_settings(m);
fd130612 2667 manager_set_first_boot(m, first_boot);
27d340c7 2668
bf4df7c3 2669 /* Remember whether we should queue the default job */
d3b1c508 2670 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 2671
9d76d730
LP
2672 before_startup = now(CLOCK_MONOTONIC);
2673
d3b1c508 2674 r = manager_startup(m, arg_serialization, fds);
58f88d92 2675 if (r < 0) {
cefb3eda 2676 error_message = "Failed to start up manager";
58f88d92
ZJS
2677 goto finish;
2678 }
a16e1123 2679
6acca5fc 2680 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2feceb5e 2681 fds = fdset_free(fds);
74ca738f 2682 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
2683
2684 if (queue_default_job) {
6acca5fc 2685 r = do_queue_default_job(m, &error_message);
718db961 2686 if (r < 0)
37d88da7 2687 goto finish;
6acca5fc 2688 }
ab17a050 2689
6acca5fc 2690 after_startup = now(CLOCK_MONOTONIC);
60918275 2691
6acca5fc
LP
2692 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2693 "Loaded units and determined initial transaction in %s.",
2694 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 2695
6acca5fc 2696 if (arg_action == ACTION_TEST) {
263162da 2697 test_summary(m);
6acca5fc
LP
2698 retval = EXIT_SUCCESS;
2699 goto finish;
e965d56d 2700 }
d46de8a1 2701
3046b6db 2702 (void) invoke_main_loop(m,
a9fd4cd1
FB
2703 &saved_rlimit_nofile,
2704 &saved_rlimit_memlock,
3046b6db
LP
2705 &reexecute,
2706 &retval,
2707 &shutdown_verb,
2708 &fds,
2709 &switch_root_dir,
2710 &switch_root_init,
2711 &error_message);
f170852a 2712
60918275 2713finish:
b87c2aa6
ZJS
2714 pager_close();
2715
92890452 2716 if (m) {
65224c1d 2717 arg_reboot_watchdog = m->reboot_watchdog;
acafd7d8 2718 arg_kexec_watchdog = m->kexec_watchdog;
92890452
LP
2719 m = manager_free(m);
2720 }
60918275 2721
fb39af4c 2722 reset_arguments();
cc56fafe 2723 mac_selinux_finish();
b2bb3dbe 2724
3c7878f9
LP
2725 if (reexecute)
2726 do_reexecute(argc, argv,
2727 &saved_rlimit_nofile,
2728 &saved_rlimit_memlock,
2729 fds,
2730 switch_root_dir,
2731 switch_root_init,
2732 &error_message); /* This only returns if reexecution failed */
a16e1123 2733
74ca738f 2734 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2735 fds = fdset_free(fds);
a16e1123 2736
0e06a031
LP
2737 saved_env = strv_free(saved_env);
2738
349cc4a5 2739#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
2740 /* If we are PID 1 and running under valgrind, then let's exit
2741 * here explicitly. valgrind will only generate nice output on
2742 * exit(), not on exec(), hence let's do the former not the
2743 * latter here. */
8a2c1fbf
EJ
2744 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
2745 /* Cleanup watchdog_device strings for valgrind. We need them
2746 * in become_shutdown() so normally we cannot free them yet. */
2747 watchdog_free_device();
2748 arg_watchdog_device = mfree(arg_watchdog_device);
27fe58b7 2749 return retval;
8a2c1fbf 2750 }
54b434b1
LP
2751#endif
2752
7e11a95e
EV
2753#if HAS_FEATURE_ADDRESS_SANITIZER
2754 __lsan_do_leak_check();
2755#endif
2756
b9080b03 2757 if (shutdown_verb) {
7eb35049 2758 r = become_shutdown(shutdown_verb, retval);
4a36297c 2759 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
9b9881d7 2760 error_message = "Failed to execute shutdown binary";
b9080b03
FF
2761 }
2762
8a2c1fbf
EJ
2763 watchdog_free_device();
2764 arg_watchdog_device = mfree(arg_watchdog_device);
2765
df0ff127 2766 if (getpid_cached() == 1) {
cb6531be
ZJS
2767 if (error_message)
2768 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 2769 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
bb259772
LP
2770 "%s.", error_message);
2771 freeze_or_exit_or_reboot();
cb6531be 2772 }
c3b3c274 2773
60918275
LP
2774 return retval;
2775}