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