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