]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/main.c
hwdb: Add quirk for teclast x3 plus (G4K3) rotation (#29202)
[thirdparty/systemd.git] / src / core / main.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
60918275 3#include <errno.h>
3dfc9763 4#include <fcntl.h>
f170852a 5#include <getopt.h>
d4a402e4 6#include <linux/oom.h>
664f88a7 7#include <sys/mount.h>
3dfc9763 8#include <sys/prctl.h>
40efaaed 9#include <sys/utsname.h>
3dfc9763 10#include <unistd.h>
349cc4a5 11#if HAVE_VALGRIND_VALGRIND_H
50b35193 12# include <valgrind/valgrind.h>
3dfc9763 13#endif
54b434b1 14
718db961 15#include "sd-bus.h"
cf0fbc49 16#include "sd-daemon.h"
b2e7486c 17#include "sd-messages.h"
3dfc9763 18
b5efdb8a 19#include "alloc-util.h"
2ffadd3c 20#include "apparmor-setup.h"
d9d93745 21#include "architecture.h"
ee617a4e 22#include "argv-util.h"
b1994387
ILG
23#if HAVE_LIBBPF
24#include "bpf-lsm.h"
25#endif
3dfc9763
LP
26#include "build.h"
27#include "bus-error.h"
28#include "bus-util.h"
430f0182 29#include "capability-util.h"
a88c5b8a 30#include "cgroup-util.h"
aaa27e2e 31#include "chase.h"
24efb112 32#include "clock-util.h"
3dfc9763 33#include "conf-parser.h"
024469dd 34#include "confidential-virt.h"
3f37a825 35#include "copy.h"
618234a5 36#include "cpu-set-util.h"
898c9a6f 37#include "crash-handler.h"
3dfc9763 38#include "dbus-manager.h"
c18ecf03 39#include "dbus.h"
28db6fbf 40#include "constants.h"
32429805 41#include "dev-setup.h"
c18ecf03 42#include "efi-random.h"
209b2592 43#include "efivars.h"
eee8b7ab 44#include "emergency-action.h"
3dfc9763 45#include "env-util.h"
57b7a260 46#include "exit-status.h"
3ffd4af2 47#include "fd-util.h"
3dfc9763 48#include "fdset.h"
718db961 49#include "fileio.h"
f97b34a6 50#include "format-util.h"
f4f15635 51#include "fs-util.h"
6339d3e6 52#include "getopt-defs.h"
d247f232 53#include "hexdecoct.h"
3dfc9763
LP
54#include "hostname-setup.h"
55#include "ima-setup.h"
4b9a4b01 56#include "import-creds.h"
baa6a42d 57#include "initrd-util.h"
3dfc9763
LP
58#include "killall.h"
59#include "kmod-setup.h"
eefc66aa 60#include "limits-util.h"
d7b8eec7 61#include "load-fragment.h"
3dfc9763 62#include "log.h"
b6e66135 63#include "loopback-setup.h"
b6e66135 64#include "machine-id-setup.h"
898c9a6f 65#include "main.h"
3dfc9763 66#include "manager.h"
2a341bb9 67#include "manager-dump.h"
a01ba4b2 68#include "manager-serialize.h"
35cd0ba5 69#include "mkdir-label.h"
3dfc9763 70#include "mount-setup.h"
d58ad743 71#include "os-util.h"
3dfc9763 72#include "pager.h"
614b022c 73#include "parse-argument.h"
6bedfcbb 74#include "parse-util.h"
7d5ceb64 75#include "path-util.h"
294bf0c3 76#include "pretty-print.h"
4e731273 77#include "proc-cmdline.h"
3dfc9763 78#include "process-util.h"
6bb00842 79#include "psi-util.h"
d247f232 80#include "random-util.h"
78f22b97 81#include "rlimit-util.h"
83f12b27 82#include "seccomp-util.h"
b6e66135 83#include "selinux-setup.h"
3dfc9763
LP
84#include "selinux-util.h"
85#include "signal-util.h"
ffbd2c4d 86#include "smack-setup.h"
3dfc9763 87#include "special.h"
8fcde012 88#include "stat-util.h"
15a5e950 89#include "stdio-util.h"
3dfc9763
LP
90#include "strv.h"
91#include "switch-root.h"
a8b627aa 92#include "sysctl-util.h"
3dfc9763 93#include "terminal-util.h"
b10abe4b 94#include "time-util.h"
8612da97 95#include "umask-util.h"
b1d4f8e1 96#include "user-util.h"
bdb577f5 97#include "version.h"
3dfc9763
LP
98#include "virt.h"
99#include "watchdog.h"
b6e66135 100
7e11a95e
EV
101#if HAS_FEATURE_ADDRESS_SANITIZER
102#include <sanitizer/lsan_interface.h>
103#endif
104
f170852a
LP
105static enum {
106 ACTION_RUN,
e965d56d 107 ACTION_HELP,
9ba0bc4e 108 ACTION_VERSION,
e537352b 109 ACTION_TEST,
bbc1acab
YW
110 ACTION_DUMP_CONFIGURATION_ITEMS,
111 ACTION_DUMP_BUS_PROPERTIES,
5c08257b 112 ACTION_BUS_INTROSPECT,
fa0f4d8a 113} arg_action = ACTION_RUN;
fb39af4c 114
5c08257b
ZJS
115static const char *arg_bus_introspect = NULL;
116
45250e66
LP
117/* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
118 * defaults are assigned in reset_arguments() below. */
fb39af4c 119static char *arg_default_unit;
4870133b 120static RuntimeScope arg_runtime_scope;
898c9a6f
LP
121bool arg_dump_core;
122int arg_crash_chvt;
123bool arg_crash_shell;
124bool arg_crash_reboot;
fb39af4c
ZJS
125static char *arg_confirm_spawn;
126static ShowStatus arg_show_status;
36cf4507 127static StatusUnitFormat arg_status_unit_format;
fb39af4c
ZJS
128static bool arg_switched_root;
129static PagerFlags arg_pager_flags;
130static bool arg_service_watchdogs;
c9e120e0 131static UnitDefaults arg_defaults;
fb39af4c 132static usec_t arg_runtime_watchdog;
65224c1d 133static usec_t arg_reboot_watchdog;
acafd7d8 134static usec_t arg_kexec_watchdog;
5717062e 135static usec_t arg_pretimeout_watchdog;
fb39af4c 136static char *arg_early_core_pattern;
aff3a9e1 137static char *arg_watchdog_pretimeout_governor;
fb39af4c
ZJS
138static char *arg_watchdog_device;
139static char **arg_default_environment;
d55ed7de 140static char **arg_manager_environment;
fb39af4c
ZJS
141static uint64_t arg_capability_bounding_set;
142static bool arg_no_new_privs;
143static nsec_t arg_timer_slack_nsec;
fb39af4c
ZJS
144static Set* arg_syscall_archs;
145static FILE* arg_serialization;
fb39af4c
ZJS
146static sd_id128_t arg_machine_id;
147static EmergencyAction arg_cad_burst_action;
fb39af4c 148static CPUSet arg_cpu_affinity;
b070c7c0 149static NUMAPolicy arg_numa_policy;
3753325b 150static usec_t arg_clock_usec;
d247f232
LP
151static void *arg_random_seed;
152static size_t arg_random_seed_size;
856bfaeb
LB
153static usec_t arg_reload_limit_interval_sec;
154static unsigned arg_reload_limit_burst;
61fbbac1 155
0e06a031
LP
156/* A copy of the original environment block */
157static char **saved_env = NULL;
158
a9fd4cd1
FB
159static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
160 const struct rlimit *saved_rlimit_memlock);
4fc935ca 161
f70e6fb4
ZJS
162static int manager_find_user_config_paths(char ***ret_files, char ***ret_dirs) {
163 _cleanup_free_ char *base = NULL;
164 _cleanup_strv_free_ char **files = NULL, **dirs = NULL;
165 int r;
166
167 r = xdg_user_config_dir(&base, "/systemd");
168 if (r < 0)
169 return r;
170
171 r = strv_extendf(&files, "%s/user.conf", base);
172 if (r < 0)
173 return r;
174
175 r = strv_extend(&files, PKGSYSCONFDIR "/user.conf");
176 if (r < 0)
177 return r;
178
179 r = strv_consume(&dirs, TAKE_PTR(base));
180 if (r < 0)
181 return r;
182
183 r = strv_extend_strv(&dirs, CONF_PATHS_STRV("systemd"), false);
184 if (r < 0)
185 return r;
186
187 *ret_files = TAKE_PTR(files);
188 *ret_dirs = TAKE_PTR(dirs);
189 return 0;
190}
191
56d96fc0 192static int console_setup(void) {
254d1313 193 _cleanup_close_ int tty_fd = -EBADF;
29f5a5ae 194 unsigned rows, cols;
56d96fc0 195 int r;
80876c20 196
512947d4 197 tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
23bbb0de
MS
198 if (tty_fd < 0)
199 return log_error_errno(tty_fd, "Failed to open /dev/console: %m");
80876c20 200
56d96fc0
LP
201 /* We don't want to force text mode. plymouth may be showing
202 * pictures already from initrd. */
512947d4 203 r = reset_terminal_fd(tty_fd, false);
23bbb0de
MS
204 if (r < 0)
205 return log_error_errno(r, "Failed to reset /dev/console: %m");
843d2643 206
29f5a5ae
DDM
207 r = proc_cmdline_tty_size("/dev/console", &rows, &cols);
208 if (r < 0)
209 log_warning_errno(r, "Failed to get terminal size, ignoring: %m");
210 else {
211 r = terminal_set_size_fd(tty_fd, NULL, rows, cols);
212 if (r < 0)
213 log_warning_errno(r, "Failed to set terminal size, ignoring: %m");
214 }
215
56d96fc0 216 return 0;
80876c20
LP
217}
218
96287a49 219static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
059cb385 220 int r;
f170852a 221
059cb385 222 assert(key);
5192bd19 223
1d84ad94 224 if (STR_IN_SET(key, "systemd.unit", "rd.systemd.unit")) {
bf4df7c3 225
1d84ad94
LP
226 if (proc_cmdline_value_missing(key, value))
227 return 0;
bf4df7c3 228
1d84ad94
LP
229 if (!unit_name_is_valid(value, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
230 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key, value);
cd57038a
ZJS
231 else if (in_initrd() == !!startswith(key, "rd."))
232 return free_and_strdup_warn(&arg_default_unit, value);
f170852a 233
1d84ad94 234 } else if (proc_cmdline_key_streq(key, "systemd.dump_core")) {
4fc935ca 235
1d84ad94 236 r = value ? parse_boolean(value) : true;
fb472900 237 if (r < 0)
5e1ee764 238 log_warning_errno(r, "Failed to parse dump core switch %s, ignoring: %m", value);
4fc935ca 239 else
fa0f4d8a 240 arg_dump_core = r;
4fc935ca 241
c6885f5f
FB
242 } else if (proc_cmdline_key_streq(key, "systemd.early_core_pattern")) {
243
244 if (proc_cmdline_value_missing(key, value))
245 return 0;
246
247 if (path_is_absolute(value))
614b022c 248 (void) parse_path_argument(value, false, &arg_early_core_pattern);
c6885f5f
FB
249 else
250 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value);
251
1d84ad94 252 } else if (proc_cmdline_key_streq(key, "systemd.crash_chvt")) {
b9e74c39 253
1d84ad94
LP
254 if (!value)
255 arg_crash_chvt = 0; /* turn on */
5e1ee764 256 else {
a07a7324 257 r = parse_crash_chvt(value, &arg_crash_chvt);
5e1ee764
YW
258 if (r < 0)
259 log_warning_errno(r, "Failed to parse crash chvt switch %s, ignoring: %m", value);
260 }
b9e74c39 261
1d84ad94 262 } else if (proc_cmdline_key_streq(key, "systemd.crash_shell")) {
4fc935ca 263
1d84ad94 264 r = value ? parse_boolean(value) : true;
fb472900 265 if (r < 0)
5e1ee764 266 log_warning_errno(r, "Failed to parse crash shell switch %s, ignoring: %m", value);
4fc935ca 267 else
fa0f4d8a 268 arg_crash_shell = r;
5e7ee61c 269
1d84ad94 270 } else if (proc_cmdline_key_streq(key, "systemd.crash_reboot")) {
5e7ee61c 271
1d84ad94 272 r = value ? parse_boolean(value) : true;
b9e74c39 273 if (r < 0)
5e1ee764 274 log_warning_errno(r, "Failed to parse crash reboot switch %s, ignoring: %m", value);
5e7ee61c 275 else
b9e74c39 276 arg_crash_reboot = r;
5e7ee61c 277
1d84ad94
LP
278 } else if (proc_cmdline_key_streq(key, "systemd.confirm_spawn")) {
279 char *s;
7d5ceb64 280
1d84ad94 281 r = parse_confirm_spawn(value, &s);
059cb385 282 if (r < 0)
5e1ee764
YW
283 log_warning_errno(r, "Failed to parse confirm_spawn switch %s, ignoring: %m", value);
284 else
285 free_and_replace(arg_confirm_spawn, s);
601f6a1e 286
2a12e32e
JK
287 } else if (proc_cmdline_key_streq(key, "systemd.service_watchdogs")) {
288
289 r = value ? parse_boolean(value) : true;
290 if (r < 0)
5e1ee764 291 log_warning_errno(r, "Failed to parse service watchdog switch %s, ignoring: %m", value);
2a12e32e
JK
292 else
293 arg_service_watchdogs = r;
294
1d84ad94 295 } else if (proc_cmdline_key_streq(key, "systemd.show_status")) {
9e58ff9c 296
1d84ad94
LP
297 if (value) {
298 r = parse_show_status(value, &arg_show_status);
299 if (r < 0)
5e1ee764 300 log_warning_errno(r, "Failed to parse show status switch %s, ignoring: %m", value);
1d84ad94
LP
301 } else
302 arg_show_status = SHOW_STATUS_YES;
059cb385 303
36cf4507
ZJS
304 } else if (proc_cmdline_key_streq(key, "systemd.status_unit_format")) {
305
306 if (proc_cmdline_value_missing(key, value))
307 return 0;
308
309 r = status_unit_format_from_string(value);
310 if (r < 0)
311 log_warning_errno(r, "Failed to parse %s=%s, ignoring: %m", key, value);
312 else
313 arg_status_unit_format = r;
314
1d84ad94
LP
315 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_output")) {
316
317 if (proc_cmdline_value_missing(key, value))
318 return 0;
0a494f1f 319
059cb385 320 r = exec_output_from_string(value);
fb472900 321 if (r < 0)
5e1ee764 322 log_warning_errno(r, "Failed to parse default standard output switch %s, ignoring: %m", value);
0a494f1f 323 else
c9e120e0 324 arg_defaults.std_output = r;
0a494f1f 325
1d84ad94
LP
326 } else if (proc_cmdline_key_streq(key, "systemd.default_standard_error")) {
327
328 if (proc_cmdline_value_missing(key, value))
329 return 0;
059cb385
LP
330
331 r = exec_output_from_string(value);
fb472900 332 if (r < 0)
5e1ee764 333 log_warning_errno(r, "Failed to parse default standard error switch %s, ignoring: %m", value);
0a494f1f 334 else
c9e120e0 335 arg_defaults.std_error = r;
9e7c5357 336
1d84ad94
LP
337 } else if (streq(key, "systemd.setenv")) {
338
339 if (proc_cmdline_value_missing(key, value))
340 return 0;
059cb385 341
b70935ac
ZJS
342 if (!env_assignment_is_valid(value))
343 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value);
344 else {
345 r = strv_env_replace_strdup(&arg_default_environment, value);
346 if (r < 0)
1d84ad94 347 return log_oom();
b70935ac 348 }
9e58ff9c 349
1d84ad94
LP
350 } else if (proc_cmdline_key_streq(key, "systemd.machine_id")) {
351
352 if (proc_cmdline_value_missing(key, value))
353 return 0;
354
aea3f594 355 r = id128_from_string_nonzero(value, &arg_machine_id);
1d84ad94 356 if (r < 0)
5e1ee764 357 log_warning_errno(r, "MachineID '%s' is not valid, ignoring: %m", value);
ee48dbd5 358
1d84ad94
LP
359 } else if (proc_cmdline_key_streq(key, "systemd.default_timeout_start_sec")) {
360
361 if (proc_cmdline_value_missing(key, value))
362 return 0;
363
c9e120e0 364 r = parse_sec(value, &arg_defaults.timeout_start_usec);
1d84ad94 365 if (r < 0)
5e1ee764 366 log_warning_errno(r, "Failed to parse default start timeout '%s', ignoring: %m", value);
1d84ad94 367
c9e120e0
LP
368 if (arg_defaults.timeout_start_usec <= 0)
369 arg_defaults.timeout_start_usec = USEC_INFINITY;
ee48dbd5 370
6b818cd7
DDM
371 } else if (proc_cmdline_key_streq(key, "systemd.default_device_timeout_sec")) {
372
373 if (proc_cmdline_value_missing(key, value))
374 return 0;
375
c9e120e0 376 r = parse_sec(value, &arg_defaults.device_timeout_usec);
6b818cd7
DDM
377 if (r < 0)
378 log_warning_errno(r, "Failed to parse default device timeout '%s', ignoring: %m", value);
379
c9e120e0
LP
380 if (arg_defaults.device_timeout_usec <= 0)
381 arg_defaults.device_timeout_usec = USEC_INFINITY;
6b818cd7 382
68d58f38
LP
383 } else if (proc_cmdline_key_streq(key, "systemd.cpu_affinity")) {
384
385 if (proc_cmdline_value_missing(key, value))
386 return 0;
387
388 r = parse_cpu_set(value, &arg_cpu_affinity);
389 if (r < 0)
162392b7 390 log_warning_errno(r, "Failed to parse CPU affinity mask '%s', ignoring: %m", value);
68d58f38 391
8a2c1fbf
EJ
392 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_device")) {
393
394 if (proc_cmdline_value_missing(key, value))
395 return 0;
396
614b022c 397 (void) parse_path_argument(value, false, &arg_watchdog_device);
8a2c1fbf 398
b3aa73e4
FB
399 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_sec")) {
400
401 if (proc_cmdline_value_missing(key, value))
402 return 0;
403
8a85c5b6
FB
404 if (streq(value, "default"))
405 arg_runtime_watchdog = USEC_INFINITY;
c91c95e6
LP
406 else if (streq(value, "off"))
407 arg_runtime_watchdog = 0;
8a85c5b6
FB
408 else {
409 r = parse_sec(value, &arg_runtime_watchdog);
410 if (r < 0) {
411 log_warning_errno(r, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value);
412 return 0;
413 }
414 }
415
416 arg_kexec_watchdog = arg_reboot_watchdog = arg_runtime_watchdog;
b3aa73e4 417
5717062e
CK
418 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_pre_sec")) {
419
420 if (proc_cmdline_value_missing(key, value))
421 return 0;
422
423 if (streq(value, "default"))
424 arg_pretimeout_watchdog = USEC_INFINITY;
425 else if (streq(value, "off"))
426 arg_pretimeout_watchdog = 0;
427 else {
428 r = parse_sec(value, &arg_pretimeout_watchdog);
429 if (r < 0) {
430 log_warning_errno(r, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value);
431 return 0;
432 }
433 }
434
aff3a9e1
LB
435 } else if (proc_cmdline_key_streq(key, "systemd.watchdog_pretimeout_governor")) {
436
437 if (proc_cmdline_value_missing(key, value) || isempty(value)) {
438 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
439 return 0;
440 }
441
442 if (!string_is_safe(value)) {
443 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value);
444 return 0;
445 }
446
447 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor, value);
448
3753325b
LP
449 } else if (proc_cmdline_key_streq(key, "systemd.clock_usec")) {
450
451 if (proc_cmdline_value_missing(key, value))
452 return 0;
453
454 r = safe_atou64(value, &arg_clock_usec);
455 if (r < 0)
456 log_warning_errno(r, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value);
457
d247f232
LP
458 } else if (proc_cmdline_key_streq(key, "systemd.random_seed")) {
459 void *p;
460 size_t sz;
461
462 if (proc_cmdline_value_missing(key, value))
463 return 0;
464
f5fbe71d 465 r = unbase64mem(value, SIZE_MAX, &p, &sz);
d247f232
LP
466 if (r < 0)
467 log_warning_errno(r, "Failed to parse systemd.random_seed= argument, ignoring: %s", value);
468
469 free(arg_random_seed);
470 arg_random_seed = sz > 0 ? p : mfree(p);
471 arg_random_seed_size = sz;
472
856bfaeb
LB
473 } else if (proc_cmdline_key_streq(key, "systemd.reload_limit_interval_sec")) {
474
475 if (proc_cmdline_value_missing(key, value))
476 return 0;
477
478 r = parse_sec(value, &arg_reload_limit_interval_sec);
479 if (r < 0) {
480 log_warning_errno(r, "Failed to parse systemd.reload_limit_interval_sec= argument '%s', ignoring: %m", value);
481 return 0;
482 }
483
484 } else if (proc_cmdline_key_streq(key, "systemd.reload_limit_burst")) {
485
486 if (proc_cmdline_value_missing(key, value))
487 return 0;
488
489 r = safe_atou(value, &arg_reload_limit_burst);
490 if (r < 0) {
491 log_warning_errno(r, "Failed to parse systemd.reload_limit_burst= argument '%s', ignoring: %m", value);
492 return 0;
493 }
494
059cb385 495 } else if (streq(key, "quiet") && !value) {
d7b15e0a 496
7a293242 497 if (arg_show_status == _SHOW_STATUS_INVALID)
0d066dd1 498 arg_show_status = SHOW_STATUS_ERROR;
059cb385
LP
499
500 } else if (streq(key, "debug") && !value) {
d7b15e0a 501
1de1c9c3
LP
502 /* Note that log_parse_environment() handles 'debug'
503 * too, and sets the log level to LOG_DEBUG. */
d7b15e0a 504
75f86906 505 if (detect_container() > 0)
b2103dcc 506 log_set_target(LOG_TARGET_CONSOLE);
059cb385 507
dcd61450 508 } else if (!value) {
e2c9a131 509 const char *target;
f170852a 510
ceae6295 511 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
e2c9a131
EV
512 target = runlevel_to_target(key);
513 if (target)
cd57038a 514 return free_and_strdup_warn(&arg_default_unit, target);
f170852a
LP
515 }
516
517 return 0;
518}
519
e8e581bf
ZJS
520#define DEFINE_SETTER(name, func, descr) \
521 static int name(const char *unit, \
522 const char *filename, \
523 unsigned line, \
524 const char *section, \
71a61510 525 unsigned section_line, \
e8e581bf
ZJS
526 const char *lvalue, \
527 int ltype, \
528 const char *rvalue, \
529 void *data, \
530 void *userdata) { \
531 \
532 int r; \
533 \
534 assert(filename); \
535 assert(lvalue); \
536 assert(rvalue); \
537 \
538 r = func(rvalue); \
539 if (r < 0) \
d1cefe0a
LP
540 log_syntax(unit, LOG_ERR, filename, line, r, \
541 "Invalid " descr "'%s': %m", \
542 rvalue); \
e8e581bf
ZJS
543 \
544 return 0; \
545 }
487393e9 546
a6ecbf83
FB
547DEFINE_SETTER(config_parse_level2, log_set_max_level_from_string, "log level");
548DEFINE_SETTER(config_parse_target, log_set_target_from_string, "target");
c5673ed0 549DEFINE_SETTER(config_parse_color, log_show_color_from_string, "color");
a6ecbf83 550DEFINE_SETTER(config_parse_location, log_show_location_from_string, "location");
c5673ed0 551DEFINE_SETTER(config_parse_time, log_show_time_from_string, "time");
487393e9 552
a61d6874
ZJS
553static int config_parse_default_timeout_abort(
554 const char *unit,
555 const char *filename,
556 unsigned line,
557 const char *section,
558 unsigned section_line,
559 const char *lvalue,
560 int ltype,
561 const char *rvalue,
562 void *data,
563 void *userdata) {
564 int r;
565
c9e120e0
LP
566 r = config_parse_timeout_abort(
567 unit,
568 filename,
569 line,
570 section,
571 section_line,
572 lvalue,
573 ltype,
574 rvalue,
575 &arg_defaults.timeout_abort_usec,
576 userdata);
a61d6874 577 if (r >= 0)
c9e120e0 578 arg_defaults.timeout_abort_set = r;
a61d6874
ZJS
579 return 0;
580}
487393e9 581
d4a402e4
LP
582static int config_parse_oom_score_adjust(
583 const char *unit,
584 const char *filename,
585 unsigned line,
586 const char *section,
587 unsigned section_line,
588 const char *lvalue,
589 int ltype,
590 const char *rvalue,
591 void *data,
592 void *userdata) {
593
594 int oa, r;
595
596 if (isempty(rvalue)) {
c9e120e0 597 arg_defaults.oom_score_adjust_set = false;
d4a402e4
LP
598 return 0;
599 }
600
601 r = parse_oom_score_adjust(rvalue, &oa);
602 if (r < 0) {
603 log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue);
604 return 0;
605 }
606
c9e120e0
LP
607 arg_defaults.oom_score_adjust = oa;
608 arg_defaults.oom_score_adjust_set = true;
d4a402e4
LP
609
610 return 0;
611}
612
a61d6874 613static int parse_config_file(void) {
f975e971 614 const ConfigTableItem items[] = {
3f87eaa5
YW
615 { "Manager", "LogLevel", config_parse_level2, 0, NULL },
616 { "Manager", "LogTarget", config_parse_target, 0, NULL },
617 { "Manager", "LogColor", config_parse_color, 0, NULL },
618 { "Manager", "LogLocation", config_parse_location, 0, NULL },
619 { "Manager", "LogTime", config_parse_time, 0, NULL },
620 { "Manager", "DumpCore", config_parse_bool, 0, &arg_dump_core },
621 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt, 0, &arg_crash_chvt },
622 { "Manager", "CrashChangeVT", config_parse_crash_chvt, 0, &arg_crash_chvt },
623 { "Manager", "CrashShell", config_parse_bool, 0, &arg_crash_shell },
624 { "Manager", "CrashReboot", config_parse_bool, 0, &arg_crash_reboot },
625 { "Manager", "ShowStatus", config_parse_show_status, 0, &arg_show_status },
626 { "Manager", "StatusUnitFormat", config_parse_status_unit_format, 0, &arg_status_unit_format },
627 { "Manager", "CPUAffinity", config_parse_cpu_affinity2, 0, &arg_cpu_affinity },
628 { "Manager", "NUMAPolicy", config_parse_numa_policy, 0, &arg_numa_policy.type },
629 { "Manager", "NUMAMask", config_parse_numa_mask, 0, &arg_numa_policy },
630 { "Manager", "JoinControllers", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
631 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec, 0, &arg_runtime_watchdog },
632 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec, 0, &arg_pretimeout_watchdog },
633 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec, 0, &arg_reboot_watchdog },
634 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec, 0, &arg_reboot_watchdog }, /* obsolete alias */
635 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec, 0, &arg_kexec_watchdog },
636 { "Manager", "WatchdogDevice", config_parse_path, 0, &arg_watchdog_device },
637 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string, CONFIG_PARSE_STRING_SAFE, &arg_watchdog_pretimeout_governor },
638 { "Manager", "CapabilityBoundingSet", config_parse_capability_set, 0, &arg_capability_bounding_set },
639 { "Manager", "NoNewPrivileges", config_parse_bool, 0, &arg_no_new_privs },
349cc4a5 640#if HAVE_SECCOMP
3f87eaa5 641 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs, 0, &arg_syscall_archs },
6aa2c555
LP
642#else
643 { "Manager", "SystemCallArchitectures", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
644
89fffa27 645#endif
3f87eaa5 646 { "Manager", "TimerSlackNSec", config_parse_nsec, 0, &arg_timer_slack_nsec },
c9e120e0
LP
647 { "Manager", "DefaultTimerAccuracySec", config_parse_sec, 0, &arg_defaults.timer_accuracy_usec },
648 { "Manager", "DefaultStandardOutput", config_parse_output_restricted, 0, &arg_defaults.std_output },
649 { "Manager", "DefaultStandardError", config_parse_output_restricted, 0, &arg_defaults.std_error },
650 { "Manager", "DefaultTimeoutStartSec", config_parse_sec, 0, &arg_defaults.timeout_start_usec },
651 { "Manager", "DefaultTimeoutStopSec", config_parse_sec, 0, &arg_defaults.timeout_stop_usec },
3f87eaa5 652 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort, 0, NULL },
c9e120e0
LP
653 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec, 0, &arg_defaults.device_timeout_usec },
654 { "Manager", "DefaultRestartSec", config_parse_sec, 0, &arg_defaults.restart_usec },
655 { "Manager", "DefaultStartLimitInterval", config_parse_sec, 0, &arg_defaults.start_limit_interval}, /* obsolete alias */
656 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec, 0, &arg_defaults.start_limit_interval},
657 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned, 0, &arg_defaults.start_limit_burst },
4870133b
LP
658 { "Manager", "DefaultEnvironment", config_parse_environ, arg_runtime_scope, &arg_default_environment },
659 { "Manager", "ManagerEnvironment", config_parse_environ, arg_runtime_scope, &arg_manager_environment },
c9e120e0
LP
660 { "Manager", "DefaultLimitCPU", config_parse_rlimit, RLIMIT_CPU, arg_defaults.rlimit },
661 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit, RLIMIT_FSIZE, arg_defaults.rlimit },
662 { "Manager", "DefaultLimitDATA", config_parse_rlimit, RLIMIT_DATA, arg_defaults.rlimit },
663 { "Manager", "DefaultLimitSTACK", config_parse_rlimit, RLIMIT_STACK, arg_defaults.rlimit },
664 { "Manager", "DefaultLimitCORE", config_parse_rlimit, RLIMIT_CORE, arg_defaults.rlimit },
665 { "Manager", "DefaultLimitRSS", config_parse_rlimit, RLIMIT_RSS, arg_defaults.rlimit },
666 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit, RLIMIT_NOFILE, arg_defaults.rlimit },
667 { "Manager", "DefaultLimitAS", config_parse_rlimit, RLIMIT_AS, arg_defaults.rlimit },
668 { "Manager", "DefaultLimitNPROC", config_parse_rlimit, RLIMIT_NPROC, arg_defaults.rlimit },
669 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit, RLIMIT_MEMLOCK, arg_defaults.rlimit },
670 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit, RLIMIT_LOCKS, arg_defaults.rlimit },
671 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit, RLIMIT_SIGPENDING, arg_defaults.rlimit },
672 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit, RLIMIT_MSGQUEUE, arg_defaults.rlimit },
673 { "Manager", "DefaultLimitNICE", config_parse_rlimit, RLIMIT_NICE, arg_defaults.rlimit },
674 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit, RLIMIT_RTPRIO, arg_defaults.rlimit },
675 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit, RLIMIT_RTTIME, arg_defaults.rlimit },
676 { "Manager", "DefaultCPUAccounting", config_parse_bool, 0, &arg_defaults.cpu_accounting },
677 { "Manager", "DefaultIOAccounting", config_parse_bool, 0, &arg_defaults.io_accounting },
678 { "Manager", "DefaultIPAccounting", config_parse_bool, 0, &arg_defaults.ip_accounting },
679 { "Manager", "DefaultBlockIOAccounting", config_parse_bool, 0, &arg_defaults.blockio_accounting },
680 { "Manager", "DefaultMemoryAccounting", config_parse_bool, 0, &arg_defaults.memory_accounting },
681 { "Manager", "DefaultTasksAccounting", config_parse_bool, 0, &arg_defaults.tasks_accounting },
682 { "Manager", "DefaultTasksMax", config_parse_tasks_max, 0, &arg_defaults.tasks_max },
683 { "Manager", "DefaultMemoryPressureThresholdSec", config_parse_sec, 0, &arg_defaults.memory_pressure_threshold_usec },
684 { "Manager", "DefaultMemoryPressureWatch", config_parse_memory_pressure_watch, 0, &arg_defaults.memory_pressure_watch },
4870133b 685 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action, arg_runtime_scope, &arg_cad_burst_action },
c9e120e0 686 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy, 0, &arg_defaults.oom_policy },
3f87eaa5 687 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust, 0, NULL },
856bfaeb
LB
688 { "Manager", "ReloadLimitIntervalSec", config_parse_sec, 0, &arg_reload_limit_interval_sec },
689 { "Manager", "ReloadLimitBurst", config_parse_unsigned, 0, &arg_reload_limit_burst },
aa5ae971 690#if ENABLE_SMACK
c9e120e0 691 { "Manager", "DefaultSmackProcessLabel", config_parse_string, 0, &arg_defaults.smack_process_label },
aa5ae971
ŁS
692#else
693 { "Manager", "DefaultSmackProcessLabel", config_parse_warn_compat, DISABLED_CONFIGURATION, NULL },
694#endif
d3b1c508 695 {}
487393e9
LP
696 };
697
4870133b 698 if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM)
07e0ffc8
FB
699 (void) config_parse_config_file("system.conf",
700 "Manager\0",
701 config_item_table_lookup, items,
702 CONFIG_PARSE_WARN,
703 NULL);
e94a009c 704 else {
07e0ffc8
FB
705 _cleanup_strv_free_ char **files = NULL, **dirs = NULL;
706 int r;
707
4870133b
LP
708 assert(arg_runtime_scope == RUNTIME_SCOPE_USER);
709
e94a009c 710 r = manager_find_user_config_paths(&files, &dirs);
f70e6fb4
ZJS
711 if (r < 0)
712 return log_error_errno(r, "Failed to determine config file paths: %m");
e94a009c 713
07e0ffc8
FB
714 (void) config_parse_many(
715 (const char* const*) files,
716 (const char* const*) dirs,
717 "user.conf.d",
947f59ba 718 /* root = */ NULL,
07e0ffc8
FB
719 "Manager\0",
720 config_item_table_lookup, items,
721 CONFIG_PARSE_WARN,
722 NULL, NULL, NULL);
f70e6fb4 723 }
75eb6154 724
f70e6fb4
ZJS
725 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
726 * USEC_INFINITY like everywhere else. */
c9e120e0
LP
727 if (arg_defaults.timeout_start_usec <= 0)
728 arg_defaults.timeout_start_usec = USEC_INFINITY;
729 if (arg_defaults.timeout_stop_usec <= 0)
730 arg_defaults.timeout_stop_usec = USEC_INFINITY;
487393e9 731
487393e9
LP
732 return 0;
733}
734
85cb4151 735static void set_manager_defaults(Manager *m) {
bfb27b06 736 int r;
06af2a04
TB
737
738 assert(m);
739
bfb27b06
LP
740 /* Propagates the various default unit property settings into the manager object, i.e. properties
741 * that do not affect the manager itself, but are just what newly allocated units will have set if
742 * they haven't set anything else. (Also see set_manager_settings() for the settings that affect the
743 * manager's own behaviour) */
744
745 r = manager_set_unit_defaults(m, &arg_defaults);
746 if (r < 0)
747 log_warning_errno(r, "Failed to set manager defaults, ignoring: %m");
748
749 r = manager_default_environment(m);
750 if (r < 0)
751 log_warning_errno(r, "Failed to set manager default environment, ignoring: %m");
752
753 r = manager_transient_environment_add(m, arg_default_environment);
754 if (r < 0)
755 log_warning_errno(r, "Failed to add to transient environment, ignoring: %m");
06af2a04
TB
756}
757
7b46fc6a 758static void set_manager_settings(Manager *m) {
aff3a9e1 759 int r;
7b46fc6a
LP
760
761 assert(m);
762
986935cf
FB
763 /* Propagates the various manager settings into the manager object, i.e. properties that
764 * effect the manager itself (as opposed to just being inherited into newly allocated
765 * units, see set_manager_defaults() above). */
5b65ae15 766
7b46fc6a 767 m->confirm_spawn = arg_confirm_spawn;
2a12e32e 768 m->service_watchdogs = arg_service_watchdogs;
7b46fc6a 769 m->cad_burst_action = arg_cad_burst_action;
856bfaeb
LB
770 /* Note that we don't do structured initialization here, otherwise it will reset the rate limit
771 * counter on every daemon-reload. */
772 m->reload_ratelimit.interval = arg_reload_limit_interval_sec;
773 m->reload_ratelimit.burst = arg_reload_limit_burst;
7b46fc6a 774
986935cf
FB
775 manager_set_watchdog(m, WATCHDOG_RUNTIME, arg_runtime_watchdog);
776 manager_set_watchdog(m, WATCHDOG_REBOOT, arg_reboot_watchdog);
777 manager_set_watchdog(m, WATCHDOG_KEXEC, arg_kexec_watchdog);
5717062e 778 manager_set_watchdog(m, WATCHDOG_PRETIMEOUT, arg_pretimeout_watchdog);
aff3a9e1
LB
779 r = manager_set_watchdog_pretimeout_governor(m, arg_watchdog_pretimeout_governor);
780 if (r < 0)
781 log_warning_errno(r, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor);
986935cf 782
7365a296 783 manager_set_show_status(m, arg_show_status, "commandline");
36cf4507 784 m->status_unit_format = arg_status_unit_format;
7b46fc6a
LP
785}
786
f170852a 787static int parse_argv(int argc, char *argv[]) {
f170852a 788 enum {
6339d3e6
YW
789 COMMON_GETOPT_ARGS,
790 SYSTEMD_GETOPT_ARGS,
f170852a
LP
791 };
792
793 static const struct option options[] = {
6339d3e6
YW
794 COMMON_GETOPT_OPTIONS,
795 SYSTEMD_GETOPT_OPTIONS,
fb472900 796 {}
f170852a
LP
797 };
798
799 int c, r;
9a9ca408 800 bool user_arg_seen = false;
f170852a
LP
801
802 assert(argc >= 1);
803 assert(argv);
804
df0ff127 805 if (getpid_cached() == 1)
b770165a
LP
806 opterr = 0;
807
6339d3e6 808 while ((c = getopt_long(argc, argv, SYSTEMD_GETOPT_SHORT_OPTIONS, options, NULL)) >= 0)
f170852a
LP
809
810 switch (c) {
811
812 case ARG_LOG_LEVEL:
fb472900 813 r = log_set_max_level_from_string(optarg);
2b5107e1
ZJS
814 if (r < 0)
815 return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
f170852a
LP
816
817 break;
818
819 case ARG_LOG_TARGET:
fb472900 820 r = log_set_target_from_string(optarg);
2b5107e1
ZJS
821 if (r < 0)
822 return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
f170852a
LP
823
824 break;
825
bbe63281
LP
826 case ARG_LOG_COLOR:
827
d0b170c8 828 if (optarg) {
fb472900 829 r = log_show_color_from_string(optarg);
2b5107e1
ZJS
830 if (r < 0)
831 return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
832 optarg);
d0b170c8
LP
833 } else
834 log_show_color(true);
bbe63281
LP
835
836 break;
837
838 case ARG_LOG_LOCATION:
d0b170c8 839 if (optarg) {
fb472900 840 r = log_show_location_from_string(optarg);
2b5107e1
ZJS
841 if (r < 0)
842 return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
843 optarg);
d0b170c8
LP
844 } else
845 log_show_location(true);
bbe63281
LP
846
847 break;
848
c5673ed0
DS
849 case ARG_LOG_TIME:
850
851 if (optarg) {
852 r = log_show_time_from_string(optarg);
853 if (r < 0)
854 return log_error_errno(r, "Failed to parse log time setting \"%s\": %m",
855 optarg);
856 } else
857 log_show_time(true);
858
859 break;
860
0a494f1f 861 case ARG_DEFAULT_STD_OUTPUT:
fb472900 862 r = exec_output_from_string(optarg);
2b5107e1
ZJS
863 if (r < 0)
864 return log_error_errno(r, "Failed to parse default standard output setting \"%s\": %m",
865 optarg);
c9e120e0 866 arg_defaults.std_output = r;
0a494f1f
LP
867 break;
868
869 case ARG_DEFAULT_STD_ERROR:
fb472900 870 r = exec_output_from_string(optarg);
2b5107e1
ZJS
871 if (r < 0)
872 return log_error_errno(r, "Failed to parse default standard error output setting \"%s\": %m",
873 optarg);
c9e120e0 874 arg_defaults.std_error = r;
0a494f1f
LP
875 break;
876
2f198e2f 877 case ARG_UNIT:
e6e242ad 878 r = free_and_strdup(&arg_default_unit, optarg);
23bbb0de 879 if (r < 0)
2b5107e1 880 return log_error_errno(r, "Failed to set default unit \"%s\": %m", optarg);
f170852a
LP
881
882 break;
883
edb9aaa8 884 case ARG_SYSTEM:
4870133b 885 arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
edb9aaa8 886 break;
a5dab5ce 887
af2d49f7 888 case ARG_USER:
4870133b 889 arg_runtime_scope = RUNTIME_SCOPE_USER;
9a9ca408 890 user_arg_seen = true;
a5dab5ce 891 break;
a5dab5ce 892
e965d56d 893 case ARG_TEST:
fa0f4d8a 894 arg_action = ACTION_TEST;
b87c2aa6
ZJS
895 break;
896
897 case ARG_NO_PAGER:
0221d68a 898 arg_pager_flags |= PAGER_DISABLE;
e965d56d
LP
899 break;
900
9ba0bc4e
ZJS
901 case ARG_VERSION:
902 arg_action = ACTION_VERSION;
903 break;
904
e537352b 905 case ARG_DUMP_CONFIGURATION_ITEMS:
fa0f4d8a 906 arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
e537352b
LP
907 break;
908
bbc1acab
YW
909 case ARG_DUMP_BUS_PROPERTIES:
910 arg_action = ACTION_DUMP_BUS_PROPERTIES;
911 break;
912
5c08257b
ZJS
913 case ARG_BUS_INTROSPECT:
914 arg_bus_introspect = optarg;
915 arg_action = ACTION_BUS_INTROSPECT;
916 break;
917
9e58ff9c 918 case ARG_DUMP_CORE:
599c7c54
ZJS
919 r = parse_boolean_argument("--dump-core", optarg, &arg_dump_core);
920 if (r < 0)
921 return r;
b9e74c39
LP
922 break;
923
924 case ARG_CRASH_CHVT:
a07a7324 925 r = parse_crash_chvt(optarg, &arg_crash_chvt);
b9e74c39 926 if (r < 0)
2b5107e1
ZJS
927 return log_error_errno(r, "Failed to parse crash virtual terminal index: \"%s\": %m",
928 optarg);
9e58ff9c
LP
929 break;
930
931 case ARG_CRASH_SHELL:
599c7c54
ZJS
932 r = parse_boolean_argument("--crash-shell", optarg, &arg_crash_shell);
933 if (r < 0)
934 return r;
b9e74c39
LP
935 break;
936
937 case ARG_CRASH_REBOOT:
599c7c54
ZJS
938 r = parse_boolean_argument("--crash-reboot", optarg, &arg_crash_reboot);
939 if (r < 0)
940 return r;
9e58ff9c
LP
941 break;
942
80876c20 943 case ARG_CONFIRM_SPAWN:
7d5ceb64
FB
944 arg_confirm_spawn = mfree(arg_confirm_spawn);
945
946 r = parse_confirm_spawn(optarg, &arg_confirm_spawn);
947 if (r < 0)
2b5107e1
ZJS
948 return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
949 optarg);
80876c20
LP
950 break;
951
2a12e32e 952 case ARG_SERVICE_WATCHDOGS:
599c7c54 953 r = parse_boolean_argument("--service-watchdogs=", optarg, &arg_service_watchdogs);
2a12e32e 954 if (r < 0)
599c7c54 955 return r;
2a12e32e
JK
956 break;
957
9e58ff9c 958 case ARG_SHOW_STATUS:
d450b6f2
ZJS
959 if (optarg) {
960 r = parse_show_status(optarg, &arg_show_status);
ac7ec288 961 if (r < 0)
2b5107e1
ZJS
962 return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
963 optarg);
d450b6f2
ZJS
964 } else
965 arg_show_status = SHOW_STATUS_YES;
6e98720f 966 break;
a5d87bf0 967
a16e1123
LP
968 case ARG_DESERIALIZE: {
969 int fd;
970 FILE *f;
971
e652663a 972 fd = parse_fd(optarg);
baaa35ad 973 if (fd < 0)
d2132d3d 974 return log_error_errno(fd, "Failed to parse serialization fd \"%s\": %m", optarg);
a16e1123 975
b9e74c39 976 (void) fd_cloexec(fd, true);
01e10de3
LP
977
978 f = fdopen(fd, "r");
4a62c710 979 if (!f)
2b5107e1 980 return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
a16e1123 981
74ca738f 982 safe_fclose(arg_serialization);
d3b1c508 983 arg_serialization = f;
a16e1123
LP
984
985 break;
986 }
987
2660882b 988 case ARG_SWITCHED_ROOT:
bf4df7c3 989 arg_switched_root = true;
d03bc1b8
HH
990 break;
991
ee48dbd5 992 case ARG_MACHINE_ID:
aea3f594 993 r = id128_from_string_nonzero(optarg, &arg_machine_id);
54500613 994 if (r < 0)
2b5107e1 995 return log_error_errno(r, "MachineID '%s' is not valid: %m", optarg);
ee48dbd5
NC
996 break;
997
f170852a 998 case 'h':
fa0f4d8a 999 arg_action = ACTION_HELP;
f170852a
LP
1000 break;
1001
1d2e23ab
LP
1002 case 'D':
1003 log_set_max_level(LOG_DEBUG);
1004 break;
1005
099663ff
LP
1006 case 'b':
1007 case 's':
1008 case 'z':
cd57038a
ZJS
1009 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1010 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1011 */
099663ff 1012 case '?':
df0ff127 1013 if (getpid_cached() != 1)
099663ff 1014 return -EINVAL;
601185b4
ZJS
1015 else
1016 return 0;
099663ff 1017
601185b4 1018 default:
04499a70 1019 assert_not_reached();
f170852a
LP
1020 }
1021
d7a0f1f4 1022 if (optind < argc && getpid_cached() != 1)
9a9ca408
ZJS
1023 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1024 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Excess arguments.");
1025
4870133b 1026 if (arg_action == ACTION_RUN && arg_runtime_scope == RUNTIME_SCOPE_USER && !user_arg_seen)
baaa35ad 1027 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
9a9ca408 1028 "Explicit --user argument required to run as user manager.");
d821e6d6 1029
f170852a
LP
1030 return 0;
1031}
1032
1033static int help(void) {
37ec0fdd
LP
1034 _cleanup_free_ char *link = NULL;
1035 int r;
1036
1037 r = terminal_urlify_man("systemd", "1", &link);
1038 if (r < 0)
1039 return log_oom();
f170852a 1040
2e33c433 1041 printf("%s [OPTIONS...]\n\n"
7ae47326
ZJS
1042 "%sStarts and monitors system and user services.%s\n\n"
1043 "This program takes no positional arguments.\n\n"
1044 "%sOptions%s:\n"
e537352b 1045 " -h --help Show this help\n"
cb4069d9 1046 " --version Show version\n"
cd69e88b 1047 " --test Determine initial transaction, dump it and exit\n"
03b3b55e
ZJS
1048 " --system Combined with --test: operate in system mode\n"
1049 " --user Combined with --test: operate in user mode\n"
80876c20 1050 " --dump-configuration-items Dump understood unit configuration items\n"
bbc1acab 1051 " --dump-bus-properties Dump exposed bus properties\n"
5c08257b 1052 " --bus-introspect=PATH Write XML introspection data\n"
9e58ff9c 1053 " --unit=UNIT Set default unit\n"
b9e74c39
LP
1054 " --dump-core[=BOOL] Dump core on crash\n"
1055 " --crash-vt=NR Change to specified VT on crash\n"
1056 " --crash-reboot[=BOOL] Reboot on crash\n"
1057 " --crash-shell[=BOOL] Run shell on crash\n"
1058 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
03b3b55e
ZJS
1059 " --show-status[=BOOL] Show status updates on the console during boot\n"
1060 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1061 " journal-or-kmsg, null)\n"
1062 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1063 " err, crit, alert, emerg)\n"
b9e74c39
LP
1064 " --log-color[=BOOL] Highlight important log messages\n"
1065 " --log-location[=BOOL] Include code location in log messages\n"
c5673ed0 1066 " --log-time[=BOOL] Prefix log messages with current time\n"
0a494f1f 1067 " --default-standard-output= Set default standard output for services\n"
37ec0fdd 1068 " --default-standard-error= Set default standard error output for services\n"
03b3b55e 1069 " --no-pager Do not pipe output into a pager\n"
bc556335
DDM
1070 "\nSee the %s for details.\n",
1071 program_invocation_short_name,
1072 ansi_highlight(),
1073 ansi_normal(),
1074 ansi_underline(),
1075 ansi_normal(),
1076 link);
f170852a
LP
1077
1078 return 0;
1079}
1080
2cc856ac
LP
1081static int prepare_reexecute(
1082 Manager *m,
1083 FILE **ret_f,
1084 FDSet **ret_fds,
1085 bool switching_root) {
1086
48b90859
LP
1087 _cleanup_fdset_free_ FDSet *fds = NULL;
1088 _cleanup_fclose_ FILE *f = NULL;
a16e1123
LP
1089 int r;
1090
1091 assert(m);
2cc856ac
LP
1092 assert(ret_f);
1093 assert(ret_fds);
a16e1123 1094
6b78f9b4 1095 r = manager_open_serialization(m, &f);
48b90859
LP
1096 if (r < 0)
1097 return log_error_errno(r, "Failed to create serialization file: %m");
a16e1123 1098
71445ae7 1099 /* Make sure nothing is really destructed when we shut down */
313cefa1 1100 m->n_reloading++;
718db961 1101 bus_manager_send_reloading(m, true);
71445ae7 1102
6b78f9b4 1103 fds = fdset_new();
48b90859
LP
1104 if (!fds)
1105 return log_oom();
a16e1123 1106
b3680f49 1107 r = manager_serialize(m, f, fds, switching_root);
48b90859 1108 if (r < 0)
d68c645b 1109 return r;
a16e1123 1110
48b90859
LP
1111 if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
1112 return log_error_errno(errno, "Failed to rewind serialization fd: %m");
a16e1123 1113
6b78f9b4 1114 r = fd_cloexec(fileno(f), false);
48b90859
LP
1115 if (r < 0)
1116 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
a16e1123 1117
6b78f9b4 1118 r = fdset_cloexec(fds, false);
48b90859
LP
1119 if (r < 0)
1120 return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
a16e1123 1121
2cc856ac
LP
1122 *ret_f = TAKE_PTR(f);
1123 *ret_fds = TAKE_PTR(fds);
a16e1123 1124
48b90859 1125 return 0;
a16e1123
LP
1126}
1127
a8b627aa
LP
1128static void bump_file_max_and_nr_open(void) {
1129
ff3a7019
ZJS
1130 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1131 * numbers of file descriptors are no longer a performance problem and their memory is properly
1132 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1133 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1134 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
a8b627aa
LP
1135
1136#if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
a8b627aa
LP
1137 int r;
1138#endif
1139
1140#if BUMP_PROC_SYS_FS_FILE_MAX
409607c1
ZJS
1141 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1142 * different, but the operation would fail silently.) */
a5fac1df 1143 r = sysctl_write("fs/file-max", LONG_MAX_STR);
a8b627aa 1144 if (r < 0)
b47e0fac
ZJS
1145 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING,
1146 r, "Failed to bump fs.file-max, ignoring: %m");
a8b627aa
LP
1147#endif
1148
a8b627aa
LP
1149#if BUMP_PROC_SYS_FS_NR_OPEN
1150 int v = INT_MAX;
1151
ff3a7019
ZJS
1152 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1153 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1154 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1155 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1156 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1157 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
a8b627aa
LP
1158
1159 for (;;) {
1160 int k;
1161
1162 v &= ~(__SIZEOF_POINTER__ - 1); /* Round down to next multiple of the pointer size */
1163 if (v < 1024) {
1164 log_warning("Can't bump fs.nr_open, value too small.");
1165 break;
1166 }
1167
1168 k = read_nr_open();
1169 if (k < 0) {
1170 log_error_errno(k, "Failed to read fs.nr_open: %m");
1171 break;
1172 }
1173 if (k >= v) { /* Already larger */
1174 log_debug("Skipping bump, value is already larger.");
1175 break;
1176 }
1177
b47e0fac 1178 r = sysctl_writef("fs/nr_open", "%i", v);
a8b627aa
LP
1179 if (r == -EINVAL) {
1180 log_debug("Couldn't write fs.nr_open as %i, halving it.", v);
1181 v /= 2;
1182 continue;
1183 }
1184 if (r < 0) {
1185 log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r, "Failed to bump fs.nr_open, ignoring: %m");
1186 break;
1187 }
1188
1189 log_debug("Successfully bumped fs.nr_open to %i", v);
1190 break;
1191 }
1192#endif
1193}
1194
eadb4f19 1195static int bump_rlimit_nofile(const struct rlimit *saved_rlimit) {
cda7faa9 1196 struct rlimit new_rlimit;
9264cc39 1197 int r, nr;
4096d6f5 1198
52d62075
LP
1199 /* Get the underlying absolute limit the kernel enforces */
1200 nr = read_nr_open();
1201
cda7faa9
LP
1202 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1203 new_rlimit = (struct rlimit) {
1204 .rlim_cur = MAX((rlim_t) nr, saved_rlimit->rlim_cur),
1205 .rlim_max = MAX((rlim_t) nr, saved_rlimit->rlim_max),
1206 };
1207
1208 /* Shortcut if nothing changes. */
1209 if (saved_rlimit->rlim_max >= new_rlimit.rlim_max &&
1210 saved_rlimit->rlim_cur >= new_rlimit.rlim_cur) {
1211 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1212 return 0;
1213 }
1214
52d62075
LP
1215 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1216 * both hard and soft. */
cda7faa9 1217 r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
23bbb0de 1218 if (r < 0)
3ce40911 1219 return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
4096d6f5
LP
1220
1221 return 0;
1222}
1223
eadb4f19 1224static int bump_rlimit_memlock(const struct rlimit *saved_rlimit) {
cda7faa9 1225 struct rlimit new_rlimit;
04d1ee0f 1226 uint64_t mm;
fb3ae275
LP
1227 int r;
1228
ff3a7019
ZJS
1229 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1230 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1231 * IPAddressDeny=, hence let's bump the value high enough for our user. */
fb3ae275 1232
cda7faa9
LP
1233 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1234 * must be unsigned, hence this is a given, but let's make this clear here. */
1235 assert_cc(RLIM_INFINITY > 0);
1236
ff3a7019
ZJS
1237 mm = physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1238 * physical RAM. We allow an eighth to be locked by us, just to
1239 * pick a value. */
04d1ee0f 1240
cda7faa9 1241 new_rlimit = (struct rlimit) {
04d1ee0f
LP
1242 .rlim_cur = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur, mm),
1243 .rlim_max = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max, mm),
cda7faa9
LP
1244 };
1245
1246 if (saved_rlimit->rlim_max >= new_rlimit.rlim_cur &&
1247 saved_rlimit->rlim_cur >= new_rlimit.rlim_max) {
1248 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1249 return 0;
1250 }
1251
1252 r = setrlimit_closest(RLIMIT_MEMLOCK, &new_rlimit);
fb3ae275
LP
1253 if (r < 0)
1254 return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1255
1256 return 0;
1257}
1258
80758717 1259static void test_usr(void) {
80758717 1260
796ac4c1 1261 /* Check that /usr is either on the same file system as / or mounted already. */
80758717 1262
db55bbf2 1263 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
871c44a7
LP
1264 return;
1265
8b173b5e 1266 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
871c44a7 1267 "Some things will probably break (sometimes even silently) in mysterious ways. "
a25d9395 1268 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
871c44a7
LP
1269}
1270
d3b1c508 1271static int enforce_syscall_archs(Set *archs) {
349cc4a5 1272#if HAVE_SECCOMP
d3b1c508
LP
1273 int r;
1274
83f12b27
FS
1275 if (!is_seccomp_available())
1276 return 0;
1277
469830d1 1278 r = seccomp_restrict_archs(arg_syscall_archs);
d3b1c508 1279 if (r < 0)
469830d1 1280 return log_error_errno(r, "Failed to enforce system call architecture restrication: %m");
d3b1c508 1281#endif
469830d1 1282 return 0;
d3b1c508
LP
1283}
1284
4bd03515
ZJS
1285static int os_release_status(void) {
1286 _cleanup_free_ char *pretty_name = NULL, *name = NULL, *version = NULL,
1287 *ansi_color = NULL, *support_end = NULL;
b6e2f329
LP
1288 int r;
1289
d58ad743
LP
1290 r = parse_os_release(NULL,
1291 "PRETTY_NAME", &pretty_name,
4bd03515
ZJS
1292 "NAME", &name,
1293 "VERSION", &version,
1294 "ANSI_COLOR", &ansi_color,
1295 "SUPPORT_END", &support_end);
d58ad743 1296 if (r < 0)
4bd03515
ZJS
1297 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1298 "Failed to read os-release file, ignoring: %m");
b6e2f329 1299
02b7005e 1300 const char *label = os_release_pretty_name(pretty_name, name);
4bd03515
ZJS
1301
1302 if (show_status_on(arg_show_status)) {
1303 if (log_get_show_color())
1304 status_printf(NULL, 0,
1305 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1306 empty_to_null(ansi_color) ?: "1",
1307 label);
1308 else
1309 status_printf(NULL, 0,
1310 "\nWelcome to %s!\n",
1311 label);
1312 }
1313
6bfe9b3b 1314 if (support_end && os_release_support_ended(support_end, /* quiet */ false, NULL) > 0)
4bd03515
ZJS
1315 /* pretty_name may include the version already, so we'll print the version only if we
1316 * have it and we're not using pretty_name. */
1317 status_printf(ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL, 0,
1318 "This OS version (%s%s%s) is past its end-of-support date (%s)",
1319 label,
1320 (pretty_name || !version) ? "" : " version ",
1321 (pretty_name || !version) ? "" : version,
1322 support_end);
1323
1324 return 0;
b6e2f329
LP
1325}
1326
3f37a825
LB
1327static int setup_os_release(RuntimeScope scope) {
1328 _cleanup_free_ char *os_release_dst = NULL;
1329 const char *os_release_src = "/etc/os-release";
1330 int r;
1331
1332 if (access("/etc/os-release", F_OK) < 0) {
1333 if (errno != ENOENT)
1334 log_debug_errno(errno, "Failed to check if /etc/os-release exists, ignoring: %m");
1335
1336 os_release_src = "/usr/lib/os-release";
1337 }
1338
1339 if (scope == RUNTIME_SCOPE_SYSTEM) {
663e2756 1340 os_release_dst = strdup("/run/systemd/propagate/.os-release-stage/os-release");
3f37a825
LB
1341 if (!os_release_dst)
1342 return log_oom_debug();
1343 } else {
663e2756 1344 if (asprintf(&os_release_dst, "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage/os-release", geteuid()) < 0)
3f37a825
LB
1345 return log_oom_debug();
1346 }
1347
1348 r = mkdir_parents_label(os_release_dst, 0755);
bf85c239 1349 if (r < 0)
3f37a825
LB
1350 return log_debug_errno(r, "Failed to create parent directory of %s, ignoring: %m", os_release_dst);
1351
663e2756 1352 r = copy_file_atomic(os_release_src, os_release_dst, 0644, COPY_MAC_CREATE|COPY_REPLACE);
3f37a825
LB
1353 if (r < 0)
1354 return log_debug_errno(r, "Failed to create %s, ignoring: %m", os_release_dst);
1355
1356 return 0;
1357}
1358
fdd25311
LP
1359static int write_container_id(void) {
1360 const char *c;
7756528e 1361 int r = 0; /* avoid false maybe-uninitialized warning */
fdd25311
LP
1362
1363 c = getenv("container");
1364 if (isempty(c))
1365 return 0;
1366
2053593f 1367 WITH_UMASK(0022)
8612da97 1368 r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
19854865 1369 if (r < 0)
f1f849b0 1370 return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
19854865
LP
1371
1372 return 1;
1373}
1374
1375static int bump_unix_max_dgram_qlen(void) {
1376 _cleanup_free_ char *qlen = NULL;
1377 unsigned long v;
1378 int r;
1379
ff3a7019
ZJS
1380 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1381 * the value really really early during boot, so that it is actually applied to all our sockets,
1382 * including the $NOTIFY_SOCKET one. */
19854865
LP
1383
1384 r = read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen);
1385 if (r < 0)
ff3a7019
ZJS
1386 return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
1387 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
19854865
LP
1388
1389 r = safe_atolu(qlen, &v);
1390 if (r < 0)
3130fca5 1391 return log_warning_errno(r, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen);
19854865
LP
1392
1393 if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
1394 return 0;
1395
27c8ca43 1396 r = sysctl_write("net/unix/max_dgram_qlen", STRINGIFY(DEFAULT_UNIX_MAX_DGRAM_QLEN));
19854865
LP
1397 if (r < 0)
1398 return log_full_errno(IN_SET(r, -EROFS, -EPERM, -EACCES) ? LOG_DEBUG : LOG_WARNING, r,
1399 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1400
1401 return 1;
fdd25311
LP
1402}
1403
32391275
FB
1404static int fixup_environment(void) {
1405 _cleanup_free_ char *term = NULL;
4dc63c4b 1406 const char *t;
32391275
FB
1407 int r;
1408
43db615b
LP
1409 /* Only fix up the environment when we are started as PID 1 */
1410 if (getpid_cached() != 1)
1411 return 0;
1412
1413 /* We expect the environment to be set correctly if run inside a container. */
84af7821
LP
1414 if (detect_container() > 0)
1415 return 0;
1416
ff3a7019
ZJS
1417 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1418 * backend device used by the console. We try to make a better guess here since some consoles might
1419 * not have support for color mode for example.
32391275 1420 *
43db615b 1421 * However if TERM was configured through the kernel command line then leave it alone. */
1d84ad94 1422 r = proc_cmdline_get_key("TERM", 0, &term);
32391275
FB
1423 if (r < 0)
1424 return r;
32391275 1425
153d5dfd
DDM
1426 if (r == 0) {
1427 r = proc_cmdline_get_key("systemd.tty.term.console", 0, &term);
1428 if (r < 0)
1429 return r;
1430 }
1431
4dc63c4b
LP
1432 t = term ?: default_term_for_tty("/dev/console");
1433
1434 if (setenv("TERM", t, 1) < 0)
32391275
FB
1435 return -errno;
1436
9d48671c 1437 /* The kernels sets HOME=/ for init. Let's undo this. */
44ee03d1
ZJS
1438 if (path_equal_ptr(getenv("HOME"), "/"))
1439 assert_se(unsetenv("HOME") == 0);
9d48671c 1440
32391275
FB
1441 return 0;
1442}
1443
6808a0bc
LP
1444static void redirect_telinit(int argc, char *argv[]) {
1445
1446 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1447
1448#if HAVE_SYSV_COMPAT
1449 if (getpid_cached() == 1)
1450 return;
1451
2306d177 1452 if (!invoked_as(argv, "init"))
6808a0bc
LP
1453 return;
1454
1455 execv(SYSTEMCTL_BINARY_PATH, argv);
1456 log_error_errno(errno, "Failed to exec " SYSTEMCTL_BINARY_PATH ": %m");
a45d7127 1457 exit(EXIT_FAILURE);
6808a0bc
LP
1458#endif
1459}
1460
b22d392d 1461static int become_shutdown(int objective, int retval) {
b22d392d
VC
1462 static const char* const table[_MANAGER_OBJECTIVE_MAX] = {
1463 [MANAGER_EXIT] = "exit",
1464 [MANAGER_REBOOT] = "reboot",
1465 [MANAGER_POWEROFF] = "poweroff",
1466 [MANAGER_HALT] = "halt",
1467 [MANAGER_KEXEC] = "kexec",
1468 };
4a36297c 1469
d2ebd50d 1470 char log_level[STRLEN("--log-level=") + DECIMAL_STR_MAX(int)],
4688b089
ZJS
1471 timeout[STRLEN("--timeout=") + DECIMAL_STR_MAX(usec_t) + STRLEN("us")],
1472 exit_code[STRLEN("--exit-code=") + DECIMAL_STR_MAX(uint8_t)];
4a36297c
LP
1473
1474 _cleanup_strv_free_ char **env_block = NULL;
f16890f8 1475 usec_t watchdog_timer = 0;
4a36297c
LP
1476 int r;
1477
b22d392d
VC
1478 assert(objective >= 0 && objective < _MANAGER_OBJECTIVE_MAX);
1479 assert(table[objective]);
4a36297c 1480
d2ebd50d 1481 xsprintf(log_level, "--log-level=%d", log_get_max_level());
c9e120e0 1482 xsprintf(timeout, "--timeout=%" PRI_USEC "us", arg_defaults.timeout_stop_usec);
4a36297c 1483
4688b089
ZJS
1484 const char* command_line[10] = {
1485 SYSTEMD_SHUTDOWN_BINARY_PATH,
1486 table[objective],
1487 log_level,
1488 timeout,
1489 /* Note that the last position is a terminator and must contain NULL. */
1490 };
1491 size_t pos = 4;
1492
1493 assert(command_line[pos-1]);
1494 assert(!command_line[pos]);
1495
4a36297c
LP
1496 switch (log_get_target()) {
1497
1498 case LOG_TARGET_KMSG:
1499 case LOG_TARGET_JOURNAL_OR_KMSG:
1500 case LOG_TARGET_SYSLOG_OR_KMSG:
d2ebd50d 1501 command_line[pos++] = "--log-target=kmsg";
4a36297c
LP
1502 break;
1503
1504 case LOG_TARGET_NULL:
6b7f150b 1505 command_line[pos++] = "--log-target=null";
4a36297c
LP
1506 break;
1507
1508 case LOG_TARGET_CONSOLE:
1509 default:
d2ebd50d 1510 command_line[pos++] = "--log-target=console";
4a36297c
LP
1511 break;
1512 };
1513
1514 if (log_get_show_color())
1515 command_line[pos++] = "--log-color";
1516
1517 if (log_get_show_location())
1518 command_line[pos++] = "--log-location";
1519
c5673ed0
DS
1520 if (log_get_show_time())
1521 command_line[pos++] = "--log-time";
1522
3f92250f
DDM
1523 xsprintf(exit_code, "--exit-code=%d", retval);
1524 command_line[pos++] = exit_code;
4a36297c 1525
14ecfc1c 1526 assert(pos < ELEMENTSOF(command_line));
4688b089
ZJS
1527
1528 /* The watchdog: */
4a36297c 1529
b22d392d 1530 if (objective == MANAGER_REBOOT)
65224c1d 1531 watchdog_timer = arg_reboot_watchdog;
b22d392d 1532 else if (objective == MANAGER_KEXEC)
acafd7d8
LB
1533 watchdog_timer = arg_kexec_watchdog;
1534
f16890f8 1535 /* If we reboot or kexec let's set the shutdown watchdog and tell the
5717062e
CK
1536 * shutdown binary to repeatedly ping it.
1537 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1538 (void) watchdog_setup_pretimeout(0);
aff3a9e1 1539 (void) watchdog_setup_pretimeout_governor(NULL);
f16890f8
FB
1540 r = watchdog_setup(watchdog_timer);
1541 watchdog_close(r < 0);
4a36297c 1542
4688b089
ZJS
1543 /* The environment block: */
1544
1545 env_block = strv_copy(environ);
1546
f16890f8
FB
1547 /* Tell the binary how often to ping, ignore failure */
1548 (void) strv_extendf(&env_block, "WATCHDOG_USEC="USEC_FMT, watchdog_timer);
8a2c1fbf 1549
f16890f8
FB
1550 if (arg_watchdog_device)
1551 (void) strv_extendf(&env_block, "WATCHDOG_DEVICE=%s", arg_watchdog_device);
4a36297c 1552
3178d23d
FB
1553 /* Avoid the creation of new processes forked by the kernel; at this
1554 * point, we will not listen to the signals anyway */
4a36297c
LP
1555 if (detect_container() <= 0)
1556 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER);
1557
1558 execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
1559 return -errno;
1560}
1561
e839bafd
LP
1562static void initialize_clock(void) {
1563 int r;
1564
3753325b
LP
1565 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1566 * we are running, but only once. */
1567
e839bafd
LP
1568 if (clock_is_localtime(NULL) > 0) {
1569 int min;
1570
ff3a7019 1571 /* The very first call of settimeofday() also does a time warp in the kernel.
e839bafd 1572 *
ff3a7019
ZJS
1573 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1574 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1575 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
e839bafd
LP
1576 */
1577 r = clock_set_timezone(&min);
1578 if (r < 0)
1579 log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
1580 else
1581 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
1582
d46b79bb 1583 } else if (!in_initrd())
e839bafd
LP
1584 /*
1585 * Do a dummy very first call to seal the kernel's time warp magic.
1586 *
ff3a7019
ZJS
1587 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1588 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1589 * time-warp or the sealing until we reach the real system.
e839bafd 1590 *
ff3a7019
ZJS
1591 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1592 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1593 * time concepts will be treated as UTC that way.
e839bafd
LP
1594 */
1595 (void) clock_reset_timewarp();
e839bafd 1596
b10abe4b
EI
1597 ClockChangeDirection change_dir;
1598 r = clock_apply_epoch(&change_dir);
1599 if (r > 0 && change_dir == CLOCK_CHANGE_FORWARD)
e839bafd 1600 log_info("System time before build time, advancing clock.");
b10abe4b
EI
1601 else if (r > 0 && change_dir == CLOCK_CHANGE_BACKWARD)
1602 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1603 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX, USEC_PER_DAY));
1604 else if (r < 0 && change_dir == CLOCK_CHANGE_FORWARD)
1605 log_error_errno(r, "Current system time is before build time, but cannot correct: %m");
1606 else if (r < 0 && change_dir == CLOCK_CHANGE_BACKWARD)
1607 log_error_errno(r, "Current system time is further ahead %s after build time, but cannot correct: %m",
1608 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX, USEC_PER_DAY));
e839bafd
LP
1609}
1610
3753325b 1611static void apply_clock_update(void) {
3753325b
LP
1612 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1613 * command line and such. */
1614
1615 if (arg_clock_usec == 0)
1616 return;
1617
45250e66
LP
1618 if (getpid_cached() != 1)
1619 return;
1620
52bb308c 1621 if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(arg_clock_usec)) < 0)
3753325b 1622 log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m");
04f5c018 1623 else
3753325b 1624 log_info("Set system clock to %s, as specified on the kernel command line.",
04f5c018 1625 FORMAT_TIMESTAMP(arg_clock_usec));
3753325b
LP
1626}
1627
d247f232 1628static void cmdline_take_random_seed(void) {
d247f232
LP
1629 size_t suggested;
1630 int r;
1631
1632 if (arg_random_seed_size == 0)
1633 return;
1634
1635 if (getpid_cached() != 1)
1636 return;
1637
1638 assert(arg_random_seed);
1639 suggested = random_pool_size();
1640
1641 if (arg_random_seed_size < suggested)
1642 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1643 arg_random_seed_size, suggested);
1644
61bd7d1e 1645 r = random_write_entropy(-1, arg_random_seed, arg_random_seed_size, true);
d247f232
LP
1646 if (r < 0) {
1647 log_warning_errno(r, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1648 return;
1649 }
1650
1651 log_notice("Successfully credited entropy passed on kernel command line.\n"
ff3a7019
ZJS
1652 "Note that the seed provided this way is accessible to unprivileged programs. "
1653 "This functionality should not be used outside of testing environments.");
d247f232
LP
1654}
1655
1e41242e 1656static void initialize_coredump(bool skip_setup) {
1e41242e
LP
1657 if (getpid_cached() != 1)
1658 return;
1659
ff3a7019
ZJS
1660 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1661 * the limit) will process core dumps for system services by default. */
1e41242e
LP
1662 if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
1663 log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
1664
ff3a7019
ZJS
1665 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1666 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
32e27670 1667 * command line later so core dumps can still be generated during early startup and in initrd. */
1e41242e 1668 if (!skip_setup)
e557b1a6 1669 disable_coredumps();
1e41242e
LP
1670}
1671
c6885f5f
FB
1672static void initialize_core_pattern(bool skip_setup) {
1673 int r;
1674
1675 if (skip_setup || !arg_early_core_pattern)
1676 return;
1677
1678 if (getpid_cached() != 1)
1679 return;
1680
57512c89 1681 r = write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern, WRITE_STRING_FILE_DISABLE_BUFFER);
c6885f5f 1682 if (r < 0)
ff3a7019
ZJS
1683 log_warning_errno(r, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1684 arg_early_core_pattern);
c6885f5f
FB
1685}
1686
61fbbac1
ZJS
1687static void update_cpu_affinity(bool skip_setup) {
1688 _cleanup_free_ char *mask = NULL;
1689
1690 if (skip_setup || !arg_cpu_affinity.set)
1691 return;
1692
1693 assert(arg_cpu_affinity.allocated > 0);
1694
667030bf
ZJS
1695 mask = cpu_set_to_range_string(&arg_cpu_affinity);
1696 log_debug("Setting CPU affinity to {%s}.", strnull(mask));
61fbbac1
ZJS
1697
1698 if (sched_setaffinity(0, arg_cpu_affinity.allocated, arg_cpu_affinity.set) < 0)
6b1fa539 1699 log_warning_errno(errno, "Failed to set CPU affinity, ignoring: %m");
61fbbac1
ZJS
1700}
1701
b070c7c0
MS
1702static void update_numa_policy(bool skip_setup) {
1703 int r;
1704 _cleanup_free_ char *nodes = NULL;
1705 const char * policy = NULL;
1706
1707 if (skip_setup || !mpol_is_valid(numa_policy_get_type(&arg_numa_policy)))
1708 return;
1709
1710 if (DEBUG_LOGGING) {
1711 policy = mpol_to_string(numa_policy_get_type(&arg_numa_policy));
1712 nodes = cpu_set_to_range_string(&arg_numa_policy.nodes);
667030bf 1713 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy), strnull(nodes));
b070c7c0
MS
1714 }
1715
1716 r = apply_numa_policy(&arg_numa_policy);
1717 if (r == -EOPNOTSUPP)
1718 log_debug_errno(r, "NUMA support not available, ignoring.");
1719 else if (r < 0)
6b1fa539 1720 log_warning_errno(r, "Failed to set NUMA memory policy, ignoring: %m");
b070c7c0
MS
1721}
1722
19fd72df
LP
1723static void filter_args(
1724 const char* dst[],
1725 size_t *dst_index,
1726 char **src,
1727 int argc) {
1728
846f1da4 1729 assert(dst);
19fd72df 1730 assert(dst_index);
846f1da4
ZJS
1731
1732 /* Copy some filtered arguments into the dst array from src. */
1733 for (int i = 1; i < argc; i++) {
1734 if (STR_IN_SET(src[i],
1735 "--switched-root",
1736 "--system",
1737 "--user"))
1738 continue;
1739
1740 if (startswith(src[i], "--deserialize="))
1741 continue;
1742 if (streq(src[i], "--deserialize")) {
1743 i++; /* Skip the argument too */
1744 continue;
1745 }
1746
1747 /* Skip target unit designators. We already acted upon this information and have queued
1748 * appropriate jobs. We don't want to redo all this after reexecution. */
1749 if (startswith(src[i], "--unit="))
1750 continue;
1751 if (streq(src[i], "--unit")) {
1752 i++; /* Skip the argument too */
1753 continue;
1754 }
1755
846f1da4 1756 /* Seems we have a good old option. Let's pass it over to the new instance. */
19fd72df 1757 dst[(*dst_index)++] = src[i];
846f1da4
ZJS
1758 }
1759}
1760
05be3e8b
LB
1761static void finish_remaining_processes(ManagerObjective objective) {
1762 assert(objective >= 0 && objective < _MANAGER_OBJECTIVE_MAX);
1763
1764 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1765 * SIGCHLD for them after deserializing. */
1766 if (IN_SET(objective, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT))
c9e120e0 1767 broadcast_signal(SIGTERM, /* wait_for_exit= */ false, /* send_sighup= */ true, arg_defaults.timeout_stop_usec);
05be3e8b
LB
1768
1769 /* On soft reboot really make sure nothing is left */
1770 if (objective == MANAGER_SOFT_REBOOT)
c9e120e0 1771 broadcast_signal(SIGKILL, /* wait_for_exit= */ false, /* send_sighup= */ false, arg_defaults.timeout_stop_usec);
05be3e8b
LB
1772}
1773
1e3eee8c
ZJS
1774static int do_reexecute(
1775 ManagerObjective objective,
3c7878f9 1776 int argc,
846f1da4 1777 char* argv[],
3c7878f9
LP
1778 const struct rlimit *saved_rlimit_nofile,
1779 const struct rlimit *saved_rlimit_memlock,
1780 FDSet *fds,
1781 const char *switch_root_dir,
1782 const char *switch_root_init,
1783 const char **ret_error_message) {
1784
19fd72df 1785 size_t i, args_size;
3c7878f9
LP
1786 const char **args;
1787 int r;
1788
13ffc607 1789 assert(IN_SET(objective, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT));
19fd72df 1790 assert(argc >= 0);
3c7878f9
LP
1791 assert(saved_rlimit_nofile);
1792 assert(saved_rlimit_memlock);
1793 assert(ret_error_message);
1794
aaa27e2e
DDM
1795 if (switch_root_init) {
1796 r = chase(switch_root_init, switch_root_dir, CHASE_PREFIX_ROOT, NULL, NULL);
1797 if (r < 0)
1798 log_warning_errno(r, "Failed to chase configured init %s/%s: %m",
1799 strempty(switch_root_dir), switch_root_init);
1800 } else {
1801 r = chase(SYSTEMD_BINARY_PATH, switch_root_dir, CHASE_PREFIX_ROOT, NULL, NULL);
1802 if (r < 0)
1803 log_debug_errno(r, "Failed to chase our own binary %s/%s: %m",
1804 strempty(switch_root_dir), SYSTEMD_BINARY_PATH);
1805 }
1806
1807 if (r < 0) {
1808 r = chase("/sbin/init", switch_root_dir, CHASE_PREFIX_ROOT, NULL, NULL);
1809 if (r < 0)
1810 return log_error_errno(r, "Failed to chase %s/sbin/init", strempty(switch_root_dir));
1811 }
1812
ff3a7019
ZJS
1813 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1814 * rebooted while we do that */
3c7878f9
LP
1815 watchdog_close(true);
1816
ddfa8b0b
LP
1817 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1818 * the kernel default to its child processes */
1819 if (saved_rlimit_nofile->rlim_cur != 0)
3c7878f9 1820 (void) setrlimit(RLIMIT_NOFILE, saved_rlimit_nofile);
ddfa8b0b 1821 if (saved_rlimit_memlock->rlim_cur != RLIM_INFINITY)
3c7878f9
LP
1822 (void) setrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock);
1823
05be3e8b 1824 finish_remaining_processes(objective);
13ffc607
LP
1825
1826 if (!switch_root_dir && objective == MANAGER_SOFT_REBOOT) {
1827 /* If no switch root dir is specified, then check if /run/nextroot/ qualifies and use that */
1828 r = path_is_os_tree("/run/nextroot");
1829 if (r < 0 && r != -ENOENT)
1830 log_debug_errno(r, "Failed to determine if /run/nextroot/ is a valid OS tree, ignoring: %m");
1831 else if (r > 0)
1832 switch_root_dir = "/run/nextroot";
1833 }
3c7878f9 1834
13ffc607 1835 if (switch_root_dir) {
13ffc607
LP
1836 r = switch_root(/* new_root= */ switch_root_dir,
1837 /* old_root_after= */ NULL,
b12d41a8 1838 /* flags= */ (objective == MANAGER_SWITCH_ROOT ? SWITCH_ROOT_DESTROY_OLD_ROOT : 0) |
c2d62118 1839 (objective == MANAGER_SOFT_REBOOT ? 0 : SWITCH_ROOT_RECURSIVE_RUN));
3c7878f9
LP
1840 if (r < 0)
1841 log_error_errno(r, "Failed to switch root, trying to continue: %m");
1842 }
1843
d2ebd50d 1844 args_size = argc + 5;
3c7878f9
LP
1845 args = newa(const char*, args_size);
1846
1847 if (!switch_root_init) {
d2ebd50d 1848 char sfd[STRLEN("--deserialize=") + DECIMAL_STR_MAX(int)];
3c7878f9 1849
ff3a7019
ZJS
1850 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1851 * only if the user didn't specify an explicit init to spawn. */
3c7878f9
LP
1852
1853 assert(arg_serialization);
1854 assert(fds);
1855
d2ebd50d 1856 xsprintf(sfd, "--deserialize=%i", fileno(arg_serialization));
3c7878f9 1857
846f1da4 1858 i = 1; /* Leave args[0] empty for now. */
846f1da4 1859
06afda6b
FS
1860 /* Put our stuff first to make sure it always gets parsed in case
1861 * we get weird stuff from the kernel cmdline (like --) */
13ffc607 1862 if (IN_SET(objective, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT))
3c7878f9 1863 args[i++] = "--switched-root";
40d73340 1864 args[i++] = runtime_scope_cmdline_option_to_string(arg_runtime_scope);
3c7878f9 1865 args[i++] = sfd;
06afda6b
FS
1866
1867 filter_args(args, &i, argv, argc);
1868
3c7878f9
LP
1869 args[i++] = NULL;
1870
1871 assert(i <= args_size);
1872
1873 /*
50b35193
ZJS
1874 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
1875 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
ff3a7019
ZJS
1876 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
1877 * and wait() for it in the parent, before proceeding into the exec().
3c7878f9
LP
1878 */
1879 valgrind_summary_hack();
1880
846f1da4 1881 args[0] = SYSTEMD_BINARY_PATH;
3c7878f9 1882 (void) execv(args[0], (char* const*) args);
1e3eee8c
ZJS
1883
1884 if (objective == MANAGER_REEXECUTE) {
1885 *ret_error_message = "Failed to execute our own binary";
1886 return log_error_errno(errno, "Failed to execute our own binary %s: %m", args[0]);
1887 }
1888
846f1da4 1889 log_debug_errno(errno, "Failed to execute our own binary %s, trying fallback: %m", args[0]);
3c7878f9
LP
1890 }
1891
ff3a7019
ZJS
1892 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
1893 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
1894 * but let's hope that doesn't matter.) */
3c7878f9
LP
1895
1896 arg_serialization = safe_fclose(arg_serialization);
1897 fds = fdset_free(fds);
1898
1899 /* Reopen the console */
1900 (void) make_console_stdio();
1901
846f1da4
ZJS
1902 i = 1; /* Leave args[0] empty for now. */
1903 for (int j = 1; j <= argc; j++)
3c7878f9 1904 args[i++] = argv[j];
3c7878f9
LP
1905 assert(i <= args_size);
1906
55c041b4 1907 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
3c7878f9
LP
1908 (void) reset_all_signal_handlers();
1909 (void) reset_signal_mask();
595225af 1910 (void) rlimit_nofile_safe();
3c7878f9
LP
1911
1912 if (switch_root_init) {
1913 args[0] = switch_root_init;
a5cede8c 1914 (void) execve(args[0], (char* const*) args, saved_env);
846f1da4 1915 log_warning_errno(errno, "Failed to execute configured init %s, trying fallback: %m", args[0]);
3c7878f9
LP
1916 }
1917
1918 args[0] = "/sbin/init";
1919 (void) execv(args[0], (char* const*) args);
1920 r = -errno;
1921
1922 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1923 ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL,
1924 "Failed to execute /sbin/init");
1925
1e3eee8c 1926 *ret_error_message = "Failed to execute fallback shell";
3c7878f9
LP
1927 if (r == -ENOENT) {
1928 log_warning("No /sbin/init, trying fallback");
1929
1930 args[0] = "/bin/sh";
1931 args[1] = NULL;
a5cede8c 1932 (void) execve(args[0], (char* const*) args, saved_env);
1e3eee8c 1933 return log_error_errno(errno, "Failed to execute /bin/sh, giving up: %m");
3c7878f9 1934 } else
6b1fa539 1935 return log_error_errno(r, "Failed to execute /sbin/init, giving up: %m");
3c7878f9
LP
1936}
1937
7eb35049
LP
1938static int invoke_main_loop(
1939 Manager *m,
a9fd4cd1
FB
1940 const struct rlimit *saved_rlimit_nofile,
1941 const struct rlimit *saved_rlimit_memlock,
7eb35049 1942 int *ret_retval, /* Return parameters relevant for shutting down */
7eb35049
LP
1943 FDSet **ret_fds, /* Return parameters for reexecuting */
1944 char **ret_switch_root_dir, /* … */
1945 char **ret_switch_root_init, /* … */
1946 const char **ret_error_message) {
1947
1948 int r;
1949
1950 assert(m);
a9fd4cd1
FB
1951 assert(saved_rlimit_nofile);
1952 assert(saved_rlimit_memlock);
7eb35049 1953 assert(ret_retval);
7eb35049
LP
1954 assert(ret_fds);
1955 assert(ret_switch_root_dir);
1956 assert(ret_switch_root_init);
1957 assert(ret_error_message);
1958
1959 for (;;) {
5409c6fc
ZJS
1960 int objective = manager_loop(m);
1961 if (objective < 0) {
7eb35049 1962 *ret_error_message = "Failed to run main loop";
ad5db940
OJ
1963 return log_struct_errno(LOG_EMERG, objective,
1964 LOG_MESSAGE("Failed to run main loop: %m"),
1965 "MESSAGE_ID=" SD_MESSAGE_CORE_MAINLOOP_FAILED_STR);
7eb35049
LP
1966 }
1967
5409c6fc 1968 switch (objective) {
7eb35049 1969
a6ecbf83 1970 case MANAGER_RELOAD: {
bda7d78b 1971 LogTarget saved_log_target;
a6ecbf83
FB
1972 int saved_log_level;
1973
dd0ab174
LP
1974 manager_send_reloading(m);
1975
af2fb2f2 1976 log_info("Reloading...");
7eb35049 1977
ff3a7019
ZJS
1978 /* First, save any overridden log level/target, then parse the configuration file,
1979 * which might change the log level to new settings. */
bda7d78b 1980
a6ecbf83 1981 saved_log_level = m->log_level_overridden ? log_get_max_level() : -1;
bda7d78b 1982 saved_log_target = m->log_target_overridden ? log_get_target() : _LOG_TARGET_INVALID;
a6ecbf83 1983
a9fd4cd1 1984 (void) parse_configuration(saved_rlimit_nofile, saved_rlimit_memlock);
7eb35049
LP
1985
1986 set_manager_defaults(m);
986935cf 1987 set_manager_settings(m);
7eb35049 1988
61fbbac1 1989 update_cpu_affinity(false);
b070c7c0 1990 update_numa_policy(false);
61fbbac1 1991
a6ecbf83
FB
1992 if (saved_log_level >= 0)
1993 manager_override_log_level(m, saved_log_level);
bda7d78b
FB
1994 if (saved_log_target >= 0)
1995 manager_override_log_target(m, saved_log_target);
a6ecbf83 1996
5409c6fc 1997 if (manager_reload(m) < 0)
ff3a7019
ZJS
1998 /* Reloading failed before the point of no return.
1999 * Let's continue running as if nothing happened. */
7a35fa24 2000 m->objective = MANAGER_OK;
af2fb2f2
LB
2001 else
2002 log_info("Reloading finished in " USEC_FMT " ms.",
2003 usec_sub_unsigned(now(CLOCK_MONOTONIC), m->timestamps[MANAGER_TIMESTAMP_UNITS_LOAD].monotonic) / USEC_PER_MSEC);
7eb35049 2004
5409c6fc 2005 continue;
a6ecbf83 2006 }
7eb35049
LP
2007
2008 case MANAGER_REEXECUTE:
dd0ab174
LP
2009
2010 manager_send_reloading(m); /* From the perspective of the manager calling us this is
2011 * pretty much the same as a reload */
2012
7eb35049
LP
2013 r = prepare_reexecute(m, &arg_serialization, ret_fds, false);
2014 if (r < 0) {
2015 *ret_error_message = "Failed to prepare for reexecution";
2016 return r;
2017 }
2018
2019 log_notice("Reexecuting.");
2020
7eb35049 2021 *ret_retval = EXIT_SUCCESS;
7eb35049
LP
2022 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2023
5409c6fc 2024 return objective;
7eb35049
LP
2025
2026 case MANAGER_SWITCH_ROOT:
dd0ab174
LP
2027
2028 manager_send_reloading(m); /* From the perspective of the manager calling us this is
2029 * pretty much the same as a reload */
2030
d35fe8c0
FB
2031 manager_set_switching_root(m, true);
2032
7eb35049
LP
2033 if (!m->switch_root_init) {
2034 r = prepare_reexecute(m, &arg_serialization, ret_fds, true);
2035 if (r < 0) {
2036 *ret_error_message = "Failed to prepare for reexecution";
2037 return r;
2038 }
2039 } else
2040 *ret_fds = NULL;
2041
2042 log_notice("Switching root.");
2043
7eb35049 2044 *ret_retval = EXIT_SUCCESS;
7eb35049
LP
2045
2046 /* Steal the switch root parameters */
49052946
YW
2047 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
2048 *ret_switch_root_init = TAKE_PTR(m->switch_root_init);
7eb35049 2049
5409c6fc 2050 return objective;
7eb35049 2051
13ffc607
LP
2052 case MANAGER_SOFT_REBOOT:
2053 manager_send_reloading(m);
2054 manager_set_switching_root(m, true);
2055
2056 r = prepare_reexecute(m, &arg_serialization, ret_fds, /* switching_root= */ true);
2057 if (r < 0) {
2058 *ret_error_message = "Failed to prepare for reexecution";
2059 return r;
2060 }
2061
2062 log_notice("Soft-rebooting.");
2063
2064 *ret_retval = EXIT_SUCCESS;
2065 *ret_switch_root_dir = TAKE_PTR(m->switch_root);
2066 *ret_switch_root_init = NULL;
2067
2068 return objective;
2069
7eb35049 2070 case MANAGER_EXIT:
7eb35049
LP
2071 if (MANAGER_IS_USER(m)) {
2072 log_debug("Exit.");
2073
7eb35049 2074 *ret_retval = m->return_value;
7eb35049
LP
2075 *ret_fds = NULL;
2076 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2077
5409c6fc 2078 return objective;
7eb35049
LP
2079 }
2080
2081 _fallthrough_;
2082 case MANAGER_REBOOT:
2083 case MANAGER_POWEROFF:
2084 case MANAGER_HALT:
2085 case MANAGER_KEXEC: {
7eb35049
LP
2086 log_notice("Shutting down.");
2087
7eb35049 2088 *ret_retval = m->return_value;
7eb35049
LP
2089 *ret_fds = NULL;
2090 *ret_switch_root_dir = *ret_switch_root_init = NULL;
2091
5409c6fc 2092 return objective;
7eb35049
LP
2093 }
2094
2095 default:
04499a70 2096 assert_not_reached();
7eb35049
LP
2097 }
2098 }
2099}
2100
31aef7ff 2101static void log_execution_mode(bool *ret_first_boot) {
7cd43e34 2102 bool first_boot = false;
4870133b 2103 int r;
7cd43e34 2104
31aef7ff
LP
2105 assert(ret_first_boot);
2106
4870133b
LP
2107 switch (arg_runtime_scope) {
2108
2109 case RUNTIME_SCOPE_SYSTEM: {
40efaaed 2110 struct utsname uts;
31aef7ff
LP
2111 int v;
2112
e7b18106 2113 log_info("systemd " GIT_VERSION " running in %ssystem mode (%s)",
91b79ba8
ZJS
2114 arg_action == ACTION_TEST ? "test " : "",
2115 systemd_features);
31aef7ff
LP
2116
2117 v = detect_virtualization();
2118 if (v > 0)
2119 log_info("Detected virtualization %s.", virtualization_to_string(v));
2120
024469dd
DB
2121 v = detect_confidential_virtualization();
2122 if (v > 0)
2123 log_info("Detected confidential virtualization %s.", confidential_virtualization_to_string(v));
2124
31aef7ff
LP
2125 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2126
7cd43e34 2127 if (in_initrd())
55c041b4 2128 log_info("Running in initrd.");
7cd43e34 2129 else {
583cef3b
HS
2130 _cleanup_free_ char *id_text = NULL;
2131
7cd43e34
ZJS
2132 /* Let's check whether we are in first boot. First, check if an override was
2133 * specified on the kernel commandline. If yes, we honour that. */
2134
3787934b 2135 r = proc_cmdline_get_bool("systemd.condition-first-boot", /* flags = */ 0, &first_boot);
7cd43e34
ZJS
2136 if (r < 0)
2137 log_debug_errno(r, "Failed to parse systemd.condition-first-boot= kernel commandline argument, ignoring: %m");
2138
2139 if (r > 0)
2140 log_full(first_boot ? LOG_INFO : LOG_DEBUG,
2141 "Kernel commandline argument says we are %s first boot.",
2142 first_boot ? "in" : "not in");
2143 else {
2144 /* Second, perform autodetection. We use /etc/machine-id as flag file for
2145 * this: If it is missing or contains the value "uninitialized", this is the
2146 * first boot. In other cases, it is not. This allows container managers and
2147 * installers to provision a couple of files in /etc but still permit the
2148 * first-boot initialization to occur. If the container manager wants to
2149 * provision the machine ID it should pass $container_uuid to PID 1. */
2150
2151 r = read_one_line_file("/etc/machine-id", &id_text);
2152 if (r < 0 || streq(id_text, "uninitialized")) {
2153 if (r < 0 && r != -ENOENT)
2154 log_warning_errno(r, "Unexpected error while reading /etc/machine-id, ignoring: %m");
2155
2156 first_boot = true;
2157 log_info("Detected first boot.");
2158 } else
2159 log_debug("Detected initialized system, this is not the first boot.");
583cef3b 2160 }
31aef7ff 2161 }
40efaaed 2162
5180394b 2163 assert_se(uname(&uts) >= 0);
40efaaed
LP
2164
2165 if (strverscmp_improved(uts.release, KERNEL_BASELINE_VERSION) < 0)
2166 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2167 "Your mileage may vary.", uts.release, KERNEL_BASELINE_VERSION);
2168 else
2169 log_debug("Kernel version %s, our baseline is %s", uts.release, KERNEL_BASELINE_VERSION);
4870133b
LP
2170
2171 break;
2172 }
2173
2174 case RUNTIME_SCOPE_USER:
b9e90f3a 2175 if (DEBUG_LOGGING) {
c2b2df60 2176 _cleanup_free_ char *t = NULL;
31aef7ff 2177
b9e90f3a 2178 t = uid_to_name(getuid());
91b79ba8
ZJS
2179 log_debug("systemd " GIT_VERSION " running in %suser mode for user " UID_FMT "/%s. (%s)",
2180 arg_action == ACTION_TEST ? " test" : "",
2181 getuid(), strna(t), systemd_features);
b9e90f3a 2182 }
4870133b
LP
2183
2184 break;
2185
2186 default:
2187 assert_not_reached();
31aef7ff 2188 }
7cd43e34
ZJS
2189
2190 *ret_first_boot = first_boot;
31aef7ff
LP
2191}
2192
5afbaa36
LP
2193static int initialize_runtime(
2194 bool skip_setup,
3023f2fe 2195 bool first_boot,
5afbaa36
LP
2196 struct rlimit *saved_rlimit_nofile,
2197 struct rlimit *saved_rlimit_memlock,
2198 const char **ret_error_message) {
5afbaa36
LP
2199 int r;
2200
2201 assert(ret_error_message);
2202
2203 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2204 *
2205 * - Some only apply to --system instances
2206 * - Some only apply to --user instances
2207 * - Some only apply when we first start up, but not when we reexecute
2208 */
2209
2d776038
LP
2210 if (arg_action != ACTION_RUN)
2211 return 0;
2212
61fbbac1 2213 update_cpu_affinity(skip_setup);
b070c7c0 2214 update_numa_policy(skip_setup);
61fbbac1 2215
4870133b
LP
2216 switch (arg_runtime_scope) {
2217
2218 case RUNTIME_SCOPE_SYSTEM:
5238e957 2219 /* Make sure we leave a core dump without panicking the kernel. */
3c3c6cb9 2220 install_crash_handler();
5afbaa36 2221
3c3c6cb9 2222 if (!skip_setup) {
143fadf3 2223 r = mount_cgroup_controllers();
3c3c6cb9
LP
2224 if (r < 0) {
2225 *ret_error_message = "Failed to mount cgroup hierarchies";
2226 return r;
2227 }
2228
deb0d489
LP
2229 /* Pull credentials from various sources into a common credential directory (we do
2230 * this here, before setting up the machine ID, so that we can use credential info
2231 * for setting up the machine ID) */
2232 (void) import_credentials();
2233
4bd03515 2234 (void) os_release_status();
b6fad306 2235 (void) hostname_setup(true);
3023f2fe 2236 /* Force transient machine-id on first boot. */
deb0d489 2237 machine_id_setup(/* root= */ NULL, /* force_transient= */ first_boot, arg_machine_id, /* ret_machine_id */ NULL);
df883de9 2238 (void) loopback_setup();
3c3c6cb9 2239 bump_unix_max_dgram_qlen();
a8b627aa 2240 bump_file_max_and_nr_open();
3c3c6cb9
LP
2241 test_usr();
2242 write_container_id();
3f37a825
LB
2243
2244 /* Copy os-release to the propagate directory, so that we update it for services running
2245 * under RootDirectory=/RootImage= when we do a soft reboot. */
2246 r = setup_os_release(RUNTIME_SCOPE_SYSTEM);
2247 if (r < 0)
2248 log_warning_errno(r, "Failed to copy os-release for propagation, ignoring: %m");
3c3c6cb9 2249 }
8a2c1fbf 2250
82d7a151
YW
2251 r = watchdog_set_device(arg_watchdog_device);
2252 if (r < 0)
2253 log_warning_errno(r, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device);
4870133b
LP
2254
2255 break;
2256
2257 case RUNTIME_SCOPE_USER: {
32429805
LP
2258 _cleanup_free_ char *p = NULL;
2259
2260 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2261 * user mode. In system mode mount_setup() already did that. */
2262
2263 r = xdg_user_runtime_dir(&p, "/systemd");
2264 if (r < 0) {
2265 *ret_error_message = "$XDG_RUNTIME_DIR is not set";
ad5db940
OJ
2266 return log_struct_errno(LOG_EMERG, r,
2267 LOG_MESSAGE("Failed to determine $XDG_RUNTIME_DIR path: %m"),
2268 "MESSAGE_ID=" SD_MESSAGE_CORE_NO_XDGDIR_PATH_STR);
32429805
LP
2269 }
2270
e813a74a 2271 (void) mkdir_p_label(p, 0755);
32429805 2272 (void) make_inaccessible_nodes(p, UID_INVALID, GID_INVALID);
3f37a825
LB
2273 r = setup_os_release(RUNTIME_SCOPE_USER);
2274 if (r < 0)
2275 log_warning_errno(r, "Failed to copy os-release for propagation, ignoring: %m");
4870133b
LP
2276 break;
2277 }
2278
2279 default:
2280 assert_not_reached();
3c3c6cb9 2281 }
5afbaa36
LP
2282
2283 if (arg_timer_slack_nsec != NSEC_INFINITY)
2284 if (prctl(PR_SET_TIMERSLACK, arg_timer_slack_nsec) < 0)
3a671cd1 2285 log_warning_errno(errno, "Failed to adjust timer slack, ignoring: %m");
5afbaa36 2286
4870133b 2287 if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM) {
5afbaa36 2288
4870133b
LP
2289 if (!cap_test_all(arg_capability_bounding_set)) {
2290 r = capability_bounding_set_drop_usermode(arg_capability_bounding_set);
2291 if (r < 0) {
2292 *ret_error_message = "Failed to drop capability bounding set of usermode helpers";
ad5db940
OJ
2293 return log_struct_errno(LOG_EMERG, r,
2294 LOG_MESSAGE("Failed to drop capability bounding set of usermode helpers: %m"),
2295 "MESSAGE_ID=" SD_MESSAGE_CORE_CAPABILITY_BOUNDING_USER_STR);
4870133b
LP
2296 }
2297
2298 r = capability_bounding_set_drop(arg_capability_bounding_set, true);
2299 if (r < 0) {
2300 *ret_error_message = "Failed to drop capability bounding set";
ad5db940
OJ
2301 return log_struct_errno(LOG_EMERG, r,
2302 LOG_MESSAGE("Failed to drop capability bounding set: %m"),
2303 "MESSAGE_ID=" SD_MESSAGE_CORE_CAPABILITY_BOUNDING_STR);
4870133b 2304 }
5afbaa36 2305 }
5afbaa36 2306
4870133b
LP
2307 if (arg_no_new_privs) {
2308 if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
2309 *ret_error_message = "Failed to disable new privileges";
ad5db940
OJ
2310 return log_struct_errno(LOG_EMERG, errno,
2311 LOG_MESSAGE("Failed to disable new privileges: %m"),
2312 "MESSAGE_ID=" SD_MESSAGE_CORE_DISABLE_PRIVILEGES_STR);
4870133b 2313 }
39362f6f
JB
2314 }
2315 }
2316
5afbaa36
LP
2317 if (arg_syscall_archs) {
2318 r = enforce_syscall_archs(arg_syscall_archs);
2319 if (r < 0) {
2320 *ret_error_message = "Failed to set syscall architectures";
2321 return r;
2322 }
2323 }
2324
8c3fe1b5
LP
2325 r = make_reaper_process(true);
2326 if (r < 0)
2327 log_warning_errno(r, "Failed to make us a subreaper, ignoring: %m");
5afbaa36 2328
a17c1712
LP
2329 /* Bump up RLIMIT_NOFILE for systemd itself */
2330 (void) bump_rlimit_nofile(saved_rlimit_nofile);
2331 (void) bump_rlimit_memlock(saved_rlimit_memlock);
5afbaa36
LP
2332
2333 return 0;
2334}
2335
6acca5fc
LP
2336static int do_queue_default_job(
2337 Manager *m,
2338 const char **ret_error_message) {
2339
2340 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
f1d075dc
ZJS
2341 const char *unit;
2342 Job *job;
2343 Unit *target;
6acca5fc
LP
2344 int r;
2345
8755dbad 2346 if (arg_default_unit)
f1d075dc 2347 unit = arg_default_unit;
8755dbad 2348 else if (in_initrd())
f1d075dc 2349 unit = SPECIAL_INITRD_TARGET;
8755dbad 2350 else
f1d075dc 2351 unit = SPECIAL_DEFAULT_TARGET;
8755dbad 2352
f1d075dc 2353 log_debug("Activating default unit: %s", unit);
8755dbad 2354
f1d075dc 2355 r = manager_load_startable_unit_or_warn(m, unit, NULL, &target);
8755dbad
ZJS
2356 if (r < 0 && in_initrd() && !arg_default_unit) {
2357 /* Fall back to default.target, which we used to always use by default. Only do this if no
2358 * explicit configuration was given. */
2359
2360 log_info("Falling back to " SPECIAL_DEFAULT_TARGET ".");
6acca5fc 2361
8755dbad
ZJS
2362 r = manager_load_startable_unit_or_warn(m, SPECIAL_DEFAULT_TARGET, NULL, &target);
2363 }
4109ede7 2364 if (r < 0) {
8755dbad 2365 log_info("Falling back to " SPECIAL_RESCUE_TARGET ".");
6acca5fc 2366
4109ede7 2367 r = manager_load_startable_unit_or_warn(m, SPECIAL_RESCUE_TARGET, NULL, &target);
6acca5fc 2368 if (r < 0) {
8755dbad
ZJS
2369 *ret_error_message = r == -ERFKILL ? SPECIAL_RESCUE_TARGET " masked"
2370 : "Failed to load " SPECIAL_RESCUE_TARGET;
4109ede7 2371 return r;
6acca5fc
LP
2372 }
2373 }
2374
2375 assert(target->load_state == UNIT_LOADED);
2376
f1d075dc 2377 r = manager_add_job(m, JOB_START, target, JOB_ISOLATE, NULL, &error, &job);
6acca5fc
LP
2378 if (r == -EPERM) {
2379 log_debug_errno(r, "Default target could not be isolated, starting instead: %s", bus_error_message(&error, r));
2380
2381 sd_bus_error_free(&error);
2382
f1d075dc 2383 r = manager_add_job(m, JOB_START, target, JOB_REPLACE, NULL, &error, &job);
6acca5fc
LP
2384 if (r < 0) {
2385 *ret_error_message = "Failed to start default target";
ad5db940
OJ
2386 return log_struct_errno(LOG_EMERG, r,
2387 LOG_MESSAGE("Failed to start default target: %s", bus_error_message(&error, r)),
2388 "MESSAGE_ID=" SD_MESSAGE_CORE_START_TARGET_FAILED_STR);
6acca5fc
LP
2389 }
2390
2391 } else if (r < 0) {
2392 *ret_error_message = "Failed to isolate default target";
ad5db940
OJ
2393 return log_struct_errno(LOG_EMERG, r,
2394 LOG_MESSAGE("Failed to isolate default target: %s", bus_error_message(&error, r)),
2395 "MESSAGE_ID=" SD_MESSAGE_CORE_ISOLATE_TARGET_FAILED_STR);
c86c31d9
ZJS
2396 } else
2397 log_info("Queued %s job for default target %s.",
2398 job_type_to_string(job->type),
04d232d8 2399 unit_status_string(job->unit, NULL));
6acca5fc 2400
f1d075dc 2401 m->default_unit_job_id = job->id;
6acca5fc
LP
2402
2403 return 0;
2404}
2405
a9fd4cd1
FB
2406static void save_rlimits(struct rlimit *saved_rlimit_nofile,
2407 struct rlimit *saved_rlimit_memlock) {
2408
2409 assert(saved_rlimit_nofile);
2410 assert(saved_rlimit_memlock);
2411
2412 if (getrlimit(RLIMIT_NOFILE, saved_rlimit_nofile) < 0)
2413 log_warning_errno(errno, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2414
2415 if (getrlimit(RLIMIT_MEMLOCK, saved_rlimit_memlock) < 0)
2416 log_warning_errno(errno, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2417}
2418
2419static void fallback_rlimit_nofile(const struct rlimit *saved_rlimit_nofile) {
2420 struct rlimit *rl;
2421
c9e120e0 2422 if (arg_defaults.rlimit[RLIMIT_NOFILE])
a9fd4cd1
FB
2423 return;
2424
2425 /* Make sure forked processes get limits based on the original kernel setting */
2426
2427 rl = newdup(struct rlimit, saved_rlimit_nofile, 1);
2428 if (!rl) {
2429 log_oom();
2430 return;
2431 }
2432
2433 /* Bump the hard limit for system services to a substantially higher value. The default
2434 * hard limit current kernels set is pretty low (4K), mostly for historical
2435 * reasons. According to kernel developers, the fd handling in recent kernels has been
2436 * optimized substantially enough, so that we can bump the limit now, without paying too
2437 * high a price in memory or performance. Note however that we only bump the hard limit,
2438 * not the soft limit. That's because select() works the way it works, and chokes on fds
2439 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2440 * unexpecting programs that they get fds higher than what they can process using
2441 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2442 * this pitfall: programs that are written by folks aware of the select() problem in mind
2443 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2444 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2445 * we pass. */
4870133b 2446 if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM) {
a9fd4cd1
FB
2447 int nr;
2448
2449 /* Get the underlying absolute limit the kernel enforces */
2450 nr = read_nr_open();
2451
2452 rl->rlim_max = MIN((rlim_t) nr, MAX(rl->rlim_max, (rlim_t) HIGH_RLIMIT_NOFILE));
2453 }
2454
2455 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2456 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2457 * instance), then lower what we pass on to not confuse our children */
2458 rl->rlim_cur = MIN(rl->rlim_cur, (rlim_t) FD_SETSIZE);
2459
c9e120e0 2460 arg_defaults.rlimit[RLIMIT_NOFILE] = rl;
a9fd4cd1
FB
2461}
2462
2463static void fallback_rlimit_memlock(const struct rlimit *saved_rlimit_memlock) {
2464 struct rlimit *rl;
2465
2466 /* Pass the original value down to invoked processes */
2467
c9e120e0 2468 if (arg_defaults.rlimit[RLIMIT_MEMLOCK])
a9fd4cd1
FB
2469 return;
2470
2471 rl = newdup(struct rlimit, saved_rlimit_memlock, 1);
2472 if (!rl) {
2473 log_oom();
2474 return;
2475 }
2476
4870133b 2477 if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM) {
852b6250
LP
2478 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2479 * default for this since kernel 5.16) */
2480 rl->rlim_max = MAX(rl->rlim_max, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
2481 rl->rlim_cur = MAX(rl->rlim_cur, (rlim_t) DEFAULT_RLIMIT_MEMLOCK);
2482 }
2483
c9e120e0 2484 arg_defaults.rlimit[RLIMIT_MEMLOCK] = rl;
a9fd4cd1
FB
2485}
2486
d55ed7de 2487static void setenv_manager_environment(void) {
d55ed7de
ZJS
2488 int r;
2489
2490 STRV_FOREACH(p, arg_manager_environment) {
2491 log_debug("Setting '%s' in our own environment.", *p);
2492
2493 r = putenv_dup(*p, true);
2494 if (r < 0)
2495 log_warning_errno(errno, "Failed to setenv \"%s\", ignoring: %m", *p);
2496 }
2497}
2498
fb39af4c
ZJS
2499static void reset_arguments(void) {
2500 /* Frees/resets arg_* variables, with a few exceptions commented below. */
970777b5
LP
2501
2502 arg_default_unit = mfree(arg_default_unit);
fb39af4c 2503
4870133b 2504 /* arg_runtime_scope — ignore */
fb39af4c
ZJS
2505
2506 arg_dump_core = true;
2507 arg_crash_chvt = -1;
2508 arg_crash_shell = false;
2509 arg_crash_reboot = false;
970777b5 2510 arg_confirm_spawn = mfree(arg_confirm_spawn);
fb39af4c 2511 arg_show_status = _SHOW_STATUS_INVALID;
36cf4507 2512 arg_status_unit_format = STATUS_UNIT_FORMAT_DEFAULT;
fb39af4c
ZJS
2513 arg_switched_root = false;
2514 arg_pager_flags = 0;
2515 arg_service_watchdogs = true;
c9e120e0
LP
2516
2517 unit_defaults_done(&arg_defaults);
ea09a416 2518 unit_defaults_init(&arg_defaults, arg_runtime_scope);
c9e120e0 2519
fb39af4c 2520 arg_runtime_watchdog = 0;
65224c1d 2521 arg_reboot_watchdog = 10 * USEC_PER_MINUTE;
acafd7d8 2522 arg_kexec_watchdog = 0;
5717062e 2523 arg_pretimeout_watchdog = 0;
919ea64f
ŁS
2524 arg_early_core_pattern = mfree(arg_early_core_pattern);
2525 arg_watchdog_device = mfree(arg_watchdog_device);
aff3a9e1 2526 arg_watchdog_pretimeout_governor = mfree(arg_watchdog_pretimeout_governor);
fb39af4c 2527
970777b5 2528 arg_default_environment = strv_free(arg_default_environment);
d55ed7de 2529 arg_manager_environment = strv_free(arg_manager_environment);
fb39af4c 2530
3fd5190b 2531 arg_capability_bounding_set = CAP_MASK_UNSET;
fb39af4c
ZJS
2532 arg_no_new_privs = false;
2533 arg_timer_slack_nsec = NSEC_INFINITY;
fb39af4c 2534
970777b5 2535 arg_syscall_archs = set_free(arg_syscall_archs);
61fbbac1 2536
fb39af4c
ZJS
2537 /* arg_serialization — ignore */
2538
fb39af4c
ZJS
2539 arg_machine_id = (sd_id128_t) {};
2540 arg_cad_burst_action = EMERGENCY_ACTION_REBOOT_FORCE;
fb39af4c 2541
61fbbac1 2542 cpu_set_reset(&arg_cpu_affinity);
b070c7c0 2543 numa_policy_reset(&arg_numa_policy);
d247f232
LP
2544
2545 arg_random_seed = mfree(arg_random_seed);
2546 arg_random_seed_size = 0;
33d943d1 2547 arg_clock_usec = 0;
d4a402e4 2548
856bfaeb
LB
2549 arg_reload_limit_interval_sec = 0;
2550 arg_reload_limit_burst = 0;
d4a402e4
LP
2551}
2552
2553static void determine_default_oom_score_adjust(void) {
2554 int r, a, b;
2555
2556 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2557 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2558 * user). */
2559
c9e120e0 2560 if (arg_defaults.oom_score_adjust_set)
d4a402e4
LP
2561 return;
2562
2563 if (getuid() == 0)
2564 return;
2565
2566 r = get_oom_score_adjust(&a);
2567 if (r < 0)
2568 return (void) log_warning_errno(r, "Failed to determine current OOM score adjustment value, ignoring: %m");
2569
2570 assert_cc(100 <= OOM_SCORE_ADJ_MAX);
2571 b = a >= OOM_SCORE_ADJ_MAX - 100 ? OOM_SCORE_ADJ_MAX : a + 100;
2572
2573 if (a == b)
2574 return;
2575
c9e120e0
LP
2576 arg_defaults.oom_score_adjust = b;
2577 arg_defaults.oom_score_adjust_set = true;
970777b5
LP
2578}
2579
a9fd4cd1
FB
2580static int parse_configuration(const struct rlimit *saved_rlimit_nofile,
2581 const struct rlimit *saved_rlimit_memlock) {
97d1fb94
LP
2582 int r;
2583
a9fd4cd1
FB
2584 assert(saved_rlimit_nofile);
2585 assert(saved_rlimit_memlock);
2586
fb39af4c
ZJS
2587 /* Assign configuration defaults */
2588 reset_arguments();
2589
97d1fb94 2590 r = parse_config_file();
470a5e6d
ZJS
2591 if (r < 0)
2592 log_warning_errno(r, "Failed to parse config file, ignoring: %m");
97d1fb94 2593
4870133b 2594 if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM) {
97d1fb94
LP
2595 r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0);
2596 if (r < 0)
2597 log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m");
2598 }
2599
a9fd4cd1
FB
2600 /* Initialize some default rlimits for services if they haven't been configured */
2601 fallback_rlimit_nofile(saved_rlimit_nofile);
2602 fallback_rlimit_memlock(saved_rlimit_memlock);
2603
97d1fb94
LP
2604 /* Note that this also parses bits from the kernel command line, including "debug". */
2605 log_parse_environment();
2606
db33214b 2607 /* Initialize the show status setting if it hasn't been set explicitly yet */
7a293242 2608 if (arg_show_status == _SHOW_STATUS_INVALID)
db33214b
LP
2609 arg_show_status = SHOW_STATUS_YES;
2610
d4a402e4
LP
2611 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2612 determine_default_oom_score_adjust();
2613
d55ed7de
ZJS
2614 /* Push variables into the manager environment block */
2615 setenv_manager_environment();
2616
a4303b40
DDM
2617 /* Parse log environment variables again to take into account any new environment variables. */
2618 log_parse_environment();
2619
97d1fb94
LP
2620 return 0;
2621}
2622
b0d7c989
LP
2623static int safety_checks(void) {
2624
febf46a4 2625 if (getpid_cached() == 1 &&
baaa35ad
ZJS
2626 arg_action != ACTION_RUN)
2627 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2628 "Unsupported execution mode while PID 1.");
febf46a4
LP
2629
2630 if (getpid_cached() == 1 &&
4870133b 2631 arg_runtime_scope == RUNTIME_SCOPE_USER)
baaa35ad
ZJS
2632 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2633 "Can't run --user mode as PID 1.");
febf46a4
LP
2634
2635 if (arg_action == ACTION_RUN &&
4870133b 2636 arg_runtime_scope == RUNTIME_SCOPE_SYSTEM &&
baaa35ad
ZJS
2637 getpid_cached() != 1)
2638 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2639 "Can't run system mode unless PID 1.");
febf46a4 2640
b0d7c989 2641 if (arg_action == ACTION_TEST &&
baaa35ad
ZJS
2642 geteuid() == 0)
2643 return log_error_errno(SYNTHETIC_ERRNO(EPERM),
2644 "Don't run test mode as root.");
b0d7c989 2645
4870133b
LP
2646 switch (arg_runtime_scope) {
2647
2648 case RUNTIME_SCOPE_USER:
2649
2650 if (arg_action == ACTION_RUN &&
2651 sd_booted() <= 0)
2652 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2653 "Trying to run as user instance, but the system has not been booted with systemd.");
2654
2655 if (arg_action == ACTION_RUN &&
2656 !getenv("XDG_RUNTIME_DIR"))
2657 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH),
2658 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2659
2660 break;
b0d7c989 2661
4870133b
LP
2662 case RUNTIME_SCOPE_SYSTEM:
2663 if (arg_action == ACTION_RUN &&
2664 running_in_chroot() > 0)
2665 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2666 "Cannot be run in a chroot() environment.");
2667 break;
b0d7c989 2668
4870133b
LP
2669 default:
2670 assert_not_reached();
2671 }
b0d7c989
LP
2672
2673 return 0;
2674}
2675
74da609f
LP
2676static int initialize_security(
2677 bool *loaded_policy,
2678 dual_timestamp *security_start_timestamp,
2679 dual_timestamp *security_finish_timestamp,
2680 const char **ret_error_message) {
2681
2682 int r;
2683
2684 assert(loaded_policy);
2685 assert(security_start_timestamp);
2686 assert(security_finish_timestamp);
2687 assert(ret_error_message);
2688
2689 dual_timestamp_get(security_start_timestamp);
2690
97149f40 2691 r = mac_selinux_setup(loaded_policy);
74da609f
LP
2692 if (r < 0) {
2693 *ret_error_message = "Failed to load SELinux policy";
2694 return r;
2695 }
2696
2697 r = mac_smack_setup(loaded_policy);
2698 if (r < 0) {
2699 *ret_error_message = "Failed to load SMACK policy";
2700 return r;
2701 }
2702
2ffadd3c
Y
2703 r = mac_apparmor_setup();
2704 if (r < 0) {
2705 *ret_error_message = "Failed to load AppArmor policy";
2706 return r;
2707 }
2708
74da609f
LP
2709 r = ima_setup();
2710 if (r < 0) {
2711 *ret_error_message = "Failed to load IMA policy";
2712 return r;
2713 }
2714
2715 dual_timestamp_get(security_finish_timestamp);
2716 return 0;
2717}
2718
efeb853f
LP
2719static int collect_fds(FDSet **ret_fds, const char **ret_error_message) {
2720 int r;
2721
2722 assert(ret_fds);
2723 assert(ret_error_message);
2724
a3dff21a
LP
2725 /* Pick up all fds passed to us. We apply a filter here: we only take the fds that have O_CLOEXEC
2726 * off. All fds passed via execve() to us must have O_CLOEXEC off, and our own code and dependencies
2727 * should be clean enough to set O_CLOEXEC universally. Thus checking the bit should be a safe
2728 * mechanism to distinguish passed in fds from our own.
2729 *
2730 * Why bother? Some subsystems we initialize early, specifically selinux might keep fds open in our
2731 * process behind our back. We should not take possession of that (and then accidentally close
2732 * it). SELinux thankfully sets O_CLOEXEC on its fds, so this test should work. */
2733 r = fdset_new_fill(/* filter_cloexec= */ 0, ret_fds);
efeb853f
LP
2734 if (r < 0) {
2735 *ret_error_message = "Failed to allocate fd set";
ad5db940
OJ
2736 return log_struct_errno(LOG_EMERG, r,
2737 LOG_MESSAGE("Failed to allocate fd set: %m"),
2738 "MESSAGE_ID=" SD_MESSAGE_CORE_FD_SET_FAILED_STR);
efeb853f
LP
2739 }
2740
a3dff21a 2741 (void) fdset_cloexec(*ret_fds, true);
efeb853f 2742
a3dff21a
LP
2743 /* The serialization fd should have O_CLOEXEC turned on already, let's verify that we didn't pick it up here */
2744 assert_se(!arg_serialization || !fdset_contains(*ret_fds, fileno(arg_serialization)));
efeb853f
LP
2745
2746 return 0;
2747}
2748
2e51b31c
LP
2749static void setup_console_terminal(bool skip_setup) {
2750
4870133b 2751 if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
2e51b31c
LP
2752 return;
2753
2754 /* Become a session leader if we aren't one yet. */
2755 (void) setsid();
2756
ff3a7019
ZJS
2757 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2758 * controlling tty. */
2e51b31c
LP
2759 (void) release_terminal();
2760
2761 /* Reset the console, but only if this is really init and we are freshly booted */
2762 if (getpid_cached() == 1 && !skip_setup)
2763 (void) console_setup();
2764}
2765
aa40ff07
LP
2766static bool early_skip_setup_check(int argc, char *argv[]) {
2767 bool found_deserialize = false;
aa40ff07 2768
ff3a7019
ZJS
2769 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2770 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2771 * special setup things anyway, even if in that case we also do deserialization. */
aa40ff07 2772
431733b8 2773 for (int i = 1; i < argc; i++)
aa40ff07
LP
2774 if (streq(argv[i], "--switched-root"))
2775 return false; /* If we switched root, don't skip the setup. */
09567df7 2776 else if (startswith(argv[i], "--deserialize=") || streq(argv[i], "--deserialize"))
aa40ff07 2777 found_deserialize = true;
aa40ff07
LP
2778
2779 return found_deserialize; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2780}
2781
0e06a031
LP
2782static int save_env(void) {
2783 char **l;
2784
2785 l = strv_copy(environ);
2786 if (!l)
2787 return -ENOMEM;
2788
2789 strv_free_and_replace(saved_env, l);
2790 return 0;
2791}
2792
60918275 2793int main(int argc, char *argv[]) {
5409c6fc
ZJS
2794 dual_timestamp
2795 initrd_timestamp = DUAL_TIMESTAMP_NULL,
2796 userspace_timestamp = DUAL_TIMESTAMP_NULL,
2797 kernel_timestamp = DUAL_TIMESTAMP_NULL,
2798 security_start_timestamp = DUAL_TIMESTAMP_NULL,
2799 security_finish_timestamp = DUAL_TIMESTAMP_NULL;
ddfa8b0b
LP
2800 struct rlimit saved_rlimit_nofile = RLIMIT_MAKE_CONST(0),
2801 saved_rlimit_memlock = RLIMIT_MAKE_CONST(RLIM_INFINITY); /* The original rlimits we passed
2802 * in. Note we use different values
2803 * for the two that indicate whether
2804 * these fields are initialized! */
5409c6fc 2805 bool skip_setup, loaded_policy = false, queue_default_job = false, first_boot = false;
625e8690 2806 char *switch_root_dir = NULL, *switch_root_init = NULL;
9d76d730 2807 usec_t before_startup, after_startup;
625e8690 2808 static char systemd[] = "systemd";
b22d392d 2809 const char *error_message = NULL;
625e8690
LP
2810 int r, retval = EXIT_FAILURE;
2811 Manager *m = NULL;
a16e1123 2812 FDSet *fds = NULL;
27b14a22 2813
61b9769b 2814 assert_se(argc > 0 && !isempty(argv[0]));
cf3095ac 2815
d72a8f10 2816 /* SysV compatibility: redirect init → telinit */
6808a0bc 2817 redirect_telinit(argc, argv);
2cb1a60d 2818
d72a8f10 2819 /* Take timestamps early on */
c3a170f3
HH
2820 dual_timestamp_from_monotonic(&kernel_timestamp, 0);
2821 dual_timestamp_get(&userspace_timestamp);
2822
d72a8f10 2823 /* Figure out whether we need to do initialize the system, or if we already did that because we are
ff3a7019 2824 * reexecuting. */
aa40ff07 2825 skip_setup = early_skip_setup_check(argc, argv);
d03bc1b8 2826
ff3a7019
ZJS
2827 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2828 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2829 * right-away. */
f3b6a3ed 2830 program_invocation_short_name = systemd;
eee8b7ab 2831 (void) prctl(PR_SET_NAME, systemd);
5d6b1584 2832
d72a8f10 2833 /* Save the original command line */
36fea155 2834 save_argc_argv(argc, argv);
f3b6a3ed 2835
0e06a031
LP
2836 /* Save the original environment as we might need to restore it if we're requested to execute another
2837 * system manager later. */
2838 r = save_env();
2839 if (r < 0) {
2840 error_message = "Failed to copy environment block";
2841 goto finish;
2842 }
a5cede8c 2843
6fdb8de4 2844 /* Make sure that if the user says "syslog" we actually log to the journal. */
c1dc6153 2845 log_set_upgrade_syslog_to_journal(true);
bbe63281 2846
df0ff127 2847 if (getpid_cached() == 1) {
b5752d23 2848 /* When we run as PID 1 force system mode */
4870133b 2849 arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
b5752d23 2850
48a601fe 2851 /* Disable the umask logic */
90dc8c2e
MG
2852 umask(0);
2853
ff3a7019
ZJS
2854 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2855 * not be activated yet (even though the log socket for it exists). */
d075092f
LP
2856 log_set_prohibit_ipc(true);
2857
ff3a7019
ZJS
2858 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
2859 * is important so that we never end up logging to any foreign stderr, for example if we have
2860 * to log in a child process right before execve()'ing the actual binary, at a point in time
2861 * where socket activation stderr/stdout area already set up. */
48a601fe 2862 log_set_always_reopen_console(true);
48a601fe 2863
92890452 2864 if (detect_container() <= 0) {
4f8d551f 2865
92890452 2866 /* Running outside of a container as PID 1 */
1e344c1d 2867 log_set_target_and_open(LOG_TARGET_KMSG);
a866073d 2868
92890452
LP
2869 if (in_initrd())
2870 initrd_timestamp = userspace_timestamp;
c3ba6250 2871
92890452
LP
2872 if (!skip_setup) {
2873 r = mount_setup_early();
2874 if (r < 0) {
2875 error_message = "Failed to mount early API filesystems";
2876 goto finish;
2877 }
d2f57745
DDM
2878 }
2879
2880 /* We might have just mounted /proc, so let's try to parse the kernel
2881 * command line log arguments immediately. */
2882 log_parse_environment();
92890452 2883
d2f57745
DDM
2884 /* Let's open the log backend a second time, in case the first time didn't
2885 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
2886 * available, and it previously wasn't. */
2887 log_open();
0a2eef1e 2888
d2f57745 2889 if (!skip_setup) {
6123dfaa
ZJS
2890 disable_printk_ratelimit();
2891
92890452
LP
2892 r = initialize_security(
2893 &loaded_policy,
2894 &security_start_timestamp,
2895 &security_finish_timestamp,
2896 &error_message);
2897 if (r < 0)
2898 goto finish;
d723cd65 2899 }
eee8b7ab 2900
a452c807
DDM
2901 if (mac_init() < 0) {
2902 error_message = "Failed to initialize MAC support";
96694e99 2903 goto finish;
92890452 2904 }
0b3325e7 2905
92890452
LP
2906 if (!skip_setup)
2907 initialize_clock();
2908
ff3a7019
ZJS
2909 /* Set the default for later on, but don't actually open the logs like this for
2910 * now. Note that if we are transitioning from the initrd there might still be
2911 * journal fd open, and we shouldn't attempt opening that before we parsed
2912 * /proc/cmdline which might redirect output elsewhere. */
92890452
LP
2913 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG);
2914
2915 } else {
2916 /* Running inside a container, as PID 1 */
1e344c1d 2917 log_set_target_and_open(LOG_TARGET_CONSOLE);
92890452
LP
2918
2919 /* For later on, see above... */
2920 log_set_target(LOG_TARGET_JOURNAL);
2921
45250e66 2922 /* clear the kernel timestamp, because we are in a container */
92890452 2923 kernel_timestamp = DUAL_TIMESTAMP_NULL;
cb6531be 2924 }
7948c4df 2925
92890452 2926 initialize_coredump(skip_setup);
a866073d 2927
92890452
LP
2928 r = fixup_environment();
2929 if (r < 0) {
ad5db940
OJ
2930 log_struct_errno(LOG_EMERG, r,
2931 LOG_MESSAGE("Failed to fix up PID 1 environment: %m"),
2932 "MESSAGE_ID=" SD_MESSAGE_CORE_PID1_ENVIRONMENT_STR);
92890452
LP
2933 error_message = "Failed to fix up PID1 environment";
2934 goto finish;
2935 }
a866073d 2936
ff3a7019
ZJS
2937 /* Try to figure out if we can use colors with the console. No need to do that for user
2938 * instances since they never log into the console. */
3a18b604 2939 log_show_color(colors_enabled());
92890452 2940
c76cf844
AK
2941 r = make_null_stdio();
2942 if (r < 0)
92890452 2943 log_warning_errno(r, "Failed to redirect standard streams to /dev/null, ignoring: %m");
f84f9974 2944
a132bef0 2945 /* Load the kernel modules early. */
2e75e2a8 2946 if (!skip_setup)
e921a00d 2947 (void) kmod_setup();
2e75e2a8 2948
3196e423 2949 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
f74349d8 2950 r = mount_setup(loaded_policy, skip_setup);
cb6531be
ZJS
2951 if (r < 0) {
2952 error_message = "Failed to mount API filesystems";
8efe3c01 2953 goto finish;
cb6531be 2954 }
c18ecf03 2955
0be72218
JD
2956 /* The efivarfs is now mounted, let's lock down the system token. */
2957 lock_down_efi_variables();
209b2592
FB
2958
2959 /* Cache command-line options passed from EFI variables */
2960 if (!skip_setup)
2961 (void) cache_efi_options_variable();
3196e423
LP
2962 } else {
2963 /* Running as user instance */
4870133b 2964 arg_runtime_scope = RUNTIME_SCOPE_USER;
2a646b1d 2965 log_set_always_reopen_console(true);
1e344c1d 2966 log_set_target_and_open(LOG_TARGET_AUTO);
3196e423
LP
2967
2968 /* clear the kernel timestamp, because we are not PID 1 */
2969 kernel_timestamp = DUAL_TIMESTAMP_NULL;
2970
963b6b90
ŁS
2971 /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
2972 * not affect the permitted and effective sets which are important for the manager itself to
2973 * operate. */
2974 capability_ambient_set_apply(0, /* also_inherit= */ false);
2975
a452c807
DDM
2976 if (mac_init() < 0) {
2977 error_message = "Failed to initialize MAC support";
3196e423
LP
2978 goto finish;
2979 }
0c85a4f3 2980 }
4ade7963 2981
a9fd4cd1
FB
2982 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
2983 * transitioning from the initrd to the main systemd or suchlike. */
2984 save_rlimits(&saved_rlimit_nofile, &saved_rlimit_memlock);
2985
4ade7963 2986 /* Reset all signal handlers. */
ce30c8dc 2987 (void) reset_all_signal_handlers();
9c274488 2988 (void) ignore_signals(SIGNALS_IGNORE);
078e4539 2989
ffe5c01e
FB
2990 (void) parse_configuration(&saved_rlimit_nofile, &saved_rlimit_memlock);
2991
2992 r = parse_argv(argc, argv);
2993 if (r < 0) {
2994 error_message = "Failed to parse commandline arguments";
f170852a 2995 goto finish;
ffe5c01e 2996 }
10c961b9 2997
b0d7c989
LP
2998 r = safety_checks();
2999 if (r < 0)
fe783b03 3000 goto finish;
fe783b03 3001
5c08257b 3002 if (IN_SET(arg_action, ACTION_TEST, ACTION_HELP, ACTION_DUMP_CONFIGURATION_ITEMS, ACTION_DUMP_BUS_PROPERTIES, ACTION_BUS_INTROSPECT))
384c2c32 3003 pager_open(arg_pager_flags);
b0d7c989
LP
3004
3005 if (arg_action != ACTION_RUN)
74e7579c 3006 skip_setup = true;
b87c2aa6 3007
fa0f4d8a 3008 if (arg_action == ACTION_HELP) {
37ec0fdd 3009 retval = help() < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
f170852a 3010 goto finish;
9ba0bc4e
ZJS
3011 } else if (arg_action == ACTION_VERSION) {
3012 retval = version();
3013 goto finish;
fa0f4d8a 3014 } else if (arg_action == ACTION_DUMP_CONFIGURATION_ITEMS) {
e537352b 3015 unit_dump_config_items(stdout);
22f4096c 3016 retval = EXIT_SUCCESS;
e537352b 3017 goto finish;
bbc1acab
YW
3018 } else if (arg_action == ACTION_DUMP_BUS_PROPERTIES) {
3019 dump_bus_properties(stdout);
3020 retval = EXIT_SUCCESS;
3021 goto finish;
5c08257b
ZJS
3022 } else if (arg_action == ACTION_BUS_INTROSPECT) {
3023 r = bus_manager_introspect_implementations(stdout, arg_bus_introspect);
3024 retval = r >= 0 ? EXIT_SUCCESS : EXIT_FAILURE;
3025 goto finish;
f170852a
LP
3026 }
3027
4c701096 3028 assert_se(IN_SET(arg_action, ACTION_RUN, ACTION_TEST));
f170852a 3029
5a2e0c62
LP
3030 /* Move out of the way, so that we won't block unmounts */
3031 assert_se(chdir("/") == 0);
3032
dea374e8 3033 if (arg_action == ACTION_RUN) {
d247f232
LP
3034 if (!skip_setup) {
3035 /* Apply the systemd.clock_usec= kernel command line switch */
45250e66 3036 apply_clock_update();
a70c72a0 3037
d247f232
LP
3038 /* Apply random seed from kernel command line */
3039 cmdline_take_random_seed();
3040 }
3041
c6885f5f
FB
3042 /* A core pattern might have been specified via the cmdline. */
3043 initialize_core_pattern(skip_setup);
3044
efeb853f 3045 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
a70c72a0
LP
3046 log_close();
3047
3048 /* Remember open file descriptors for later deserialization */
efeb853f
LP
3049 r = collect_fds(&fds, &error_message);
3050 if (r < 0)
dea374e8 3051 goto finish;
a16e1123 3052
2e51b31c
LP
3053 /* Give up any control of the console, but make sure its initialized. */
3054 setup_console_terminal(skip_setup);
56d96fc0 3055
a70c72a0
LP
3056 /* Open the logging devices, if possible and necessary */
3057 log_open();
56d96fc0 3058 }
4ade7963 3059
31aef7ff 3060 log_execution_mode(&first_boot);
a5dab5ce 3061
2d776038 3062 r = initialize_runtime(skip_setup,
3023f2fe 3063 first_boot,
2d776038
LP
3064 &saved_rlimit_nofile,
3065 &saved_rlimit_memlock,
3066 &error_message);
3067 if (r < 0)
3068 goto finish;
4096d6f5 3069
4870133b 3070 r = manager_new(arg_runtime_scope,
e0a3da1f
ZJS
3071 arg_action == ACTION_TEST ? MANAGER_TEST_FULL : 0,
3072 &m);
e96d6be7 3073 if (r < 0) {
ad5db940
OJ
3074 log_struct_errno(LOG_EMERG, r,
3075 LOG_MESSAGE("Failed to allocate manager object: %m"),
3076 "MESSAGE_ID=" SD_MESSAGE_CORE_MANAGER_ALLOCATE_STR);
cb6531be 3077 error_message = "Failed to allocate manager object";
60918275
LP
3078 goto finish;
3079 }
3080
9f9f0342
LP
3081 m->timestamps[MANAGER_TIMESTAMP_KERNEL] = kernel_timestamp;
3082 m->timestamps[MANAGER_TIMESTAMP_INITRD] = initrd_timestamp;
3083 m->timestamps[MANAGER_TIMESTAMP_USERSPACE] = userspace_timestamp;
d4ee7bd8
YW
3084 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START)] = security_start_timestamp;
3085 m->timestamps[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH)] = security_finish_timestamp;
9e58ff9c 3086
85cb4151 3087 set_manager_defaults(m);
7b46fc6a 3088 set_manager_settings(m);
fd130612 3089 manager_set_first_boot(m, first_boot);
d35fe8c0 3090 manager_set_switching_root(m, arg_switched_root);
27d340c7 3091
bf4df7c3 3092 /* Remember whether we should queue the default job */
d3b1c508 3093 queue_default_job = !arg_serialization || arg_switched_root;
bf4df7c3 3094
9d76d730
LP
3095 before_startup = now(CLOCK_MONOTONIC);
3096
2a7cf953 3097 r = manager_startup(m, arg_serialization, fds, /* root= */ NULL);
58f88d92 3098 if (r < 0) {
cefb3eda 3099 error_message = "Failed to start up manager";
58f88d92
ZJS
3100 goto finish;
3101 }
a16e1123 3102
6acca5fc 3103 /* This will close all file descriptors that were opened, but not claimed by any unit. */
2feceb5e 3104 fds = fdset_free(fds);
74ca738f 3105 arg_serialization = safe_fclose(arg_serialization);
bf4df7c3
LP
3106
3107 if (queue_default_job) {
6acca5fc 3108 r = do_queue_default_job(m, &error_message);
718db961 3109 if (r < 0)
37d88da7 3110 goto finish;
6acca5fc 3111 }
ab17a050 3112
6acca5fc 3113 after_startup = now(CLOCK_MONOTONIC);
60918275 3114
6acca5fc
LP
3115 log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
3116 "Loaded units and determined initial transaction in %s.",
5291f26d 3117 FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
07672f49 3118
6acca5fc 3119 if (arg_action == ACTION_TEST) {
2a341bb9 3120 manager_test_summary(m);
6acca5fc
LP
3121 retval = EXIT_SUCCESS;
3122 goto finish;
e965d56d 3123 }
d46de8a1 3124
5409c6fc
ZJS
3125 r = invoke_main_loop(m,
3126 &saved_rlimit_nofile,
3127 &saved_rlimit_memlock,
3128 &retval,
5409c6fc
ZJS
3129 &fds,
3130 &switch_root_dir,
3131 &switch_root_init,
3132 &error_message);
3133 assert(r < 0 || IN_SET(r, MANAGER_EXIT, /* MANAGER_OK is not expected here. */
3134 MANAGER_RELOAD,
3135 MANAGER_REEXECUTE,
3136 MANAGER_REBOOT,
13ffc607 3137 MANAGER_SOFT_REBOOT,
5409c6fc
ZJS
3138 MANAGER_POWEROFF,
3139 MANAGER_HALT,
3140 MANAGER_KEXEC,
3141 MANAGER_SWITCH_ROOT));
f170852a 3142
60918275 3143finish:
b87c2aa6
ZJS
3144 pager_close();
3145
92890452 3146 if (m) {
986935cf
FB
3147 arg_reboot_watchdog = manager_get_watchdog(m, WATCHDOG_REBOOT);
3148 arg_kexec_watchdog = manager_get_watchdog(m, WATCHDOG_KEXEC);
92890452
LP
3149 m = manager_free(m);
3150 }
60918275 3151
cc56fafe 3152 mac_selinux_finish();
b2bb3dbe 3153
13ffc607 3154 if (IN_SET(r, MANAGER_REEXECUTE, MANAGER_SWITCH_ROOT, MANAGER_SOFT_REBOOT))
1e3eee8c
ZJS
3155 r = do_reexecute(r,
3156 argc, argv,
3157 &saved_rlimit_nofile,
3158 &saved_rlimit_memlock,
3159 fds,
3160 switch_root_dir,
3161 switch_root_init,
3162 &error_message); /* This only returns if reexecution failed */
a16e1123 3163
74ca738f 3164 arg_serialization = safe_fclose(arg_serialization);
2feceb5e 3165 fds = fdset_free(fds);
a16e1123 3166
0e06a031
LP
3167 saved_env = strv_free(saved_env);
3168
349cc4a5 3169#if HAVE_VALGRIND_VALGRIND_H
54b434b1
LP
3170 /* If we are PID 1 and running under valgrind, then let's exit
3171 * here explicitly. valgrind will only generate nice output on
3172 * exit(), not on exec(), hence let's do the former not the
3173 * latter here. */
8a2c1fbf
EJ
3174 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND) {
3175 /* Cleanup watchdog_device strings for valgrind. We need them
3176 * in become_shutdown() so normally we cannot free them yet. */
3177 watchdog_free_device();
7d9eea2b 3178 reset_arguments();
27fe58b7 3179 return retval;
8a2c1fbf 3180 }
54b434b1
LP
3181#endif
3182
7e11a95e 3183#if HAS_FEATURE_ADDRESS_SANITIZER
ae5ce7e3
FS
3184 /* At this stage we most likely don't have stdio/stderr open, so the following
3185 * LSan check would not print any actionable information and would just crash
3186 * PID 1. To make this a bit more helpful, let's try to open /dev/console,
3187 * and if we succeed redirect LSan's report there. */
3188
3189 int tty_fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
3190 if (tty_fd >= 0)
3191 __sanitizer_set_report_fd((void*) (intptr_t) tty_fd);
3192
7e11a95e 3193 __lsan_do_leak_check();
ae5ce7e3 3194 tty_fd = safe_close(tty_fd);
7e11a95e
EV
3195#endif
3196
88eec29d
DDM
3197 if (r < 0)
3198 (void) sd_notifyf(0, "ERRNO=%i", -r);
3199
5409c6fc
ZJS
3200 /* Try to invoke the shutdown binary unless we already failed.
3201 * If we failed above, we want to freeze after finishing cleanup. */
4870133b
LP
3202 if (arg_runtime_scope == RUNTIME_SCOPE_SYSTEM &&
3203 IN_SET(r, MANAGER_EXIT, MANAGER_REBOOT, MANAGER_POWEROFF, MANAGER_HALT, MANAGER_KEXEC)) {
b22d392d 3204 r = become_shutdown(r, retval);
4a36297c 3205 log_error_errno(r, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
9b9881d7 3206 error_message = "Failed to execute shutdown binary";
b9080b03
FF
3207 }
3208
3a89cb84
DDM
3209 /* This is primarily useful when running systemd in a VM, as it provides the user running the VM with
3210 * a mechanism to pick up systemd's exit status in the VM. */
3211 (void) sd_notifyf(0, "EXIT_STATUS=%i", retval);
3212
8a2c1fbf
EJ
3213 watchdog_free_device();
3214 arg_watchdog_device = mfree(arg_watchdog_device);
3215
df0ff127 3216 if (getpid_cached() == 1) {
cb6531be
ZJS
3217 if (error_message)
3218 manager_status_printf(NULL, STATUS_TYPE_EMERGENCY,
1fc464f6 3219 ANSI_HIGHLIGHT_RED "!!!!!!" ANSI_NORMAL,
bb259772
LP
3220 "%s.", error_message);
3221 freeze_or_exit_or_reboot();
cb6531be 3222 }
c3b3c274 3223
7d9eea2b 3224 reset_arguments();
60918275
LP
3225 return retval;
3226}