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