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