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