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