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