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