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