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