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