]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
fix journalctl regression (#15099)
[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)
0d066dd1 497 arg_show_status = SHOW_STATUS_ERROR;
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
a9fd4cd1 1750 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
7eb35049
LP
1751
1752 set_manager_defaults(m);
1753
61fbbac1 1754 update_cpu_affinity(false);
b070c7c0 1755 update_numa_policy(false);
61fbbac1 1756
a6ecbf83
FB
1757 if (saved_log_level >= 0)
1758 manager_override_log_level(m, saved_log_level);
bda7d78b
FB
1759 if (saved_log_target >= 0)
1760 manager_override_log_target(m, saved_log_target);
a6ecbf83 1761
7eb35049
LP
1762 r = manager_reload(m);
1763 if (r < 0)
7a35fa24
LP
1764 /* Reloading failed before the point of no return. Let's continue running as if nothing happened. */
1765 m->objective = MANAGER_OK;
7eb35049
LP
1766
1767 break;
a6ecbf83 1768 }
7eb35049
LP
1769
1770 case MANAGER_REEXECUTE:
1771
1772 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
1773 if (r < 0) {
1774 *ret_error_message = "Failed to prepare for reexecution";
1775 return r;
1776 }
1777
1778 log_notice("Reexecuting.");
1779
1780 *ret_reexecute = true;
1781 *ret_retval = EXIT_SUCCESS;
1782 *ret_shutdown_verb = NULL;
1783 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1784
1785 return 0;
1786
1787 case MANAGER_SWITCH_ROOT:
1788 if (!m->switch_root_init) {
1789 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
1790 if (r < 0) {
1791 *ret_error_message = "Failed to prepare for reexecution";
1792 return r;
1793 }
1794 } else
1795 *ret_fds = NULL;
1796
1797 log_notice("Switching root.");
1798
1799 *ret_reexecute = true;
1800 *ret_retval = EXIT_SUCCESS;
1801 *ret_shutdown_verb = NULL;
1802
1803 /* Steal the switch root parameters */
49052946
YW
1804 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
1805 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
7eb35049
LP
1806
1807 return 0;
1808
1809 case MANAGER_EXIT:
1810
1811 if (MANAGER_IS_USER(m)) {
1812 log_debug("Exit.");
1813
1814 *ret_reexecute = false;
1815 *ret_retval = m->return_value;
1816 *ret_shutdown_verb = NULL;
1817 *ret_fds = NULL;
1818 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1819
1820 return 0;
1821 }
1822
1823 _fallthrough_;
1824 case MANAGER_REBOOT:
1825 case MANAGER_POWEROFF:
1826 case MANAGER_HALT:
1827 case MANAGER_KEXEC: {
af41e508
LP
1828 static const char * const table[_MANAGER_OBJECTIVE_MAX] = {
1829 [MANAGER_EXIT] = "exit",
1830 [MANAGER_REBOOT] = "reboot",
7eb35049 1831 [MANAGER_POWEROFF] = "poweroff",
af41e508
LP
1832 [MANAGER_HALT] = "halt",
1833 [MANAGER_KEXEC] = "kexec",
7eb35049
LP
1834 };
1835
1836 log_notice("Shutting down.");
1837
1838 *ret_reexecute = false;
1839 *ret_retval = m->return_value;
af41e508 1840 assert_se(*ret_shutdown_verb = table[m->objective]);
7eb35049
LP
1841 *ret_fds = NULL;
1842 *ret_switch_root_dir = *ret_switch_root_init = NULL;
1843
1844 return 0;
1845 }
1846
1847 default:
af41e508 1848 assert_not_reached("Unknown or unexpected manager objective.");
7eb35049
LP
1849 }
1850 }
1851}
1852
31aef7ff
LP
1853static void log_execution_mode(bool *ret_first_boot) {
1854 assert(ret_first_boot);
1855
1856 if (arg_system) {
1857 int v;
1858
681bd2c5 1859 log_info("systemd " GIT_VERSION " running in %ssystem mode. (" SYSTEMD_FEATURES ")",
31aef7ff
LP
1860 arg_action == ACTION_TEST ? "test " : "" );
1861
1862 v = detect_virtualization();
1863 if (v > 0)
1864 log_info("Detected virtualization %s.", virtualization_to_string(v));
1865
1866 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
1867
1868 if (in_initrd()) {
1869 *ret_first_boot = false;
1870 log_info("Running in initial RAM disk.");
1871 } else {
1872 /* Let's check whether we are in first boot, i.e. whether /etc is still unpopulated. We use
1873 * /etc/machine-id as flag file, for this: if it exists we assume /etc is populated, if it
1874 * doesn't it's unpopulated. This allows container managers and installers to provision a
1875 * couple of files already. If the container manager wants to provision the machine ID itself
1876 * it should pass $container_uuid to PID 1. */
1877
1878 *ret_first_boot = access("/etc/machine-id", F_OK) < 0;
1879 if (*ret_first_boot)
1880 log_info("Running with unpopulated /etc.");
1881 }
1882 } else {
b9e90f3a
LP
1883 if (DEBUG_LOGGING) {
1884 _cleanup_free_ char *t;
31aef7ff 1885
b9e90f3a 1886 t = uid_to_name(getuid());
681bd2c5 1887 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (" SYSTEMD_FEATURES ")",
b9e90f3a
LP
1888 arg_action == ACTION_TEST ? " test" : "", getuid(), strna(t));
1889 }
31aef7ff
LP
1890
1891 *ret_first_boot = false;
1892 }
1893}
1894
5afbaa36
LP
1895static int initialize_runtime(
1896 bool skip_setup,
1897 struct rlimit *saved_rlimit_nofile,
1898 struct rlimit *saved_rlimit_memlock,
1899 const char **ret_error_message) {
5afbaa36
LP
1900 int r;
1901
1902 assert(ret_error_message);
1903
1904 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
1905 *
1906 * - Some only apply to --system instances
1907 * - Some only apply to --user instances
1908 * - Some only apply when we first start up, but not when we reexecute
1909 */
1910
2d776038
LP
1911 if (arg_action != ACTION_RUN)
1912 return 0;
1913
61fbbac1 1914 update_cpu_affinity(skip_setup);
b070c7c0 1915 update_numa_policy(skip_setup);
61fbbac1 1916
3c3c6cb9 1917 if (arg_system) {
5238e957 1918 /* Make sure we leave a core dump without panicking the kernel. */
3c3c6cb9 1919 install_crash_handler();
5afbaa36 1920
3c3c6cb9 1921 if (!skip_setup) {
143fadf3 1922 r = mount_cgroup_controllers();
3c3c6cb9
LP
1923 if (r < 0) {
1924 *ret_error_message = "Failed to mount cgroup hierarchies";
1925 return r;
1926 }
1927
1928 status_welcome();
1929 hostname_setup();
1930 machine_id_setup(NULL, arg_machine_id, NULL);
df883de9 1931 (void) loopback_setup();
3c3c6cb9 1932 bump_unix_max_dgram_qlen();
a8b627aa 1933 bump_file_max_and_nr_open();
3c3c6cb9
LP
1934 test_usr();
1935 write_container_id();
1936 }
8a2c1fbf 1937
3c3c6cb9
LP
1938 if (arg_watchdog_device) {
1939 r = watchdog_set_device(arg_watchdog_device);
1940 if (r < 0)
1941 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
1942 }
1943
1f65fd49 1944 if (timestamp_is_set(arg_runtime_watchdog))
3c3c6cb9
LP
1945 watchdog_set_timeout(&arg_runtime_watchdog);
1946 }
5afbaa36
LP
1947
1948 if (arg_timer_slack_nsec != NSEC_INFINITY)
1949 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
3a671cd1 1950 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
5afbaa36
LP
1951
1952 if (arg_system && !cap_test_all(arg_capability_bounding_set)) {
1953 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
1954 if (r < 0) {
1955 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
1956 return log_emergency_errno(r, "Failed to drop capability bounding set of usermode helpers: %m");
1957 }
1958
1959 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
1960 if (r < 0) {
1961 *ret_error_message = "Failed to drop capability bounding set";
1962 return log_emergency_errno(r, "Failed to drop capability bounding set: %m");
1963 }
1964 }
1965
39362f6f
JB
1966 if (arg_system && arg_no_new_privs) {
1967 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
1968 *ret_error_message = "Failed to disable new privileges";
1969 return log_emergency_errno(errno, "Failed to disable new privileges: %m");
1970 }
1971 }
1972
5afbaa36
LP
1973 if (arg_syscall_archs) {
1974 r = enforce_syscall_archs(arg_syscall_archs);
1975 if (r < 0) {
1976 *ret_error_message = "Failed to set syscall architectures";
1977 return r;
1978 }
1979 }
1980
1981 if (!arg_system)
1982 /* Become reaper of our children */
1983 if (prctl(PR_SET_CHILD_SUBREAPER, 1) < 0)
1984 log_warning_errno(errno, "Failed to make us a subreaper: %m");
1985
a17c1712
LP
1986 /* Bump up RLIMIT_NOFILE for systemd itself */
1987 (void) bump_rlimit_nofile(saved_rlimit_nofile);
1988 (void) bump_rlimit_memlock(saved_rlimit_memlock);
5afbaa36
LP
1989
1990 return 0;
1991}
1992
6acca5fc
LP
1993static int do_queue_default_job(
1994 Manager *m,
1995 const char **ret_error_message) {
1996
1997 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f1d075dc
ZJS
1998 const char *unit;
1999 Job *job;
2000 Unit *target;
6acca5fc
LP
2001 int r;
2002
8755dbad 2003 if (arg_default_unit)
f1d075dc 2004 unit = arg_default_unit;
8755dbad 2005 else if (in_initrd())
f1d075dc 2006 unit = SPECIAL_INITRD_TARGET;
8755dbad 2007 else
f1d075dc 2008 unit = SPECIAL_DEFAULT_TARGET;
8755dbad 2009
f1d075dc 2010 log_debug("Activating default unit: %s", unit);
8755dbad 2011
f1d075dc 2012 r = manager_load_startable_unit_or_warn(m, unit, NULL, &target);
8755dbad
ZJS
2013 if (r < 0 && in_initrd() && !arg_default_unit) {
2014 /* Fall back to default.target, which we used to always use by default. Only do this if no
2015 * explicit configuration was given. */
2016
2017 log_info("Falling back to " SPECIAL_DEFAULT_TARGET ".");
6acca5fc 2018
8755dbad
ZJS
2019 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2020 }
4109ede7 2021 if (r < 0) {
8755dbad 2022 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
6acca5fc 2023
4109ede7 2024 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
6acca5fc 2025 if (r < 0) {
8755dbad
ZJS
2026 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2027 : "Failed to load " SPECIAL_RESCUE_TARGET;
4109ede7 2028 return r;
6acca5fc
LP
2029 }
2030 }
2031
2032 assert(target->load_state == UNIT_LOADED);
2033
f1d075dc 2034 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &job);
6acca5fc
LP
2035 if (r == -EPERM) {
2036 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2037
2038 sd_bus_error_free(&error);
2039
f1d075dc 2040 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &job);
6acca5fc
LP
2041 if (r < 0) {
2042 *ret_error_message = "Failed to start default target";
2043 return log_emergency_errno(r, "Failed to start default target: %s", bus_error_message(&error, r));
2044 }
2045
2046 } else if (r < 0) {
2047 *ret_error_message = "Failed to isolate default target";
2048 return log_emergency_errno(r, "Failed to isolate default target: %s", bus_error_message(&error, r));
c86c31d9
ZJS
2049 } else
2050 log_info("Queued %s job for default target %s.",
2051 job_type_to_string(job->type),
2052 unit_status_string(job->unit));
6acca5fc 2053
f1d075dc 2054 m->default_unit_job_id = job->id;
6acca5fc
LP
2055
2056 return 0;
2057}
2058
a9fd4cd1
FB
2059static void save_rlimits(struct rlimit *saved_rlimit_nofile,
2060 struct rlimit *saved_rlimit_memlock) {
2061
2062 assert(saved_rlimit_nofile);
2063 assert(saved_rlimit_memlock);
2064
2065 if (getrlimit(RLIMIT_NOFILE, saved_rlimit_nofile) < 0)
2066 log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2067
2068 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock) < 0)
2069 log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2070}
2071
2072static void fallback_rlimit_nofile(const struct rlimit *saved_rlimit_nofile) {
2073 struct rlimit *rl;
2074
2075 if (arg_default_rlimit[RLIMIT_NOFILE])
2076 return;
2077
2078 /* Make sure forked processes get limits based on the original kernel setting */
2079
2080 rl = newdup(struct rlimit, saved_rlimit_nofile, 1);
2081 if (!rl) {
2082 log_oom();
2083 return;
2084 }
2085
2086 /* Bump the hard limit for system services to a substantially higher value. The default
2087 * hard limit current kernels set is pretty low (4K), mostly for historical
2088 * reasons. According to kernel developers, the fd handling in recent kernels has been
2089 * optimized substantially enough, so that we can bump the limit now, without paying too
2090 * high a price in memory or performance. Note however that we only bump the hard limit,
2091 * not the soft limit. That's because select() works the way it works, and chokes on fds
2092 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2093 * unexpecting programs that they get fds higher than what they can process using
2094 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2095 * this pitfall: programs that are written by folks aware of the select() problem in mind
2096 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2097 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2098 * we pass. */
2099 if (arg_system) {
2100 int nr;
2101
2102 /* Get the underlying absolute limit the kernel enforces */
2103 nr = read_nr_open();
2104
2105 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
2106 }
2107
2108 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2109 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2110 * instance), then lower what we pass on to not confuse our children */
2111 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
2112
2113 arg_default_rlimit[RLIMIT_NOFILE] = rl;
2114}
2115
2116static void fallback_rlimit_memlock(const struct rlimit *saved_rlimit_memlock) {
2117 struct rlimit *rl;
2118
2119 /* Pass the original value down to invoked processes */
2120
2121 if (arg_default_rlimit[RLIMIT_MEMLOCK])
2122 return;
2123
2124 rl = newdup(struct rlimit, saved_rlimit_memlock, 1);
2125 if (!rl) {
2126 log_oom();
2127 return;
2128 }
2129
2130 arg_default_rlimit[RLIMIT_MEMLOCK] = rl;
2131}
2132
fb39af4c
ZJS
2133static void reset_arguments(void) {
2134 /* Frees/resets arg_* variables, with a few exceptions commented below. */
970777b5
LP
2135
2136 arg_default_unit = mfree(arg_default_unit);
fb39af4c
ZJS
2137
2138 /* arg_system — ignore */
2139
2140 arg_dump_core = true;
2141 arg_crash_chvt = -1;
2142 arg_crash_shell = false;
2143 arg_crash_reboot = false;
970777b5 2144 arg_confirm_spawn = mfree(arg_confirm_spawn);
fb39af4c 2145 arg_show_status = _SHOW_STATUS_INVALID;
36cf4507 2146 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
fb39af4c
ZJS
2147 arg_switched_root = false;
2148 arg_pager_flags = 0;
2149 arg_service_watchdogs = true;
2150 arg_default_std_output = EXEC_OUTPUT_JOURNAL;
2151 arg_default_std_error = EXEC_OUTPUT_INHERIT;
2152 arg_default_restart_usec = DEFAULT_RESTART_USEC;
2153 arg_default_timeout_start_usec = DEFAULT_TIMEOUT_USEC;
2154 arg_default_timeout_stop_usec = DEFAULT_TIMEOUT_USEC;
2155 arg_default_timeout_abort_usec = DEFAULT_TIMEOUT_USEC;
2156 arg_default_timeout_abort_set = false;
2157 arg_default_start_limit_interval = DEFAULT_START_LIMIT_INTERVAL;
2158 arg_default_start_limit_burst = DEFAULT_START_LIMIT_BURST;
2159 arg_runtime_watchdog = 0;
65224c1d 2160 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
acafd7d8 2161 arg_kexec_watchdog = 0;
fb39af4c
ZJS
2162 arg_early_core_pattern = NULL;
2163 arg_watchdog_device = NULL;
2164
970777b5 2165 arg_default_environment = strv_free(arg_default_environment);
fb39af4c
ZJS
2166 rlimit_free_all(arg_default_rlimit);
2167
2168 arg_capability_bounding_set = CAP_ALL;
2169 arg_no_new_privs = false;
2170 arg_timer_slack_nsec = NSEC_INFINITY;
2171 arg_default_timer_accuracy_usec = 1 * USEC_PER_MINUTE;
2172
970777b5 2173 arg_syscall_archs = set_free(arg_syscall_archs);
61fbbac1 2174
fb39af4c
ZJS
2175 /* arg_serialization — ignore */
2176
2177 arg_default_cpu_accounting = -1;
2178 arg_default_io_accounting = false;
2179 arg_default_ip_accounting = false;
2180 arg_default_blockio_accounting = false;
2181 arg_default_memory_accounting = MEMORY_ACCOUNTING_DEFAULT;
2182 arg_default_tasks_accounting = true;
3a0f06c4 2183 arg_default_tasks_max = DEFAULT_TASKS_MAX;
fb39af4c
ZJS
2184 arg_machine_id = (sd_id128_t) {};
2185 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
2186 arg_default_oom_policy = OOM_STOP;
2187
61fbbac1 2188 cpu_set_reset(&arg_cpu_affinity);
b070c7c0 2189 numa_policy_reset(&arg_numa_policy);
970777b5
LP
2190}
2191
a9fd4cd1
FB
2192static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2193 const struct rlimit *saved_rlimit_memlock) {
97d1fb94
LP
2194 int r;
2195
a9fd4cd1
FB
2196 assert(saved_rlimit_nofile);
2197 assert(saved_rlimit_memlock);
2198
fb39af4c
ZJS
2199 /* Assign configuration defaults */
2200 reset_arguments();
2201
97d1fb94 2202 r = parse_config_file();
470a5e6d
ZJS
2203 if (r < 0)
2204 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
97d1fb94
LP
2205
2206 if (arg_system) {
2207 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2208 if (r < 0)
2209 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2210 }
2211
a9fd4cd1
FB
2212 /* Initialize some default rlimits for services if they haven't been configured */
2213 fallback_rlimit_nofile(saved_rlimit_nofile);
2214 fallback_rlimit_memlock(saved_rlimit_memlock);
2215
97d1fb94
LP
2216 /* Note that this also parses bits from the kernel command line, including "debug". */
2217 log_parse_environment();
2218
470a5e6d
ZJS
2219 return 0;
2220}
2221
a9fd4cd1
FB
2222static int load_configuration(
2223 int argc,
2224 char **argv,
2225 const struct rlimit *saved_rlimit_nofile,
2226 const struct rlimit *saved_rlimit_memlock,
2227 const char **ret_error_message) {
470a5e6d
ZJS
2228 int r;
2229
a9fd4cd1
FB
2230 assert(saved_rlimit_nofile);
2231 assert(saved_rlimit_memlock);
470a5e6d
ZJS
2232 assert(ret_error_message);
2233
a9fd4cd1 2234 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
470a5e6d 2235
97d1fb94
LP
2236 r = parse_argv(argc, argv);
2237 if (r < 0) {
2238 *ret_error_message = "Failed to parse commandline arguments";
2239 return r;
2240 }
2241
db33214b 2242 /* Initialize the show status setting if it hasn't been set explicitly yet */
7a293242 2243 if (arg_show_status == _SHOW_STATUS_INVALID)
db33214b
LP
2244 arg_show_status = SHOW_STATUS_YES;
2245
97d1fb94
LP
2246 return 0;
2247}
2248
b0d7c989
LP
2249static int safety_checks(void) {
2250
febf46a4 2251 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2252 arg_action != ACTION_RUN)
2253 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2254 "Unsupported execution mode while PID 1.");
febf46a4
LP
2255
2256 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2257 !arg_system)
2258 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2259 "Can't run --user mode as PID 1.");
febf46a4
LP
2260
2261 if (arg_action == ACTION_RUN &&
2262 arg_system &&
baaa35ad
ZJS
2263 getpid_cached() != 1)
2264 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2265 "Can't run system mode unless PID 1.");
febf46a4 2266
b0d7c989 2267 if (arg_action == ACTION_TEST &&
baaa35ad
ZJS
2268 geteuid() == 0)
2269 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2270 "Don't run test mode as root.");
b0d7c989
LP
2271
2272 if (!arg_system &&
2273 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2274 sd_booted() <= 0)
2275 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2276 "Trying to run as user instance, but the system has not been booted with systemd.");
b0d7c989
LP
2277
2278 if (!arg_system &&
2279 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2280 !getenv("XDG_RUNTIME_DIR"))
2281 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2282 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
b0d7c989
LP
2283
2284 if (arg_system &&
2285 arg_action == ACTION_RUN &&
baaa35ad
ZJS
2286 running_in_chroot() > 0)
2287 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2288 "Cannot be run in a chroot() environment.");
b0d7c989
LP
2289
2290 return 0;
2291}
2292
74da609f
LP
2293static int initialize_security(
2294 bool *loaded_policy,
2295 dual_timestamp *security_start_timestamp,
2296 dual_timestamp *security_finish_timestamp,
2297 const char **ret_error_message) {
2298
2299 int r;
2300
2301 assert(loaded_policy);
2302 assert(security_start_timestamp);
2303 assert(security_finish_timestamp);
2304 assert(ret_error_message);
2305
2306 dual_timestamp_get(security_start_timestamp);
2307
97149f40 2308 r = mac_selinux_setup(loaded_policy);
74da609f
LP
2309 if (r < 0) {
2310 *ret_error_message = "Failed to load SELinux policy";
2311 return r;
2312 }
2313
2314 r = mac_smack_setup(loaded_policy);
2315 if (r < 0) {
2316 *ret_error_message = "Failed to load SMACK policy";
2317 return r;
2318 }
2319
2320 r = ima_setup();
2321 if (r < 0) {
2322 *ret_error_message = "Failed to load IMA policy";
2323 return r;
2324 }
2325
2326 dual_timestamp_get(security_finish_timestamp);
2327 return 0;
2328}
2329
263162da
LP
2330static void test_summary(Manager *m) {
2331 assert(m);
2332
2333 printf("-> By units:\n");
2334 manager_dump_units(m, stdout, "\t");
2335
2336 printf("-> By jobs:\n");
2337 manager_dump_jobs(m, stdout, "\t");
2338}
2339
efeb853f
LP
2340static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2341 int r;
2342
2343 assert(ret_fds);
2344 assert(ret_error_message);
2345
2346 r = fdset_new_fill(ret_fds);
2347 if (r < 0) {
2348 *ret_error_message = "Failed to allocate fd set";
2349 return log_emergency_errno(r, "Failed to allocate fd set: %m");
2350 }
2351
2352 fdset_cloexec(*ret_fds, true);
2353
2354 if (arg_serialization)
2355 assert_se(fdset_remove(*ret_fds, fileno(arg_serialization)) >= 0);
2356
2357 return 0;
2358}
2359
2e51b31c
LP
2360static void setup_console_terminal(bool skip_setup) {
2361
2362 if (!arg_system)
2363 return;
2364
2365 /* Become a session leader if we aren't one yet. */
2366 (void) setsid();
2367
2368 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a controlling
2369 * tty. */
2370 (void) release_terminal();
2371
2372 /* Reset the console, but only if this is really init and we are freshly booted */
2373 if (getpid_cached() == 1 && !skip_setup)
2374 (void) console_setup();
2375}
2376
aa40ff07
LP
2377static bool early_skip_setup_check(int argc, char *argv[]) {
2378 bool found_deserialize = false;
2379 int i;
2380
2381 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much later, so
2382 * let's just have a quick peek here. Note that if we have switched root, do all the special setup things
2383 * anyway, even if in that case we also do deserialization. */
2384
2385 for (i = 1; i < argc; i++) {
aa40ff07
LP
2386 if (streq(argv[i], "--switched-root"))
2387 return false; /* If we switched root, don't skip the setup. */
2388 else if (streq(argv[i], "--deserialize"))
2389 found_deserialize = true;
2390 }
2391
2392 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2393}
2394
0e06a031
LP
2395static int save_env(void) {
2396 char **l;
2397
2398 l = strv_copy(environ);
2399 if (!l)
2400 return -ENOMEM;
2401
2402 strv_free_and_replace(saved_env, l);
2403 return 0;
2404}
2405
60918275 2406int main(int argc, char *argv[]) {
625e8690
LP
2407
2408 dual_timestamp initrd_timestamp = DUAL_TIMESTAMP_NULL, userspace_timestamp = DUAL_TIMESTAMP_NULL, kernel_timestamp = DUAL_TIMESTAMP_NULL,
2409 security_start_timestamp = DUAL_TIMESTAMP_NULL, security_finish_timestamp = DUAL_TIMESTAMP_NULL;
ddfa8b0b
LP
2410 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2411 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2412 * in. Note we use different values
2413 * for the two that indicate whether
2414 * these fields are initialized! */
625e8690
LP
2415 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false, reexecute = false;
2416 char *switch_root_dir = NULL, *switch_root_init = NULL;
9d76d730 2417 usec_t before_startup, after_startup;
625e8690 2418 static char systemd[] = "systemd";
9d76d730 2419 char timespan[FORMAT_TIMESPAN_MAX];
625e8690
LP
2420 const char *shutdown_verb = NULL, *error_message = NULL;
2421 int r, retval = EXIT_FAILURE;
2422 Manager *m = NULL;
a16e1123 2423 FDSet *fds = NULL;
27b14a22 2424
d72a8f10 2425 /* SysV compatibility: redirect init → telinit */
6808a0bc 2426 redirect_telinit(argc, argv);
2cb1a60d 2427
d72a8f10 2428 /* Take timestamps early on */
c3a170f3
HH
2429 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2430 dual_timestamp_get(&userspace_timestamp);
2431
d72a8f10
LP
2432 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2433 * reexecuting */
aa40ff07 2434 skip_setup = early_skip_setup_check(argc, argv);
d03bc1b8 2435
d72a8f10
LP
2436 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent reexecution we
2437 * are then called 'systemd'. That is confusing, hence let's call us systemd right-away. */
f3b6a3ed 2438 program_invocation_short_name = systemd;
eee8b7ab 2439 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 2440
d72a8f10 2441 /* Save the original command line */
36fea155 2442 save_argc_argv(argc, argv);
f3b6a3ed 2443
0e06a031
LP
2444 /* Save the original environment as we might need to restore it if we're requested to execute another
2445 * system manager later. */
2446 r = save_env();
2447 if (r < 0) {
2448 error_message = "Failed to copy environment block";
2449 goto finish;
2450 }
a5cede8c 2451
6fdb8de4 2452 /* Make sure that if the user says "syslog" we actually log to the journal. */
c1dc6153 2453 log_set_upgrade_syslog_to_journal(true);
bbe63281 2454
df0ff127 2455 if (getpid_cached() == 1) {
b5752d23
LP
2456 /* When we run as PID 1 force system mode */
2457 arg_system = true;
2458
48a601fe 2459 /* Disable the umask logic */
90dc8c2e
MG
2460 umask(0);
2461
92890452
LP
2462 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might not be
2463 * activated yet (even though the log socket for it exists). */
d075092f
LP
2464 log_set_prohibit_ipc(true);
2465
48a601fe
LP
2466 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This is
2467 * important so that we never end up logging to any foreign stderr, for example if we have to log in a
2468 * child process right before execve()'ing the actual binary, at a point in time where socket
2469 * activation stderr/stdout area already set up. */
2470 log_set_always_reopen_console(true);
48a601fe 2471
92890452 2472 if (detect_container() <= 0) {
4f8d551f 2473
92890452 2474 /* Running outside of a container as PID 1 */
92890452
LP
2475 log_set_target(LOG_TARGET_KMSG);
2476 log_open();
a866073d 2477
92890452
LP
2478 if (in_initrd())
2479 initrd_timestamp = userspace_timestamp;
c3ba6250 2480
92890452
LP
2481 if (!skip_setup) {
2482 r = mount_setup_early();
2483 if (r < 0) {
2484 error_message = "Failed to mount early API filesystems";
2485 goto finish;
2486 }
2487
0a2eef1e
LP
2488 /* Let's open the log backend a second time, in case the first time didn't
2489 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2490 * available, and it previously wasn't. */
2491 log_open();
2492
6123dfaa
ZJS
2493 disable_printk_ratelimit();
2494
92890452
LP
2495 r = initialize_security(
2496 &loaded_policy,
2497 &security_start_timestamp,
2498 &security_finish_timestamp,
2499 &error_message);
2500 if (r < 0)
2501 goto finish;
d723cd65 2502 }
eee8b7ab 2503
92890452
LP
2504 if (mac_selinux_init() < 0) {
2505 error_message = "Failed to initialize SELinux policy";
96694e99 2506 goto finish;
92890452 2507 }
0b3325e7 2508
92890452
LP
2509 if (!skip_setup)
2510 initialize_clock();
2511
2512 /* Set the default for later on, but don't actually open the logs like this for now. Note that
2513 * if we are transitioning from the initrd there might still be journal fd open, and we
2514 * shouldn't attempt opening that before we parsed /proc/cmdline which might redirect output
2515 * elsewhere. */
2516 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2517
2518 } else {
2519 /* Running inside a container, as PID 1 */
92890452
LP
2520 log_set_target(LOG_TARGET_CONSOLE);
2521 log_open();
2522
2523 /* For later on, see above... */
2524 log_set_target(LOG_TARGET_JOURNAL);
2525
2526 /* clear the kernel timestamp,
2527 * because we are in a container */
2528 kernel_timestamp = DUAL_TIMESTAMP_NULL;
cb6531be 2529 }
7948c4df 2530
92890452 2531 initialize_coredump(skip_setup);
a866073d 2532
92890452
LP
2533 r = fixup_environment();
2534 if (r < 0) {
2535 log_emergency_errno(r, "Failed to fix up PID 1 environment: %m");
2536 error_message = "Failed to fix up PID1 environment";
2537 goto finish;
2538 }
a866073d 2539
c3a170f3 2540 } else {
a866073d 2541 /* Running as user instance */
463d0d15 2542 arg_system = false;
eeecf6e6 2543 log_set_target(LOG_TARGET_AUTO);
871e5809 2544 log_open();
c3a170f3
HH
2545
2546 /* clear the kernel timestamp,
2547 * because we are not PID 1 */
6513d561 2548 kernel_timestamp = DUAL_TIMESTAMP_NULL;
bbe63281 2549 }
a5dab5ce 2550
6edefe0b 2551 if (arg_system) {
92890452
LP
2552 /* Try to figure out if we can use colors with the console. No need to do that for user instances since
2553 * they never log into the console. */
3a18b604 2554 log_show_color(colors_enabled());
92890452 2555
c76cf844
AK
2556 r = make_null_stdio();
2557 if (r < 0)
92890452 2558 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
3a18b604
FB
2559 }
2560
f170852a
LP
2561 /* Mount /proc, /sys and friends, so that /proc/cmdline and
2562 * /proc/$PID/fd is available. */
df0ff127 2563 if (getpid_cached() == 1) {
f84f9974 2564
a132bef0 2565 /* Load the kernel modules early. */
2e75e2a8
DM
2566 if (!skip_setup)
2567 kmod_setup();
2e75e2a8 2568
0c85a4f3 2569 r = mount_setup(loaded_policy);
cb6531be
ZJS
2570 if (r < 0) {
2571 error_message = "Failed to mount API filesystems";
8efe3c01 2572 goto finish;
cb6531be 2573 }
c18ecf03
LP
2574
2575 /* The efivarfs is now mounted, let's read the random seed off it */
2576 (void) efi_take_random_seed();
0c85a4f3 2577 }
4ade7963 2578
a9fd4cd1
FB
2579 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2580 * transitioning from the initrd to the main systemd or suchlike. */
2581 save_rlimits(&saved_rlimit_nofile, &saved_rlimit_memlock);
2582
4ade7963 2583 /* Reset all signal handlers. */
ce30c8dc
LP
2584 (void) reset_all_signal_handlers();
2585 (void) ignore_signals(SIGNALS_IGNORE, -1);
078e4539 2586
a9fd4cd1 2587 r = load_configuration(argc, argv, &saved_rlimit_nofile, &saved_rlimit_memlock, &error_message);
97d1fb94 2588 if (r < 0)
f170852a 2589 goto finish;
10c961b9 2590
b0d7c989
LP
2591 r = safety_checks();
2592 if (r < 0)
fe783b03 2593 goto finish;
fe783b03 2594
bbc1acab 2595 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES))
0221d68a 2596 (void) pager_open(arg_pager_flags);
b0d7c989
LP
2597
2598 if (arg_action != ACTION_RUN)
74e7579c 2599 skip_setup = true;
b87c2aa6 2600
fa0f4d8a 2601 if (arg_action == ACTION_HELP) {
37ec0fdd 2602 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
f170852a 2603 goto finish;
9ba0bc4e
ZJS
2604 } else if (arg_action == ACTION_VERSION) {
2605 retval = version();
2606 goto finish;
fa0f4d8a 2607 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 2608 unit_dump_config_items(stdout);
22f4096c 2609 retval = EXIT_SUCCESS;
e537352b 2610 goto finish;
bbc1acab
YW
2611 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
2612 dump_bus_properties(stdout);
2613 retval = EXIT_SUCCESS;
2614 goto finish;
f170852a
LP
2615 }
2616
4c701096 2617 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
f170852a 2618
5a2e0c62
LP
2619 /* Move out of the way, so that we won't block unmounts */
2620 assert_se(chdir("/") == 0);
2621
dea374e8 2622 if (arg_action == ACTION_RUN) {
a70c72a0 2623
c6885f5f
FB
2624 /* A core pattern might have been specified via the cmdline. */
2625 initialize_core_pattern(skip_setup);
2626
efeb853f 2627 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
a70c72a0
LP
2628 log_close();
2629
2630 /* Remember open file descriptors for later deserialization */
efeb853f
LP
2631 r = collect_fds(&fds, &error_message);
2632 if (r < 0)
dea374e8 2633 goto finish;
a16e1123 2634
2e51b31c
LP
2635 /* Give up any control of the console, but make sure its initialized. */
2636 setup_console_terminal(skip_setup);
56d96fc0 2637
a70c72a0
LP
2638 /* Open the logging devices, if possible and necessary */
2639 log_open();
56d96fc0 2640 }
4ade7963 2641
31aef7ff 2642 log_execution_mode(&first_boot);
a5dab5ce 2643
2d776038
LP
2644 r = initialize_runtime(skip_setup,
2645 &saved_rlimit_nofile,
2646 &saved_rlimit_memlock,
2647 &error_message);
2648 if (r < 0)
2649 goto finish;
4096d6f5 2650
e0a3da1f
ZJS
2651 r = manager_new(arg_system ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
2652 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
2653 &m);
e96d6be7 2654 if (r < 0) {
da927ba9 2655 log_emergency_errno(r, "Failed to allocate manager object: %m");
cb6531be 2656 error_message = "Failed to allocate manager object";
60918275
LP
2657 goto finish;
2658 }
2659
9f9f0342
LP
2660 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
2661 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
2662 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
d4ee7bd8
YW
2663 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
2664 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
9e58ff9c 2665
85cb4151 2666 set_manager_defaults(m);
7b46fc6a 2667 set_manager_settings(m);
fd130612 2668 manager_set_first_boot(m, first_boot);
27d340c7 2669
bf4df7c3 2670 /* Remember whether we should queue the default job */
d3b1c508 2671 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 2672
9d76d730
LP
2673 before_startup = now(CLOCK_MONOTONIC);
2674
d3b1c508 2675 r = manager_startup(m, arg_serialization, fds);
58f88d92 2676 if (r < 0) {
cefb3eda 2677 error_message = "Failed to start up manager";
58f88d92
ZJS
2678 goto finish;
2679 }
a16e1123 2680
6acca5fc 2681 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2feceb5e 2682 fds = fdset_free(fds);
74ca738f 2683 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
2684
2685 if (queue_default_job) {
6acca5fc 2686 r = do_queue_default_job(m, &error_message);
718db961 2687 if (r < 0)
37d88da7 2688 goto finish;
6acca5fc 2689 }
ab17a050 2690
6acca5fc 2691 after_startup = now(CLOCK_MONOTONIC);
60918275 2692
6acca5fc
LP
2693 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
2694 "Loaded units and determined initial transaction in %s.",
2695 format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 2696
6acca5fc 2697 if (arg_action == ACTION_TEST) {
263162da 2698 test_summary(m);
6acca5fc
LP
2699 retval = EXIT_SUCCESS;
2700 goto finish;
e965d56d 2701 }
d46de8a1 2702
3046b6db 2703 (void) invoke_main_loop(m,
a9fd4cd1
FB
2704 &saved_rlimit_nofile,
2705 &saved_rlimit_memlock,
3046b6db
LP
2706 &reexecute,
2707 &retval,
2708 &shutdown_verb,
2709 &fds,
2710 &switch_root_dir,
2711 &switch_root_init,
2712 &error_message);
f170852a 2713
60918275 2714finish:
b87c2aa6
ZJS
2715 pager_close();
2716
92890452 2717 if (m) {
65224c1d 2718 arg_reboot_watchdog = m->reboot_watchdog;
acafd7d8 2719 arg_kexec_watchdog = m->kexec_watchdog;
92890452
LP
2720 m = manager_free(m);
2721 }
60918275 2722
fb39af4c 2723 reset_arguments();
cc56fafe 2724 mac_selinux_finish();
b2bb3dbe 2725
3c7878f9
LP
2726 if (reexecute)
2727 do_reexecute(argc, argv,
2728 &saved_rlimit_nofile,
2729 &saved_rlimit_memlock,
2730 fds,
2731 switch_root_dir,
2732 switch_root_init,
2733 &error_message); /* This only returns if reexecution failed */
a16e1123 2734
74ca738f 2735 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 2736 fds = fdset_free(fds);
a16e1123 2737
0e06a031
LP
2738 saved_env = strv_free(saved_env);
2739
349cc4a5 2740#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
2741 /* If we are PID 1 and running under valgrind, then let's exit
2742 * here explicitly. valgrind will only generate nice output on
2743 * exit(), not on exec(), hence let's do the former not the
2744 * latter here. */
8a2c1fbf
EJ
2745 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
2746 /* Cleanup watchdog_device strings for valgrind. We need them
2747 * in become_shutdown() so normally we cannot free them yet. */
2748 watchdog_free_device();
2749 arg_watchdog_device = mfree(arg_watchdog_device);
27fe58b7 2750 return retval;
8a2c1fbf 2751 }
54b434b1
LP
2752#endif
2753
7e11a95e
EV
2754#if HAS_FEATURE_ADDRESS_SANITIZER
2755 __lsan_do_leak_check();
2756#endif
2757
b9080b03 2758 if (shutdown_verb) {
7eb35049 2759 r = become_shutdown(shutdown_verb, retval);
4a36297c 2760 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
9b9881d7 2761 error_message = "Failed to execute shutdown binary";
b9080b03
FF
2762 }
2763
8a2c1fbf
EJ
2764 watchdog_free_device();
2765 arg_watchdog_device = mfree(arg_watchdog_device);
2766
df0ff127 2767 if (getpid_cached() == 1) {
cb6531be
ZJS
2768 if (error_message)
2769 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 2770 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
bb259772
LP
2771 "%s.", error_message);
2772 freeze_or_exit_or_reboot();
cb6531be 2773 }
c3b3c274 2774
60918275
LP
2775 return retval;
2776}