1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/utsname.h>
11 #if HAVE_VALGRIND_VALGRIND_H
12 # include <valgrind/valgrind.h>
16 #include "sd-daemon.h"
17 #include "sd-messages.h"
19 #include "alloc-util.h"
20 #include "apparmor-setup.h"
21 #include "architecture.h"
22 #include "argv-util.h"
24 #include "bpf-restrict-fs.h"
27 #include "bus-error.h"
29 #include "capability-util.h"
30 #include "cgroup-util.h"
32 #include "clock-util.h"
33 #include "conf-parser.h"
34 #include "confidential-virt.h"
36 #include "cpu-set-util.h"
37 #include "crash-handler.h"
38 #include "dbus-manager.h"
40 #include "constants.h"
41 #include "dev-setup.h"
42 #include "efi-random.h"
44 #include "emergency-action.h"
46 #include "exit-status.h"
50 #include "format-util.h"
52 #include "getopt-defs.h"
53 #include "hexdecoct.h"
54 #include "hostname-setup.h"
55 #include "ima-setup.h"
56 #include "import-creds.h"
57 #include "initrd-util.h"
59 #include "kmod-setup.h"
60 #include "limits-util.h"
61 #include "load-fragment.h"
63 #include "loopback-setup.h"
64 #include "machine-id-setup.h"
67 #include "manager-dump.h"
68 #include "manager-serialize.h"
69 #include "mkdir-label.h"
70 #include "mount-setup.h"
71 #include "mount-util.h"
74 #include "parse-argument.h"
75 #include "parse-util.h"
76 #include "path-util.h"
77 #include "pretty-print.h"
78 #include "proc-cmdline.h"
79 #include "process-util.h"
81 #include "random-util.h"
82 #include "rlimit-util.h"
83 #include "seccomp-util.h"
84 #include "selinux-setup.h"
85 #include "selinux-util.h"
86 #include "signal-util.h"
87 #include "smack-setup.h"
89 #include "stat-util.h"
90 #include "stdio-util.h"
91 #include "string-table.h"
93 #include "switch-root.h"
94 #include "sysctl-util.h"
95 #include "terminal-util.h"
96 #include "time-util.h"
97 #include "umask-util.h"
98 #include "user-util.h"
101 #include "watchdog.h"
103 #if HAS_FEATURE_ADDRESS_SANITIZER
104 #include <sanitizer/lsan_interface.h>
112 ACTION_DUMP_CONFIGURATION_ITEMS
,
113 ACTION_DUMP_BUS_PROPERTIES
,
114 ACTION_BUS_INTROSPECT
,
115 } arg_action
= ACTION_RUN
;
117 static const char *arg_bus_introspect
= NULL
;
119 /* Those variables are initialized to 0 automatically, so we avoid uninitialized memory access. Real
120 * defaults are assigned in reset_arguments() below. */
121 static char *arg_default_unit
;
122 static RuntimeScope arg_runtime_scope
;
125 bool arg_crash_shell
;
126 CrashAction arg_crash_action
;
127 static char *arg_confirm_spawn
;
128 static ShowStatus arg_show_status
;
129 static StatusUnitFormat arg_status_unit_format
;
130 static bool arg_switched_root
;
131 static PagerFlags arg_pager_flags
;
132 static bool arg_service_watchdogs
;
133 static UnitDefaults arg_defaults
;
134 static usec_t arg_runtime_watchdog
;
135 static usec_t arg_reboot_watchdog
;
136 static usec_t arg_kexec_watchdog
;
137 static usec_t arg_pretimeout_watchdog
;
138 static char *arg_early_core_pattern
;
139 static char *arg_watchdog_pretimeout_governor
;
140 static char *arg_watchdog_device
;
141 static char **arg_default_environment
;
142 static char **arg_manager_environment
;
143 static uint64_t arg_capability_bounding_set
;
144 static bool arg_no_new_privs
;
145 static int arg_protect_system
;
146 static nsec_t arg_timer_slack_nsec
;
147 static Set
* arg_syscall_archs
;
148 static FILE* arg_serialization
;
149 static sd_id128_t arg_machine_id
;
150 static EmergencyAction arg_cad_burst_action
;
151 static CPUSet arg_cpu_affinity
;
152 static NUMAPolicy arg_numa_policy
;
153 static usec_t arg_clock_usec
;
154 static void *arg_random_seed
;
155 static size_t arg_random_seed_size
;
156 static usec_t arg_reload_limit_interval_sec
;
157 static unsigned arg_reload_limit_burst
;
159 /* A copy of the original environment block */
160 static char **saved_env
= NULL
;
162 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
163 const struct rlimit
*saved_rlimit_memlock
);
165 static const char* const crash_action_table
[_CRASH_ACTION_MAX
] = {
166 [CRASH_FREEZE
] = "freeze",
167 [CRASH_REBOOT
] = "reboot",
168 [CRASH_POWEROFF
] = "poweroff",
171 DEFINE_STRING_TABLE_LOOKUP(crash_action
, CrashAction
);
173 static DEFINE_CONFIG_PARSE_ENUM_WITH_DEFAULT(config_parse_crash_action
, crash_action
, CrashAction
, CRASH_FREEZE
, "Invalid crash action");
175 static int manager_find_user_config_paths(char ***ret_files
, char ***ret_dirs
) {
176 _cleanup_free_
char *base
= NULL
;
177 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
180 r
= xdg_user_config_dir(&base
, "/systemd");
184 r
= strv_extendf(&files
, "%s/user.conf", base
);
188 r
= strv_extend(&files
, PKGSYSCONFDIR
"/user.conf");
192 r
= strv_consume(&dirs
, TAKE_PTR(base
));
196 r
= strv_extend_strv(&dirs
, CONF_PATHS_STRV("systemd"), false);
200 *ret_files
= TAKE_PTR(files
);
201 *ret_dirs
= TAKE_PTR(dirs
);
205 static int console_setup(void) {
206 _cleanup_close_
int tty_fd
= -EBADF
;
210 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
212 return log_error_errno(tty_fd
, "Failed to open /dev/console: %m");
214 /* We don't want to force text mode. plymouth may be showing
215 * pictures already from initrd. */
216 r
= reset_terminal_fd(tty_fd
, false);
218 return log_error_errno(r
, "Failed to reset /dev/console: %m");
220 r
= proc_cmdline_tty_size("/dev/console", &rows
, &cols
);
222 log_warning_errno(r
, "Failed to get /dev/console size, ignoring: %m");
224 r
= terminal_set_size_fd(tty_fd
, NULL
, rows
, cols
);
226 log_warning_errno(r
, "Failed to set /dev/console size, ignoring: %m");
229 r
= terminal_reset_ansi_seq(tty_fd
);
231 log_warning_errno(r
, "Failed to reset /dev/console using ANSI sequences, ignoring: %m");
236 static int parse_proc_cmdline_item(const char *key
, const char *value
, void *data
) {
241 if (STR_IN_SET(key
, "systemd.unit", "rd.systemd.unit")) {
243 if (proc_cmdline_value_missing(key
, value
))
246 if (!unit_name_is_valid(value
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
247 log_warning("Unit name specified on %s= is not valid, ignoring: %s", key
, value
);
248 else if (in_initrd() == !!startswith(key
, "rd."))
249 return free_and_strdup_warn(&arg_default_unit
, value
);
251 } else if (proc_cmdline_key_streq(key
, "systemd.dump_core")) {
253 r
= value
? parse_boolean(value
) : true;
255 log_warning_errno(r
, "Failed to parse dump core switch %s, ignoring: %m", value
);
259 } else if (proc_cmdline_key_streq(key
, "systemd.early_core_pattern")) {
261 if (proc_cmdline_value_missing(key
, value
))
264 if (path_is_absolute(value
))
265 (void) parse_path_argument(value
, false, &arg_early_core_pattern
);
267 log_warning("Specified core pattern '%s' is not an absolute path, ignoring.", value
);
269 } else if (proc_cmdline_key_streq(key
, "systemd.crash_chvt")) {
272 arg_crash_chvt
= 0; /* turn on */
274 r
= parse_crash_chvt(value
, &arg_crash_chvt
);
276 log_warning_errno(r
, "Failed to parse crash chvt switch %s, ignoring: %m", value
);
279 } else if (proc_cmdline_key_streq(key
, "systemd.crash_shell")) {
281 r
= value
? parse_boolean(value
) : true;
283 log_warning_errno(r
, "Failed to parse crash shell switch %s, ignoring: %m", value
);
287 } else if (proc_cmdline_key_streq(key
, "systemd.crash_reboot")) {
289 r
= value
? parse_boolean(value
) : true;
291 log_warning_errno(r
, "Failed to parse crash reboot switch %s, ignoring: %m", value
);
293 arg_crash_action
= r
? CRASH_REBOOT
: CRASH_FREEZE
;
295 } else if (proc_cmdline_key_streq(key
, "systemd.crash_action")) {
297 if (proc_cmdline_value_missing(key
, value
))
300 r
= crash_action_from_string(value
);
302 log_warning_errno(r
, "Failed to parse crash action switch %s, ignoring: %m", value
);
304 arg_crash_action
= r
;
306 } else if (proc_cmdline_key_streq(key
, "systemd.confirm_spawn")) {
309 r
= parse_confirm_spawn(value
, &s
);
311 log_warning_errno(r
, "Failed to parse confirm_spawn switch %s, ignoring: %m", value
);
313 free_and_replace(arg_confirm_spawn
, s
);
315 } else if (proc_cmdline_key_streq(key
, "systemd.service_watchdogs")) {
317 r
= value
? parse_boolean(value
) : true;
319 log_warning_errno(r
, "Failed to parse service watchdog switch %s, ignoring: %m", value
);
321 arg_service_watchdogs
= r
;
323 } else if (proc_cmdline_key_streq(key
, "systemd.show_status")) {
326 r
= parse_show_status(value
, &arg_show_status
);
328 log_warning_errno(r
, "Failed to parse show status switch %s, ignoring: %m", value
);
330 arg_show_status
= SHOW_STATUS_YES
;
332 } else if (proc_cmdline_key_streq(key
, "systemd.status_unit_format")) {
334 if (proc_cmdline_value_missing(key
, value
))
337 r
= status_unit_format_from_string(value
);
339 log_warning_errno(r
, "Failed to parse %s=%s, ignoring: %m", key
, value
);
341 arg_status_unit_format
= r
;
343 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_output")) {
345 if (proc_cmdline_value_missing(key
, value
))
348 r
= exec_output_from_string(value
);
350 log_warning_errno(r
, "Failed to parse default standard output switch %s, ignoring: %m", value
);
352 arg_defaults
.std_output
= r
;
354 } else if (proc_cmdline_key_streq(key
, "systemd.default_standard_error")) {
356 if (proc_cmdline_value_missing(key
, value
))
359 r
= exec_output_from_string(value
);
361 log_warning_errno(r
, "Failed to parse default standard error switch %s, ignoring: %m", value
);
363 arg_defaults
.std_error
= r
;
365 } else if (streq(key
, "systemd.setenv")) {
367 if (proc_cmdline_value_missing(key
, value
))
370 if (!env_assignment_is_valid(value
))
371 log_warning("Environment variable assignment '%s' is not valid. Ignoring.", value
);
373 r
= strv_env_replace_strdup(&arg_default_environment
, value
);
378 } else if (proc_cmdline_key_streq(key
, "systemd.machine_id")) {
380 if (proc_cmdline_value_missing(key
, value
))
383 r
= id128_from_string_nonzero(value
, &arg_machine_id
);
385 log_warning_errno(r
, "MachineID '%s' is not valid, ignoring: %m", value
);
387 } else if (proc_cmdline_key_streq(key
, "systemd.default_timeout_start_sec")) {
389 if (proc_cmdline_value_missing(key
, value
))
392 r
= parse_sec(value
, &arg_defaults
.timeout_start_usec
);
394 log_warning_errno(r
, "Failed to parse default start timeout '%s', ignoring: %m", value
);
396 if (arg_defaults
.timeout_start_usec
<= 0)
397 arg_defaults
.timeout_start_usec
= USEC_INFINITY
;
399 } else if (proc_cmdline_key_streq(key
, "systemd.default_device_timeout_sec")) {
401 if (proc_cmdline_value_missing(key
, value
))
404 r
= parse_sec(value
, &arg_defaults
.device_timeout_usec
);
406 log_warning_errno(r
, "Failed to parse default device timeout '%s', ignoring: %m", value
);
408 if (arg_defaults
.device_timeout_usec
<= 0)
409 arg_defaults
.device_timeout_usec
= USEC_INFINITY
;
411 } else if (proc_cmdline_key_streq(key
, "systemd.cpu_affinity")) {
413 if (proc_cmdline_value_missing(key
, value
))
416 r
= parse_cpu_set(value
, &arg_cpu_affinity
);
418 log_warning_errno(r
, "Failed to parse CPU affinity mask '%s', ignoring: %m", value
);
420 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_device")) {
422 if (proc_cmdline_value_missing(key
, value
))
425 (void) parse_path_argument(value
, false, &arg_watchdog_device
);
427 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_sec")) {
429 if (proc_cmdline_value_missing(key
, value
))
432 if (streq(value
, "default"))
433 arg_runtime_watchdog
= USEC_INFINITY
;
434 else if (streq(value
, "off"))
435 arg_runtime_watchdog
= 0;
437 r
= parse_sec(value
, &arg_runtime_watchdog
);
439 log_warning_errno(r
, "Failed to parse systemd.watchdog_sec= argument '%s', ignoring: %m", value
);
444 arg_kexec_watchdog
= arg_reboot_watchdog
= arg_runtime_watchdog
;
446 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pre_sec")) {
448 if (proc_cmdline_value_missing(key
, value
))
451 if (streq(value
, "default"))
452 arg_pretimeout_watchdog
= USEC_INFINITY
;
453 else if (streq(value
, "off"))
454 arg_pretimeout_watchdog
= 0;
456 r
= parse_sec(value
, &arg_pretimeout_watchdog
);
458 log_warning_errno(r
, "Failed to parse systemd.watchdog_pre_sec= argument '%s', ignoring: %m", value
);
463 } else if (proc_cmdline_key_streq(key
, "systemd.watchdog_pretimeout_governor")) {
465 if (proc_cmdline_value_missing(key
, value
) || isempty(value
)) {
466 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
470 if (!string_is_safe(value
)) {
471 log_warning("Watchdog pretimeout governor '%s' is not valid, ignoring.", value
);
475 return free_and_strdup_warn(&arg_watchdog_pretimeout_governor
, value
);
477 } else if (proc_cmdline_key_streq(key
, "systemd.clock_usec")) {
479 if (proc_cmdline_value_missing(key
, value
))
482 r
= safe_atou64(value
, &arg_clock_usec
);
484 log_warning_errno(r
, "Failed to parse systemd.clock_usec= argument, ignoring: %s", value
);
486 } else if (proc_cmdline_key_streq(key
, "systemd.random_seed")) {
490 if (proc_cmdline_value_missing(key
, value
))
493 r
= unbase64mem(value
, &p
, &sz
);
495 log_warning_errno(r
, "Failed to parse systemd.random_seed= argument, ignoring: %s", value
);
497 free(arg_random_seed
);
498 arg_random_seed
= sz
> 0 ? p
: mfree(p
);
499 arg_random_seed_size
= sz
;
501 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_interval_sec")) {
503 if (proc_cmdline_value_missing(key
, value
))
506 r
= parse_sec(value
, &arg_reload_limit_interval_sec
);
508 log_warning_errno(r
, "Failed to parse systemd.reload_limit_interval_sec= argument '%s', ignoring: %m", value
);
512 } else if (proc_cmdline_key_streq(key
, "systemd.reload_limit_burst")) {
514 if (proc_cmdline_value_missing(key
, value
))
517 r
= safe_atou(value
, &arg_reload_limit_burst
);
519 log_warning_errno(r
, "Failed to parse systemd.reload_limit_burst= argument '%s', ignoring: %m", value
);
523 } else if (streq(key
, "quiet") && !value
) {
525 if (arg_show_status
== _SHOW_STATUS_INVALID
)
526 arg_show_status
= SHOW_STATUS_ERROR
;
528 } else if (streq(key
, "debug") && !value
) {
530 /* Note that log_parse_environment() handles 'debug'
531 * too, and sets the log level to LOG_DEBUG. */
533 if (detect_container() > 0)
534 log_set_target(LOG_TARGET_CONSOLE
);
539 /* Compatible with SysV, but supported independently even if SysV compatibility is disabled. */
540 target
= runlevel_to_target(key
);
542 return free_and_strdup_warn(&arg_default_unit
, target
);
548 #define DEFINE_SETTER(name, func, descr) \
549 static int name(const char *unit, \
550 const char *filename, \
552 const char *section, \
553 unsigned section_line, \
554 const char *lvalue, \
556 const char *rvalue, \
568 log_syntax(unit, LOG_ERR, filename, line, r, \
569 "Invalid " descr "'%s': %m", \
575 DEFINE_SETTER(config_parse_level2
, log_set_max_level_from_string
, "log level");
576 DEFINE_SETTER(config_parse_target
, log_set_target_from_string
, "target");
577 DEFINE_SETTER(config_parse_color
, log_show_color_from_string
, "color");
578 DEFINE_SETTER(config_parse_location
, log_show_location_from_string
, "location");
579 DEFINE_SETTER(config_parse_time
, log_show_time_from_string
, "time");
581 static int config_parse_default_timeout_abort(
583 const char *filename
,
586 unsigned section_line
,
594 r
= config_parse_timeout_abort(
603 &arg_defaults
.timeout_abort_usec
,
606 arg_defaults
.timeout_abort_set
= r
;
610 static int config_parse_oom_score_adjust(
612 const char *filename
,
615 unsigned section_line
,
624 if (isempty(rvalue
)) {
625 arg_defaults
.oom_score_adjust_set
= false;
629 r
= parse_oom_score_adjust(rvalue
, &oa
);
631 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse the OOM score adjust value '%s', ignoring: %m", rvalue
);
635 arg_defaults
.oom_score_adjust
= oa
;
636 arg_defaults
.oom_score_adjust_set
= true;
641 static int config_parse_protect_system_pid1(
643 const char *filename
,
646 unsigned section_line
,
653 int *v
= ASSERT_PTR(data
), r
;
655 /* This is modelled after the per-service ProtectSystem= setting, but a bit more restricted on one
656 * hand, and more automatic in another. i.e. we currently only support yes/no (not "strict" or
657 * "full"). And we will enable this automatically for the initrd unless configured otherwise.
659 * We might extend this later to match more closely what the per-service ProtectSystem= can do, but
660 * this is not trivial, due to ordering constraints: besides /usr/ we don't really have much mounted
661 * at the moment we enable this logic. */
663 if (isempty(rvalue
) || streq(rvalue
, "auto")) {
668 r
= parse_boolean(rvalue
);
670 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse ProtectSystem= argument '%s', ignoring: %m", rvalue
);
678 static int config_parse_crash_reboot(
680 const char *filename
,
683 unsigned section_line
,
690 CrashAction
*v
= ASSERT_PTR(data
);
693 if (isempty(rvalue
)) {
698 r
= parse_boolean(rvalue
);
700 log_syntax(unit
, LOG_WARNING
, filename
, line
, r
, "Failed to parse CrashReboot= argument '%s', ignoring: %m", rvalue
);
704 *v
= r
> 0 ? CRASH_REBOOT
: CRASH_FREEZE
;
708 static int parse_config_file(void) {
709 const ConfigTableItem items
[] = {
710 { "Manager", "LogLevel", config_parse_level2
, 0, NULL
},
711 { "Manager", "LogTarget", config_parse_target
, 0, NULL
},
712 { "Manager", "LogColor", config_parse_color
, 0, NULL
},
713 { "Manager", "LogLocation", config_parse_location
, 0, NULL
},
714 { "Manager", "LogTime", config_parse_time
, 0, NULL
},
715 { "Manager", "DumpCore", config_parse_bool
, 0, &arg_dump_core
},
716 { "Manager", "CrashChVT", /* legacy */ config_parse_crash_chvt
, 0, &arg_crash_chvt
},
717 { "Manager", "CrashChangeVT", config_parse_crash_chvt
, 0, &arg_crash_chvt
},
718 { "Manager", "CrashShell", config_parse_bool
, 0, &arg_crash_shell
},
719 { "Manager", "CrashReboot", config_parse_crash_reboot
, 0, &arg_crash_action
},
720 { "Manager", "CrashAction", config_parse_crash_action
, 0, &arg_crash_action
},
721 { "Manager", "ShowStatus", config_parse_show_status
, 0, &arg_show_status
},
722 { "Manager", "StatusUnitFormat", config_parse_status_unit_format
, 0, &arg_status_unit_format
},
723 { "Manager", "CPUAffinity", config_parse_cpu_affinity2
, 0, &arg_cpu_affinity
},
724 { "Manager", "NUMAPolicy", config_parse_numa_policy
, 0, &arg_numa_policy
.type
},
725 { "Manager", "NUMAMask", config_parse_numa_mask
, 0, &arg_numa_policy
},
726 { "Manager", "JoinControllers", config_parse_warn_compat
, DISABLED_LEGACY
, NULL
},
727 { "Manager", "RuntimeWatchdogSec", config_parse_watchdog_sec
, 0, &arg_runtime_watchdog
},
728 { "Manager", "RuntimeWatchdogPreSec", config_parse_watchdog_sec
, 0, &arg_pretimeout_watchdog
},
729 { "Manager", "RebootWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
},
730 { "Manager", "ShutdownWatchdogSec", config_parse_watchdog_sec
, 0, &arg_reboot_watchdog
}, /* obsolete alias */
731 { "Manager", "KExecWatchdogSec", config_parse_watchdog_sec
, 0, &arg_kexec_watchdog
},
732 { "Manager", "WatchdogDevice", config_parse_path
, 0, &arg_watchdog_device
},
733 { "Manager", "RuntimeWatchdogPreGovernor", config_parse_string
, CONFIG_PARSE_STRING_SAFE
, &arg_watchdog_pretimeout_governor
},
734 { "Manager", "CapabilityBoundingSet", config_parse_capability_set
, 0, &arg_capability_bounding_set
},
735 { "Manager", "NoNewPrivileges", config_parse_bool
, 0, &arg_no_new_privs
},
736 { "Manager", "ProtectSystem", config_parse_protect_system_pid1
, 0, &arg_protect_system
},
738 { "Manager", "SystemCallArchitectures", config_parse_syscall_archs
, 0, &arg_syscall_archs
},
740 { "Manager", "SystemCallArchitectures", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
743 { "Manager", "TimerSlackNSec", config_parse_nsec
, 0, &arg_timer_slack_nsec
},
744 { "Manager", "DefaultTimerAccuracySec", config_parse_sec
, 0, &arg_defaults
.timer_accuracy_usec
},
745 { "Manager", "DefaultStandardOutput", config_parse_output_restricted
, 0, &arg_defaults
.std_output
},
746 { "Manager", "DefaultStandardError", config_parse_output_restricted
, 0, &arg_defaults
.std_error
},
747 { "Manager", "DefaultTimeoutStartSec", config_parse_sec
, 0, &arg_defaults
.timeout_start_usec
},
748 { "Manager", "DefaultTimeoutStopSec", config_parse_sec
, 0, &arg_defaults
.timeout_stop_usec
},
749 { "Manager", "DefaultTimeoutAbortSec", config_parse_default_timeout_abort
, 0, NULL
},
750 { "Manager", "DefaultDeviceTimeoutSec", config_parse_sec
, 0, &arg_defaults
.device_timeout_usec
},
751 { "Manager", "DefaultRestartSec", config_parse_sec
, 0, &arg_defaults
.restart_usec
},
752 { "Manager", "DefaultStartLimitInterval", config_parse_sec
, 0, &arg_defaults
.start_limit_interval
}, /* obsolete alias */
753 { "Manager", "DefaultStartLimitIntervalSec", config_parse_sec
, 0, &arg_defaults
.start_limit_interval
},
754 { "Manager", "DefaultStartLimitBurst", config_parse_unsigned
, 0, &arg_defaults
.start_limit_burst
},
755 { "Manager", "DefaultEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_default_environment
},
756 { "Manager", "ManagerEnvironment", config_parse_environ
, arg_runtime_scope
, &arg_manager_environment
},
757 { "Manager", "DefaultLimitCPU", config_parse_rlimit
, RLIMIT_CPU
, arg_defaults
.rlimit
},
758 { "Manager", "DefaultLimitFSIZE", config_parse_rlimit
, RLIMIT_FSIZE
, arg_defaults
.rlimit
},
759 { "Manager", "DefaultLimitDATA", config_parse_rlimit
, RLIMIT_DATA
, arg_defaults
.rlimit
},
760 { "Manager", "DefaultLimitSTACK", config_parse_rlimit
, RLIMIT_STACK
, arg_defaults
.rlimit
},
761 { "Manager", "DefaultLimitCORE", config_parse_rlimit
, RLIMIT_CORE
, arg_defaults
.rlimit
},
762 { "Manager", "DefaultLimitRSS", config_parse_rlimit
, RLIMIT_RSS
, arg_defaults
.rlimit
},
763 { "Manager", "DefaultLimitNOFILE", config_parse_rlimit
, RLIMIT_NOFILE
, arg_defaults
.rlimit
},
764 { "Manager", "DefaultLimitAS", config_parse_rlimit
, RLIMIT_AS
, arg_defaults
.rlimit
},
765 { "Manager", "DefaultLimitNPROC", config_parse_rlimit
, RLIMIT_NPROC
, arg_defaults
.rlimit
},
766 { "Manager", "DefaultLimitMEMLOCK", config_parse_rlimit
, RLIMIT_MEMLOCK
, arg_defaults
.rlimit
},
767 { "Manager", "DefaultLimitLOCKS", config_parse_rlimit
, RLIMIT_LOCKS
, arg_defaults
.rlimit
},
768 { "Manager", "DefaultLimitSIGPENDING", config_parse_rlimit
, RLIMIT_SIGPENDING
, arg_defaults
.rlimit
},
769 { "Manager", "DefaultLimitMSGQUEUE", config_parse_rlimit
, RLIMIT_MSGQUEUE
, arg_defaults
.rlimit
},
770 { "Manager", "DefaultLimitNICE", config_parse_rlimit
, RLIMIT_NICE
, arg_defaults
.rlimit
},
771 { "Manager", "DefaultLimitRTPRIO", config_parse_rlimit
, RLIMIT_RTPRIO
, arg_defaults
.rlimit
},
772 { "Manager", "DefaultLimitRTTIME", config_parse_rlimit
, RLIMIT_RTTIME
, arg_defaults
.rlimit
},
773 { "Manager", "DefaultCPUAccounting", config_parse_bool
, 0, &arg_defaults
.cpu_accounting
},
774 { "Manager", "DefaultIOAccounting", config_parse_bool
, 0, &arg_defaults
.io_accounting
},
775 { "Manager", "DefaultIPAccounting", config_parse_bool
, 0, &arg_defaults
.ip_accounting
},
776 { "Manager", "DefaultBlockIOAccounting", config_parse_bool
, 0, &arg_defaults
.blockio_accounting
},
777 { "Manager", "DefaultMemoryAccounting", config_parse_bool
, 0, &arg_defaults
.memory_accounting
},
778 { "Manager", "DefaultTasksAccounting", config_parse_bool
, 0, &arg_defaults
.tasks_accounting
},
779 { "Manager", "DefaultTasksMax", config_parse_tasks_max
, 0, &arg_defaults
.tasks_max
},
780 { "Manager", "DefaultMemoryPressureThresholdSec", config_parse_sec
, 0, &arg_defaults
.memory_pressure_threshold_usec
},
781 { "Manager", "DefaultMemoryPressureWatch", config_parse_memory_pressure_watch
, 0, &arg_defaults
.memory_pressure_watch
},
782 { "Manager", "CtrlAltDelBurstAction", config_parse_emergency_action
, arg_runtime_scope
, &arg_cad_burst_action
},
783 { "Manager", "DefaultOOMPolicy", config_parse_oom_policy
, 0, &arg_defaults
.oom_policy
},
784 { "Manager", "DefaultOOMScoreAdjust", config_parse_oom_score_adjust
, 0, NULL
},
785 { "Manager", "ReloadLimitIntervalSec", config_parse_sec
, 0, &arg_reload_limit_interval_sec
},
786 { "Manager", "ReloadLimitBurst", config_parse_unsigned
, 0, &arg_reload_limit_burst
},
788 { "Manager", "DefaultSmackProcessLabel", config_parse_string
, 0, &arg_defaults
.smack_process_label
},
790 { "Manager", "DefaultSmackProcessLabel", config_parse_warn_compat
, DISABLED_CONFIGURATION
, NULL
},
795 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
)
796 (void) config_parse_standard_file_with_dropins(
797 "systemd/system.conf",
799 config_item_table_lookup
, items
,
801 /* userdata= */ NULL
);
803 _cleanup_strv_free_
char **files
= NULL
, **dirs
= NULL
;
806 assert(arg_runtime_scope
== RUNTIME_SCOPE_USER
);
808 r
= manager_find_user_config_paths(&files
, &dirs
);
810 return log_error_errno(r
, "Failed to determine config file paths: %m");
812 (void) config_parse_many(
813 (const char* const*) files
,
814 (const char* const*) dirs
,
818 config_item_table_lookup
, items
,
823 /* Traditionally "0" was used to turn off the default unit timeouts. Fix this up so that we use
824 * USEC_INFINITY like everywhere else. */
825 if (arg_defaults
.timeout_start_usec
<= 0)
826 arg_defaults
.timeout_start_usec
= USEC_INFINITY
;
827 if (arg_defaults
.timeout_stop_usec
<= 0)
828 arg_defaults
.timeout_stop_usec
= USEC_INFINITY
;
833 static void set_manager_defaults(Manager
*m
) {
838 /* Propagates the various default unit property settings into the manager object, i.e. properties
839 * that do not affect the manager itself, but are just what newly allocated units will have set if
840 * they haven't set anything else. (Also see set_manager_settings() for the settings that affect the
841 * manager's own behaviour) */
843 r
= manager_set_unit_defaults(m
, &arg_defaults
);
845 log_warning_errno(r
, "Failed to set manager defaults, ignoring: %m");
847 r
= manager_default_environment(m
);
849 log_warning_errno(r
, "Failed to set manager default environment, ignoring: %m");
851 r
= manager_transient_environment_add(m
, arg_default_environment
);
853 log_warning_errno(r
, "Failed to add to transient environment, ignoring: %m");
856 static void set_manager_settings(Manager
*m
) {
861 /* Propagates the various manager settings into the manager object, i.e. properties that
862 * effect the manager itself (as opposed to just being inherited into newly allocated
863 * units, see set_manager_defaults() above). */
865 m
->confirm_spawn
= arg_confirm_spawn
;
866 m
->service_watchdogs
= arg_service_watchdogs
;
867 m
->cad_burst_action
= arg_cad_burst_action
;
868 /* Note that we don't do structured initialization here, otherwise it will reset the rate limit
869 * counter on every daemon-reload. */
870 m
->reload_reexec_ratelimit
.interval
= arg_reload_limit_interval_sec
;
871 m
->reload_reexec_ratelimit
.burst
= arg_reload_limit_burst
;
873 manager_set_watchdog(m
, WATCHDOG_RUNTIME
, arg_runtime_watchdog
);
874 manager_set_watchdog(m
, WATCHDOG_REBOOT
, arg_reboot_watchdog
);
875 manager_set_watchdog(m
, WATCHDOG_KEXEC
, arg_kexec_watchdog
);
876 manager_set_watchdog(m
, WATCHDOG_PRETIMEOUT
, arg_pretimeout_watchdog
);
877 r
= manager_set_watchdog_pretimeout_governor(m
, arg_watchdog_pretimeout_governor
);
879 log_warning_errno(r
, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor
);
881 manager_set_show_status(m
, arg_show_status
, "command line");
882 m
->status_unit_format
= arg_status_unit_format
;
885 static int parse_argv(int argc
, char *argv
[]) {
891 static const struct option options
[] = {
892 COMMON_GETOPT_OPTIONS
,
893 SYSTEMD_GETOPT_OPTIONS
,
898 bool user_arg_seen
= false;
903 if (getpid_cached() == 1)
906 while ((c
= getopt_long(argc
, argv
, SYSTEMD_GETOPT_SHORT_OPTIONS
, options
, NULL
)) >= 0)
911 r
= log_set_max_level_from_string(optarg
);
913 return log_error_errno(r
, "Failed to parse log level \"%s\": %m", optarg
);
918 r
= log_set_target_from_string(optarg
);
920 return log_error_errno(r
, "Failed to parse log target \"%s\": %m", optarg
);
927 r
= log_show_color_from_string(optarg
);
929 return log_error_errno(r
, "Failed to parse log color setting \"%s\": %m",
932 log_show_color(true);
936 case ARG_LOG_LOCATION
:
938 r
= log_show_location_from_string(optarg
);
940 return log_error_errno(r
, "Failed to parse log location setting \"%s\": %m",
943 log_show_location(true);
950 r
= log_show_time_from_string(optarg
);
952 return log_error_errno(r
, "Failed to parse log time setting \"%s\": %m",
959 case ARG_DEFAULT_STD_OUTPUT
:
960 r
= exec_output_from_string(optarg
);
962 return log_error_errno(r
, "Failed to parse default standard output setting \"%s\": %m",
964 arg_defaults
.std_output
= r
;
967 case ARG_DEFAULT_STD_ERROR
:
968 r
= exec_output_from_string(optarg
);
970 return log_error_errno(r
, "Failed to parse default standard error output setting \"%s\": %m",
972 arg_defaults
.std_error
= r
;
976 r
= free_and_strdup(&arg_default_unit
, optarg
);
978 return log_error_errno(r
, "Failed to set default unit \"%s\": %m", optarg
);
983 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
987 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
988 user_arg_seen
= true;
992 arg_action
= ACTION_TEST
;
996 arg_pager_flags
|= PAGER_DISABLE
;
1000 arg_action
= ACTION_VERSION
;
1003 case ARG_DUMP_CONFIGURATION_ITEMS
:
1004 arg_action
= ACTION_DUMP_CONFIGURATION_ITEMS
;
1007 case ARG_DUMP_BUS_PROPERTIES
:
1008 arg_action
= ACTION_DUMP_BUS_PROPERTIES
;
1011 case ARG_BUS_INTROSPECT
:
1012 arg_bus_introspect
= optarg
;
1013 arg_action
= ACTION_BUS_INTROSPECT
;
1017 r
= parse_boolean_argument("--dump-core", optarg
, &arg_dump_core
);
1022 case ARG_CRASH_CHVT
:
1023 r
= parse_crash_chvt(optarg
, &arg_crash_chvt
);
1025 return log_error_errno(r
, "Failed to parse crash virtual terminal index: \"%s\": %m",
1029 case ARG_CRASH_SHELL
:
1030 r
= parse_boolean_argument("--crash-shell", optarg
, &arg_crash_shell
);
1035 case ARG_CRASH_REBOOT
:
1036 r
= parse_boolean_argument("--crash-reboot", optarg
, NULL
);
1039 arg_crash_action
= r
> 0 ? CRASH_REBOOT
: CRASH_FREEZE
;
1042 case ARG_CRASH_ACTION
:
1043 r
= crash_action_from_string(optarg
);
1045 return log_error_errno(r
, "Failed to parse crash action \"%s\": %m", optarg
);
1046 arg_crash_action
= r
;
1049 case ARG_CONFIRM_SPAWN
:
1050 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
1052 r
= parse_confirm_spawn(optarg
, &arg_confirm_spawn
);
1054 return log_error_errno(r
, "Failed to parse confirm spawn option: \"%s\": %m",
1058 case ARG_SERVICE_WATCHDOGS
:
1059 r
= parse_boolean_argument("--service-watchdogs=", optarg
, &arg_service_watchdogs
);
1064 case ARG_SHOW_STATUS
:
1066 r
= parse_show_status(optarg
, &arg_show_status
);
1068 return log_error_errno(r
, "Failed to parse show status boolean: \"%s\": %m",
1071 arg_show_status
= SHOW_STATUS_YES
;
1074 case ARG_DESERIALIZE
: {
1078 fd
= parse_fd(optarg
);
1080 return log_error_errno(fd
, "Failed to parse serialization fd \"%s\": %m", optarg
);
1082 (void) fd_cloexec(fd
, true);
1084 f
= fdopen(fd
, "r");
1086 return log_error_errno(errno
, "Failed to open serialization fd %d: %m", fd
);
1088 safe_fclose(arg_serialization
);
1089 arg_serialization
= f
;
1094 case ARG_SWITCHED_ROOT
:
1095 arg_switched_root
= true;
1098 case ARG_MACHINE_ID
:
1099 r
= id128_from_string_nonzero(optarg
, &arg_machine_id
);
1101 return log_error_errno(r
, "MachineID '%s' is not valid: %m", optarg
);
1105 arg_action
= ACTION_HELP
;
1109 log_set_max_level(LOG_DEBUG
);
1115 /* Just to eat away the sysvinit kernel cmdline args that we'll parse in
1116 * parse_proc_cmdline_item() or ignore, without any getopt() error messages.
1119 if (getpid_cached() != 1)
1125 assert_not_reached();
1128 if (optind
< argc
&& getpid_cached() != 1)
1129 /* Hmm, when we aren't run as init system let's complain about excess arguments */
1130 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Excess arguments.");
1132 if (arg_action
== ACTION_RUN
&& arg_runtime_scope
== RUNTIME_SCOPE_USER
&& !user_arg_seen
)
1133 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1134 "Explicit --user argument required to run as user manager.");
1139 static int help(void) {
1140 _cleanup_free_
char *link
= NULL
;
1143 r
= terminal_urlify_man("systemd", "1", &link
);
1147 printf("%s [OPTIONS...]\n\n"
1148 "%sStarts and monitors system and user services.%s\n\n"
1149 "This program takes no positional arguments.\n\n"
1151 " -h --help Show this help\n"
1152 " --version Show version\n"
1153 " --test Determine initial transaction, dump it and exit\n"
1154 " --system Combined with --test: operate in system mode\n"
1155 " --user Combined with --test: operate in user mode\n"
1156 " --dump-configuration-items Dump understood unit configuration items\n"
1157 " --dump-bus-properties Dump exposed bus properties\n"
1158 " --bus-introspect=PATH Write XML introspection data\n"
1159 " --unit=UNIT Set default unit\n"
1160 " --dump-core[=BOOL] Dump core on crash\n"
1161 " --crash-vt=NR Change to specified VT on crash\n"
1162 " --crash-action=ACTION Specify what to do on crash\n"
1163 " --crash-shell[=BOOL] Run shell on crash\n"
1164 " --confirm-spawn[=BOOL] Ask for confirmation when spawning processes\n"
1165 " --show-status[=BOOL] Show status updates on the console during boot\n"
1166 " --log-target=TARGET Set log target (console, journal, kmsg,\n"
1167 " journal-or-kmsg, null)\n"
1168 " --log-level=LEVEL Set log level (debug, info, notice, warning,\n"
1169 " err, crit, alert, emerg)\n"
1170 " --log-color[=BOOL] Highlight important log messages\n"
1171 " --log-location[=BOOL] Include code location in log messages\n"
1172 " --log-time[=BOOL] Prefix log messages with current time\n"
1173 " --default-standard-output= Set default standard output for services\n"
1174 " --default-standard-error= Set default standard error output for services\n"
1175 " --no-pager Do not pipe output into a pager\n"
1176 "\nSee the %s for details.\n",
1177 program_invocation_short_name
,
1187 static int prepare_reexecute(
1191 bool switching_root
) {
1193 _cleanup_fdset_free_ FDSet
*fds
= NULL
;
1194 _cleanup_fclose_
FILE *f
= NULL
;
1201 r
= manager_open_serialization(m
, &f
);
1203 return log_error_errno(r
, "Failed to create serialization file: %m");
1205 /* Make sure nothing is really destructed when we shut down */
1207 bus_manager_send_reloading(m
, true);
1213 r
= manager_serialize(m
, f
, fds
, switching_root
);
1217 if (fseeko(f
, 0, SEEK_SET
) < 0)
1218 return log_error_errno(errno
, "Failed to rewind serialization fd: %m");
1220 r
= fd_cloexec(fileno(f
), false);
1222 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization: %m");
1224 r
= fdset_cloexec(fds
, false);
1226 return log_error_errno(r
, "Failed to disable O_CLOEXEC for serialization fds: %m");
1228 *ret_f
= TAKE_PTR(f
);
1229 *ret_fds
= TAKE_PTR(fds
);
1234 static void bump_file_max_and_nr_open(void) {
1236 /* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
1237 * numbers of file descriptors are no longer a performance problem and their memory is properly
1238 * tracked by memcg, thus counting them and limiting them in another two layers of limits is
1239 * unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
1240 * on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
1242 #if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
1246 #if BUMP_PROC_SYS_FS_FILE_MAX
1247 /* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
1248 * different, but the operation would fail silently.) */
1249 r
= sysctl_write("fs/file-max", LONG_MAX_STR
);
1251 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
,
1252 r
, "Failed to bump fs.file-max, ignoring: %m");
1255 #if BUMP_PROC_SYS_FS_NR_OPEN
1258 /* Argh! The kernel enforces maximum and minimum values on the fs.nr_open, but we don't really know
1259 * what they are. The expression by which the maximum is determined is dependent on the architecture,
1260 * and is something we don't really want to copy to userspace, as it is dependent on implementation
1261 * details of the kernel. Since the kernel doesn't expose the maximum value to us, we can only try
1262 * and hope. Hence, let's start with INT_MAX, and then keep halving the value until we find one that
1263 * works. Ugly? Yes, absolutely, but kernel APIs are kernel APIs, so what do can we do... 🤯 */
1268 v
&= ~(__SIZEOF_POINTER__
- 1); /* Round down to next multiple of the pointer size */
1270 log_warning("Can't bump fs.nr_open, value too small.");
1276 log_error_errno(k
, "Failed to read fs.nr_open: %m");
1279 if (k
>= v
) { /* Already larger */
1280 log_debug("Skipping bump, value is already larger.");
1284 r
= sysctl_writef("fs/nr_open", "%i", v
);
1286 log_debug("Couldn't write fs.nr_open as %i, halving it.", v
);
1291 log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
, "Failed to bump fs.nr_open, ignoring: %m");
1295 log_debug("Successfully bumped fs.nr_open to %i", v
);
1301 static int bump_rlimit_nofile(const struct rlimit
*saved_rlimit
) {
1302 struct rlimit new_rlimit
;
1305 /* Get the underlying absolute limit the kernel enforces */
1306 nr
= read_nr_open();
1308 /* Calculate the new limits to use for us. Never lower from what we inherited. */
1309 new_rlimit
= (struct rlimit
) {
1310 .rlim_cur
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_cur
),
1311 .rlim_max
= MAX((rlim_t
) nr
, saved_rlimit
->rlim_max
),
1314 /* Shortcut if nothing changes. */
1315 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_max
&&
1316 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_cur
) {
1317 log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
1321 /* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
1322 * both hard and soft. */
1323 r
= setrlimit_closest(RLIMIT_NOFILE
, &new_rlimit
);
1325 return log_warning_errno(r
, "Setting RLIMIT_NOFILE failed, ignoring: %m");
1330 static int bump_rlimit_memlock(const struct rlimit
*saved_rlimit
) {
1331 struct rlimit new_rlimit
;
1335 /* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
1336 * which should normally disable such checks. We need them to implement IPAddressAllow= and
1337 * IPAddressDeny=, hence let's bump the value high enough for our user. */
1339 /* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
1340 * must be unsigned, hence this is a given, but let's make this clear here. */
1341 assert_cc(RLIM_INFINITY
> 0);
1343 mm
= physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
1344 * physical RAM. We allow an eighth to be locked by us, just to
1347 new_rlimit
= (struct rlimit
) {
1348 .rlim_cur
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_cur
, mm
),
1349 .rlim_max
= MAX3(HIGH_RLIMIT_MEMLOCK
, saved_rlimit
->rlim_max
, mm
),
1352 if (saved_rlimit
->rlim_max
>= new_rlimit
.rlim_cur
&&
1353 saved_rlimit
->rlim_cur
>= new_rlimit
.rlim_max
) {
1354 log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
1358 r
= setrlimit_closest(RLIMIT_MEMLOCK
, &new_rlimit
);
1360 return log_warning_errno(r
, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
1365 static void test_usr(void) {
1367 /* Check that /usr is either on the same file system as / or mounted already. */
1369 if (dir_is_empty("/usr", /* ignore_hidden_or_backup= */ false) <= 0)
1372 log_warning("/usr appears to be on its own filesystem and is not already mounted. This is not a supported setup. "
1373 "Some things will probably break (sometimes even silently) in mysterious ways. "
1374 "Consult https://www.freedesktop.org/wiki/Software/systemd/separate-usr-is-broken for more information.");
1377 static int enforce_syscall_archs(Set
*archs
) {
1381 if (!is_seccomp_available())
1384 r
= seccomp_restrict_archs(arg_syscall_archs
);
1386 return log_error_errno(r
, "Failed to enforce system call architecture restriction: %m");
1391 static int os_release_status(void) {
1392 _cleanup_free_
char *pretty_name
= NULL
, *name
= NULL
, *version
= NULL
,
1393 *ansi_color
= NULL
, *support_end
= NULL
;
1396 r
= parse_os_release(NULL
,
1397 "PRETTY_NAME", &pretty_name
,
1399 "VERSION", &version
,
1400 "ANSI_COLOR", &ansi_color
,
1401 "SUPPORT_END", &support_end
);
1403 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1404 "Failed to read os-release file, ignoring: %m");
1406 const char *label
= os_release_pretty_name(pretty_name
, name
);
1408 if (show_status_on(arg_show_status
)) {
1409 if (log_get_show_color())
1410 status_printf(NULL
, 0,
1411 "\nWelcome to \x1B[%sm%s\x1B[0m!\n",
1412 empty_to_null(ansi_color
) ?: "1",
1415 status_printf(NULL
, 0,
1416 "\nWelcome to %s!\n",
1420 if (support_end
&& os_release_support_ended(support_end
, /* quiet */ false, NULL
) > 0)
1421 /* pretty_name may include the version already, so we'll print the version only if we
1422 * have it and we're not using pretty_name. */
1423 status_printf(ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
, 0,
1424 "This OS version (%s%s%s) is past its end-of-support date (%s)",
1426 (pretty_name
|| !version
) ? "" : " version ",
1427 (pretty_name
|| !version
) ? "" : version
,
1433 static int setup_os_release(RuntimeScope scope
) {
1434 _cleanup_free_
char *os_release_dst
= NULL
;
1435 const char *os_release_src
= "/etc/os-release";
1438 if (access("/etc/os-release", F_OK
) < 0) {
1439 if (errno
!= ENOENT
)
1440 log_debug_errno(errno
, "Failed to check if /etc/os-release exists, ignoring: %m");
1442 os_release_src
= "/usr/lib/os-release";
1445 if (scope
== RUNTIME_SCOPE_SYSTEM
) {
1446 os_release_dst
= strdup("/run/systemd/propagate/.os-release-stage/os-release");
1447 if (!os_release_dst
)
1448 return log_oom_debug();
1450 if (asprintf(&os_release_dst
, "/run/user/" UID_FMT
"/systemd/propagate/.os-release-stage/os-release", geteuid()) < 0)
1451 return log_oom_debug();
1454 r
= mkdir_parents_label(os_release_dst
, 0755);
1456 return log_debug_errno(r
, "Failed to create parent directory of %s, ignoring: %m", os_release_dst
);
1458 r
= copy_file_atomic(os_release_src
, os_release_dst
, 0644, COPY_MAC_CREATE
|COPY_REPLACE
);
1460 return log_debug_errno(r
, "Failed to create %s, ignoring: %m", os_release_dst
);
1465 static int write_container_id(void) {
1467 int r
= 0; /* avoid false maybe-uninitialized warning */
1469 c
= getenv("container");
1474 r
= write_string_file("/run/systemd/container", c
, WRITE_STRING_FILE_CREATE
);
1476 return log_warning_errno(r
, "Failed to write /run/systemd/container, ignoring: %m");
1481 static int bump_unix_max_dgram_qlen(void) {
1482 _cleanup_free_
char *qlen
= NULL
;
1486 /* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
1487 * the value really really early during boot, so that it is actually applied to all our sockets,
1488 * including the $NOTIFY_SOCKET one. */
1490 r
= read_one_line_file("/proc/sys/net/unix/max_dgram_qlen", &qlen
);
1492 return log_full_errno(r
== -ENOENT
? LOG_DEBUG
: LOG_WARNING
, r
,
1493 "Failed to read AF_UNIX datagram queue length, ignoring: %m");
1495 r
= safe_atolu(qlen
, &v
);
1497 return log_warning_errno(r
, "Failed to parse AF_UNIX datagram queue length '%s', ignoring: %m", qlen
);
1499 if (v
>= DEFAULT_UNIX_MAX_DGRAM_QLEN
)
1502 r
= sysctl_write("net/unix/max_dgram_qlen", STRINGIFY(DEFAULT_UNIX_MAX_DGRAM_QLEN
));
1504 return log_full_errno(IN_SET(r
, -EROFS
, -EPERM
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1505 "Failed to bump AF_UNIX datagram queue length, ignoring: %m");
1510 static int fixup_environment(void) {
1511 _cleanup_free_
char *term
= NULL
;
1515 /* Only fix up the environment when we are started as PID 1 */
1516 if (getpid_cached() != 1)
1519 /* We expect the environment to be set correctly if run inside a container. */
1520 if (detect_container() > 0)
1523 /* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
1524 * backend device used by the console. We try to make a better guess here since some consoles might
1525 * not have support for color mode for example.
1527 * However if TERM was configured through the kernel command line then leave it alone. */
1528 r
= proc_cmdline_get_key("TERM", 0, &term
);
1533 r
= proc_cmdline_get_key("systemd.tty.term.console", 0, &term
);
1538 t
= term
?: default_term_for_tty("/dev/console");
1540 if (setenv("TERM", t
, 1) < 0)
1543 /* The kernels sets HOME=/ for init. Let's undo this. */
1544 if (path_equal(getenv("HOME"), "/"))
1545 assert_se(unsetenv("HOME") == 0);
1550 static void redirect_telinit(int argc
, char *argv
[]) {
1552 /* This is compatibility support for SysV, where calling init as a user is identical to telinit. */
1554 #if HAVE_SYSV_COMPAT
1555 if (getpid_cached() == 1)
1558 if (!invoked_as(argv
, "init"))
1561 execv(SYSTEMCTL_BINARY_PATH
, argv
);
1562 log_error_errno(errno
, "Failed to exec " SYSTEMCTL_BINARY_PATH
": %m");
1567 static int become_shutdown(int objective
, int retval
) {
1568 static const char* const table
[_MANAGER_OBJECTIVE_MAX
] = {
1569 [MANAGER_EXIT
] = "exit",
1570 [MANAGER_REBOOT
] = "reboot",
1571 [MANAGER_POWEROFF
] = "poweroff",
1572 [MANAGER_HALT
] = "halt",
1573 [MANAGER_KEXEC
] = "kexec",
1576 char timeout
[STRLEN("--timeout=") + DECIMAL_STR_MAX(usec_t
) + STRLEN("us")],
1577 exit_code
[STRLEN("--exit-code=") + DECIMAL_STR_MAX(uint8_t)];
1579 _cleanup_strv_free_
char **env_block
= NULL
;
1580 _cleanup_free_
char *max_log_levels
= NULL
;
1581 usec_t watchdog_timer
= 0;
1584 assert(objective
>= 0 && objective
< _MANAGER_OBJECTIVE_MAX
);
1585 assert(table
[objective
]);
1587 xsprintf(timeout
, "--timeout=%" PRI_USEC
"us", arg_defaults
.timeout_stop_usec
);
1589 const char* command_line
[11] = {
1590 SYSTEMD_SHUTDOWN_BINARY_PATH
,
1593 /* Note that the last position is a terminator and must contain NULL. */
1597 assert(command_line
[pos
-1]);
1598 assert(!command_line
[pos
]);
1600 (void) log_max_levels_to_string(log_get_max_level(), &max_log_levels
);
1602 if (max_log_levels
) {
1603 command_line
[pos
++] = "--log-level";
1604 command_line
[pos
++] = max_log_levels
;
1607 switch (log_get_target()) {
1609 case LOG_TARGET_KMSG
:
1610 case LOG_TARGET_JOURNAL_OR_KMSG
:
1611 case LOG_TARGET_SYSLOG_OR_KMSG
:
1612 command_line
[pos
++] = "--log-target=kmsg";
1615 case LOG_TARGET_NULL
:
1616 command_line
[pos
++] = "--log-target=null";
1619 case LOG_TARGET_CONSOLE
:
1621 command_line
[pos
++] = "--log-target=console";
1625 if (log_get_show_color())
1626 command_line
[pos
++] = "--log-color";
1628 if (log_get_show_location())
1629 command_line
[pos
++] = "--log-location";
1631 if (log_get_show_time())
1632 command_line
[pos
++] = "--log-time";
1634 xsprintf(exit_code
, "--exit-code=%d", retval
);
1635 command_line
[pos
++] = exit_code
;
1637 assert(pos
< ELEMENTSOF(command_line
));
1641 if (objective
== MANAGER_REBOOT
)
1642 watchdog_timer
= arg_reboot_watchdog
;
1643 else if (objective
== MANAGER_KEXEC
)
1644 watchdog_timer
= arg_kexec_watchdog
;
1646 /* If we reboot or kexec let's set the shutdown watchdog and tell the
1647 * shutdown binary to repeatedly ping it.
1648 * Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
1649 (void) watchdog_setup_pretimeout(0);
1650 (void) watchdog_setup_pretimeout_governor(NULL
);
1651 r
= watchdog_setup(watchdog_timer
);
1652 watchdog_close(r
< 0);
1654 /* The environment block: */
1656 env_block
= strv_copy(environ
);
1658 /* Tell the binary how often to ping, ignore failure */
1659 (void) strv_extendf(&env_block
, "WATCHDOG_USEC="USEC_FMT
, watchdog_timer
);
1661 if (arg_watchdog_device
)
1662 (void) strv_extendf(&env_block
, "WATCHDOG_DEVICE=%s", arg_watchdog_device
);
1664 /* Avoid the creation of new processes forked by the kernel; at this
1665 * point, we will not listen to the signals anyway */
1666 if (detect_container() <= 0)
1667 (void) cg_uninstall_release_agent(SYSTEMD_CGROUP_CONTROLLER
);
1669 execve(SYSTEMD_SHUTDOWN_BINARY_PATH
, (char **) command_line
, env_block
);
1673 static void initialize_clock(void) {
1676 /* This is called very early on, before we parse the kernel command line or otherwise figure out why
1677 * we are running, but only once. */
1679 if (clock_is_localtime(NULL
) > 0) {
1682 /* The very first call of settimeofday() also does a time warp in the kernel.
1684 * In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
1685 * take care of maintaining the RTC and do all adjustments. This matches the behavior of
1686 * Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
1688 r
= clock_set_timezone(&min
);
1690 log_error_errno(r
, "Failed to apply local time delta, ignoring: %m");
1692 log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min
);
1694 } else if (!in_initrd())
1696 * Do a dummy very first call to seal the kernel's time warp magic.
1698 * Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
1699 * LOCAL, but the real system could be set up that way. In such case, we need to delay the
1700 * time-warp or the sealing until we reach the real system.
1702 * Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
1703 * the time will jump or be incorrect at every daylight saving time change. All kernel local
1704 * time concepts will be treated as UTC that way.
1706 (void) clock_reset_timewarp();
1708 ClockChangeDirection change_dir
;
1709 r
= clock_apply_epoch(&change_dir
);
1710 if (r
> 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1711 log_info("System time before build time, advancing clock.");
1712 else if (r
> 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1713 log_info("System time is further ahead than %s after build time, resetting clock to build time.",
1714 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1715 else if (r
< 0 && change_dir
== CLOCK_CHANGE_FORWARD
)
1716 log_error_errno(r
, "Current system time is before build time, but cannot correct: %m");
1717 else if (r
< 0 && change_dir
== CLOCK_CHANGE_BACKWARD
)
1718 log_error_errno(r
, "Current system time is further ahead %s after build time, but cannot correct: %m",
1719 FORMAT_TIMESPAN(CLOCK_VALID_RANGE_USEC_MAX
, USEC_PER_DAY
));
1722 static void apply_clock_update(void) {
1723 /* This is called later than initialize_clock(), i.e. after we parsed configuration files/kernel
1724 * command line and such. */
1726 if (arg_clock_usec
== 0)
1729 if (getpid_cached() != 1)
1732 if (clock_settime(CLOCK_REALTIME
, TIMESPEC_STORE(arg_clock_usec
)) < 0)
1733 log_error_errno(errno
, "Failed to set system clock to time specified on kernel command line: %m");
1735 log_info("Set system clock to %s, as specified on the kernel command line.",
1736 FORMAT_TIMESTAMP(arg_clock_usec
));
1739 static void cmdline_take_random_seed(void) {
1743 if (arg_random_seed_size
== 0)
1746 if (getpid_cached() != 1)
1749 assert(arg_random_seed
);
1750 suggested
= random_pool_size();
1752 if (arg_random_seed_size
< suggested
)
1753 log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
1754 arg_random_seed_size
, suggested
);
1756 r
= random_write_entropy(-1, arg_random_seed
, arg_random_seed_size
, true);
1758 log_warning_errno(r
, "Failed to credit entropy specified on kernel command line, ignoring: %m");
1762 log_notice("Successfully credited entropy passed on kernel command line.\n"
1763 "Note that the seed provided this way is accessible to unprivileged programs. "
1764 "This functionality should not be used outside of testing environments.");
1767 static void initialize_coredump(bool skip_setup
) {
1768 if (getpid_cached() != 1)
1771 /* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
1772 * the limit) will process core dumps for system services by default. */
1773 if (setrlimit(RLIMIT_CORE
, &RLIMIT_MAKE_CONST(RLIM_INFINITY
)) < 0)
1774 log_warning_errno(errno
, "Failed to set RLIMIT_CORE: %m");
1776 /* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
1777 * until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
1778 * command line later so core dumps can still be generated during early startup and in initrd. */
1780 disable_coredumps();
1783 static void initialize_core_pattern(bool skip_setup
) {
1786 if (skip_setup
|| !arg_early_core_pattern
)
1789 if (getpid_cached() != 1)
1792 r
= write_string_file("/proc/sys/kernel/core_pattern", arg_early_core_pattern
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1794 log_warning_errno(r
, "Failed to write '%s' to /proc/sys/kernel/core_pattern, ignoring: %m",
1795 arg_early_core_pattern
);
1798 static void apply_protect_system(bool skip_setup
) {
1801 if (skip_setup
|| getpid_cached() != 1 || arg_protect_system
== 0)
1804 if (arg_protect_system
< 0 && !in_initrd()) {
1805 log_debug("ProtectSystem=auto selected, but not running in an initrd, skipping.");
1809 r
= make_mount_point("/usr");
1811 log_warning_errno(r
, "Failed to make /usr/ a mount point, ignoring: %m");
1815 if (mount_nofollow_verbose(
1820 MS_BIND
|MS_REMOUNT
|MS_RDONLY
,
1821 /* options= */ NULL
) < 0)
1824 log_info("Successfully made /usr/ read-only.");
1827 static void update_cpu_affinity(bool skip_setup
) {
1828 _cleanup_free_
char *mask
= NULL
;
1830 if (skip_setup
|| !arg_cpu_affinity
.set
)
1833 assert(arg_cpu_affinity
.allocated
> 0);
1835 mask
= cpu_set_to_range_string(&arg_cpu_affinity
);
1836 log_debug("Setting CPU affinity to {%s}.", strnull(mask
));
1838 if (sched_setaffinity(0, arg_cpu_affinity
.allocated
, arg_cpu_affinity
.set
) < 0)
1839 log_warning_errno(errno
, "Failed to set CPU affinity, ignoring: %m");
1842 static void update_numa_policy(bool skip_setup
) {
1844 _cleanup_free_
char *nodes
= NULL
;
1845 const char * policy
= NULL
;
1847 if (skip_setup
|| !mpol_is_valid(numa_policy_get_type(&arg_numa_policy
)))
1850 if (DEBUG_LOGGING
) {
1851 policy
= mpol_to_string(numa_policy_get_type(&arg_numa_policy
));
1852 nodes
= cpu_set_to_range_string(&arg_numa_policy
.nodes
);
1853 log_debug("Setting NUMA policy to %s, with nodes {%s}.", strnull(policy
), strnull(nodes
));
1856 r
= apply_numa_policy(&arg_numa_policy
);
1857 if (r
== -EOPNOTSUPP
)
1858 log_debug_errno(r
, "NUMA support not available, ignoring.");
1860 log_warning_errno(r
, "Failed to set NUMA memory policy, ignoring: %m");
1863 static void filter_args(
1872 /* Copy some filtered arguments into the dst array from src. */
1873 for (int i
= 1; i
< argc
; i
++) {
1874 if (STR_IN_SET(src
[i
],
1880 if (startswith(src
[i
], "--deserialize="))
1882 if (streq(src
[i
], "--deserialize")) {
1883 i
++; /* Skip the argument too */
1887 /* Skip target unit designators. We already acted upon this information and have queued
1888 * appropriate jobs. We don't want to redo all this after reexecution. */
1889 if (startswith(src
[i
], "--unit="))
1891 if (streq(src
[i
], "--unit")) {
1892 i
++; /* Skip the argument too */
1896 /* Seems we have a good old option. Let's pass it over to the new instance. */
1897 dst
[(*dst_index
)++] = src
[i
];
1901 static void finish_remaining_processes(ManagerObjective objective
) {
1902 assert(objective
>= 0 && objective
< _MANAGER_OBJECTIVE_MAX
);
1904 /* Kill all remaining processes from the initrd, but don't wait for them, so that we can handle the
1905 * SIGCHLD for them after deserializing. */
1906 if (IN_SET(objective
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
1907 broadcast_signal(SIGTERM
, /* wait_for_exit= */ false, /* send_sighup= */ true, arg_defaults
.timeout_stop_usec
);
1909 /* On soft reboot really make sure nothing is left. Note that this will skip cgroups
1910 * of units that were configured with SurviveFinalKillSignal=yes. */
1911 if (objective
== MANAGER_SOFT_REBOOT
)
1912 broadcast_signal(SIGKILL
, /* wait_for_exit= */ false, /* send_sighup= */ false, arg_defaults
.timeout_stop_usec
);
1915 static int do_reexecute(
1916 ManagerObjective objective
,
1919 const struct rlimit
*saved_rlimit_nofile
,
1920 const struct rlimit
*saved_rlimit_memlock
,
1922 const char *switch_root_dir
,
1923 const char *switch_root_init
,
1924 const char **ret_error_message
) {
1926 size_t i
, args_size
;
1930 assert(IN_SET(objective
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
));
1932 assert(saved_rlimit_nofile
);
1933 assert(saved_rlimit_memlock
);
1934 assert(ret_error_message
);
1936 if (switch_root_init
) {
1937 r
= chase(switch_root_init
, switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1939 log_warning_errno(r
, "Failed to chase configured init %s/%s: %m",
1940 strempty(switch_root_dir
), switch_root_init
);
1942 r
= chase(SYSTEMD_BINARY_PATH
, switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1944 log_debug_errno(r
, "Failed to chase our own binary %s/%s: %m",
1945 strempty(switch_root_dir
), SYSTEMD_BINARY_PATH
);
1949 r
= chase("/sbin/init", switch_root_dir
, CHASE_PREFIX_ROOT
, NULL
, NULL
);
1951 return log_error_errno(r
, "Failed to chase %s/sbin/init", strempty(switch_root_dir
));
1954 /* Close and disarm the watchdog, so that the new instance can reinitialize it, but doesn't get
1955 * rebooted while we do that */
1956 watchdog_close(true);
1958 /* Reset RLIMIT_NOFILE + RLIMIT_MEMLOCK back to the kernel defaults, so that the new systemd can pass
1959 * the kernel default to its child processes */
1960 if (saved_rlimit_nofile
->rlim_cur
!= 0)
1961 (void) setrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
);
1962 if (saved_rlimit_memlock
->rlim_cur
!= RLIM_INFINITY
)
1963 (void) setrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
);
1965 finish_remaining_processes(objective
);
1967 if (!switch_root_dir
&& objective
== MANAGER_SOFT_REBOOT
) {
1968 /* If no switch root dir is specified, then check if /run/nextroot/ qualifies and use that */
1969 r
= path_is_os_tree("/run/nextroot");
1970 if (r
< 0 && r
!= -ENOENT
)
1971 log_debug_errno(r
, "Failed to determine if /run/nextroot/ is a valid OS tree, ignoring: %m");
1973 switch_root_dir
= "/run/nextroot";
1976 if (switch_root_dir
) {
1977 r
= switch_root(/* new_root= */ switch_root_dir
,
1978 /* old_root_after= */ NULL
,
1979 /* flags= */ (objective
== MANAGER_SWITCH_ROOT
? SWITCH_ROOT_DESTROY_OLD_ROOT
: 0) |
1980 (objective
== MANAGER_SOFT_REBOOT
? 0 : SWITCH_ROOT_RECURSIVE_RUN
));
1982 log_error_errno(r
, "Failed to switch root, trying to continue: %m");
1985 args_size
= argc
+ 5;
1986 args
= newa(const char*, args_size
);
1988 if (!switch_root_init
) {
1989 char sfd
[STRLEN("--deserialize=") + DECIMAL_STR_MAX(int)];
1991 /* First try to spawn ourselves with the right path, and with full serialization. We do this
1992 * only if the user didn't specify an explicit init to spawn. */
1994 assert(arg_serialization
);
1997 xsprintf(sfd
, "--deserialize=%i", fileno(arg_serialization
));
1999 i
= 1; /* Leave args[0] empty for now. */
2001 /* Put our stuff first to make sure it always gets parsed in case
2002 * we get weird stuff from the kernel cmdline (like --) */
2003 if (IN_SET(objective
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
2004 args
[i
++] = "--switched-root";
2005 args
[i
++] = runtime_scope_cmdline_option_to_string(arg_runtime_scope
);
2008 filter_args(args
, &i
, argv
, argc
);
2012 assert(i
<= args_size
);
2015 * We want valgrind to print its memory usage summary before reexecution. Valgrind won't do
2016 * this is on its own on exec(), but it will do it on exit(). Hence, to ensure we get a
2017 * summary here, fork() off a child, let it exit() cleanly, so that it prints the summary,
2018 * and wait() for it in the parent, before proceeding into the exec().
2020 valgrind_summary_hack();
2022 args
[0] = SYSTEMD_BINARY_PATH
;
2023 (void) execv(args
[0], (char* const*) args
);
2025 if (objective
== MANAGER_REEXECUTE
) {
2026 *ret_error_message
= "Failed to execute our own binary";
2027 return log_error_errno(errno
, "Failed to execute our own binary %s: %m", args
[0]);
2030 log_debug_errno(errno
, "Failed to execute our own binary %s, trying fallback: %m", args
[0]);
2033 /* Try the fallback, if there is any, without any serialization. We pass the original argv[] and
2034 * envp[]. (Well, modulo the ordering changes due to getopt() in argv[], and some cleanups in envp[],
2035 * but let's hope that doesn't matter.) */
2037 arg_serialization
= safe_fclose(arg_serialization
);
2038 fds
= fdset_free(fds
);
2040 /* Reopen the console */
2041 (void) make_console_stdio();
2043 i
= 1; /* Leave args[0] empty for now. */
2044 for (int j
= 1; j
<= argc
; j
++)
2045 args
[i
++] = argv
[j
];
2046 assert(i
<= args_size
);
2048 /* Re-enable any blocked signals, especially important if we switch from initrd to init=... */
2049 (void) reset_all_signal_handlers();
2050 (void) reset_signal_mask();
2051 (void) rlimit_nofile_safe();
2053 if (switch_root_init
) {
2054 args
[0] = switch_root_init
;
2055 (void) execve(args
[0], (char* const*) args
, saved_env
);
2056 log_warning_errno(errno
, "Failed to execute configured init %s, trying fallback: %m", args
[0]);
2059 args
[0] = "/sbin/init";
2060 (void) execv(args
[0], (char* const*) args
);
2063 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
2064 ANSI_HIGHLIGHT_RED
" !! " ANSI_NORMAL
,
2065 "Failed to execute /sbin/init");
2067 *ret_error_message
= "Failed to execute fallback shell";
2069 log_warning("No /sbin/init, trying fallback");
2071 args
[0] = "/bin/sh";
2073 (void) execve(args
[0], (char* const*) args
, saved_env
);
2074 return log_error_errno(errno
, "Failed to execute /bin/sh, giving up: %m");
2076 return log_error_errno(r
, "Failed to execute /sbin/init, giving up: %m");
2079 static int invoke_main_loop(
2081 const struct rlimit
*saved_rlimit_nofile
,
2082 const struct rlimit
*saved_rlimit_memlock
,
2083 int *ret_retval
, /* Return parameters relevant for shutting down */
2084 FDSet
**ret_fds
, /* Return parameters for reexecuting */
2085 char **ret_switch_root_dir
, /* … */
2086 char **ret_switch_root_init
, /* … */
2087 const char **ret_error_message
) {
2092 assert(saved_rlimit_nofile
);
2093 assert(saved_rlimit_memlock
);
2096 assert(ret_switch_root_dir
);
2097 assert(ret_switch_root_init
);
2098 assert(ret_error_message
);
2101 int objective
= manager_loop(m
);
2102 if (objective
< 0) {
2103 *ret_error_message
= "Failed to run main loop";
2104 return log_struct_errno(LOG_EMERG
, objective
,
2105 LOG_MESSAGE("Failed to run main loop: %m"),
2106 "MESSAGE_ID=" SD_MESSAGE_CORE_MAINLOOP_FAILED_STR
);
2109 /* Ensure shutdown timestamp is taken even when bypassing the job engine */
2110 if (IN_SET(objective
,
2111 MANAGER_SOFT_REBOOT
,
2115 MANAGER_POWEROFF
) &&
2116 !dual_timestamp_is_set(m
->timestamps
+ MANAGER_TIMESTAMP_SHUTDOWN_START
))
2117 dual_timestamp_now(m
->timestamps
+ MANAGER_TIMESTAMP_SHUTDOWN_START
);
2119 switch (objective
) {
2121 case MANAGER_RELOAD
: {
2122 LogTarget saved_log_target
;
2123 int saved_log_level
;
2125 manager_send_reloading(m
);
2127 log_info("Reloading...");
2129 /* First, save any overridden log level/target, then parse the configuration file,
2130 * which might change the log level to new settings. */
2132 saved_log_level
= m
->log_level_overridden
? log_get_max_level() : -1;
2133 saved_log_target
= m
->log_target_overridden
? log_get_target() : _LOG_TARGET_INVALID
;
2135 (void) parse_configuration(saved_rlimit_nofile
, saved_rlimit_memlock
);
2137 set_manager_defaults(m
);
2138 set_manager_settings(m
);
2140 update_cpu_affinity(false);
2141 update_numa_policy(false);
2143 if (saved_log_level
>= 0)
2144 manager_override_log_level(m
, saved_log_level
);
2145 if (saved_log_target
>= 0)
2146 manager_override_log_target(m
, saved_log_target
);
2148 if (manager_reload(m
) < 0)
2149 /* Reloading failed before the point of no return.
2150 * Let's continue running as if nothing happened. */
2151 m
->objective
= MANAGER_OK
;
2153 log_info("Reloading finished in " USEC_FMT
" ms.",
2154 usec_sub_unsigned(now(CLOCK_MONOTONIC
), m
->timestamps
[MANAGER_TIMESTAMP_UNITS_LOAD
].monotonic
) / USEC_PER_MSEC
);
2159 case MANAGER_REEXECUTE
:
2161 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2162 * pretty much the same as a reload */
2164 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, false);
2166 *ret_error_message
= "Failed to prepare for reexecution";
2170 log_notice("Reexecuting.");
2172 *ret_retval
= EXIT_SUCCESS
;
2173 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2177 case MANAGER_SWITCH_ROOT
:
2179 manager_send_reloading(m
); /* From the perspective of the manager calling us this is
2180 * pretty much the same as a reload */
2182 manager_set_switching_root(m
, true);
2184 if (!m
->switch_root_init
) {
2185 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, true);
2187 *ret_error_message
= "Failed to prepare for reexecution";
2193 log_notice("Switching root.");
2195 *ret_retval
= EXIT_SUCCESS
;
2197 /* Steal the switch root parameters */
2198 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2199 *ret_switch_root_init
= TAKE_PTR(m
->switch_root_init
);
2203 case MANAGER_SOFT_REBOOT
:
2204 manager_send_reloading(m
);
2205 manager_set_switching_root(m
, true);
2207 r
= prepare_reexecute(m
, &arg_serialization
, ret_fds
, /* switching_root= */ true);
2209 *ret_error_message
= "Failed to prepare for reexecution";
2213 log_notice("Soft-rebooting.");
2215 *ret_retval
= EXIT_SUCCESS
;
2216 *ret_switch_root_dir
= TAKE_PTR(m
->switch_root
);
2217 *ret_switch_root_init
= NULL
;
2222 if (MANAGER_IS_USER(m
)) {
2225 *ret_retval
= m
->return_value
;
2227 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2233 case MANAGER_REBOOT
:
2234 case MANAGER_POWEROFF
:
2236 case MANAGER_KEXEC
: {
2237 log_notice("Shutting down.");
2239 *ret_retval
= m
->return_value
;
2241 *ret_switch_root_dir
= *ret_switch_root_init
= NULL
;
2247 assert_not_reached();
2252 static void log_execution_mode(bool *ret_first_boot
) {
2253 bool first_boot
= false;
2256 assert(ret_first_boot
);
2258 switch (arg_runtime_scope
) {
2260 case RUNTIME_SCOPE_SYSTEM
: {
2264 log_info("systemd " GIT_VERSION
" running in %ssystem mode (%s)",
2265 arg_action
== ACTION_TEST
? "test " : "",
2268 v
= detect_virtualization();
2270 log_info("Detected virtualization %s.", virtualization_to_string(v
));
2272 v
= detect_confidential_virtualization();
2274 log_info("Detected confidential virtualization %s.", confidential_virtualization_to_string(v
));
2276 log_info("Detected architecture %s.", architecture_to_string(uname_architecture()));
2279 log_info("Running in initrd.");
2281 _cleanup_free_
char *id_text
= NULL
;
2283 /* Let's check whether we are in first boot. First, check if an override was
2284 * specified on the kernel command line. If yes, we honour that. */
2286 r
= proc_cmdline_get_bool("systemd.condition_first_boot", /* flags = */ 0, &first_boot
);
2288 log_debug_errno(r
, "Failed to parse systemd.condition_first_boot= kernel command line argument, ignoring: %m");
2291 log_full(first_boot
? LOG_INFO
: LOG_DEBUG
,
2292 "Kernel command line argument says we are %s first boot.",
2293 first_boot
? "in" : "not in");
2295 /* Second, perform autodetection. We use /etc/machine-id as flag file for
2296 * this: If it is missing or contains the value "uninitialized", this is the
2297 * first boot. In other cases, it is not. This allows container managers and
2298 * installers to provision a couple of files in /etc but still permit the
2299 * first-boot initialization to occur. If the container manager wants to
2300 * provision the machine ID it should pass $container_uuid to PID 1. */
2302 r
= read_one_line_file("/etc/machine-id", &id_text
);
2303 if (r
< 0 || streq(id_text
, "uninitialized")) {
2304 if (r
< 0 && r
!= -ENOENT
)
2305 log_warning_errno(r
, "Unexpected error while reading /etc/machine-id, assuming first boot: %m");
2308 log_info("Detected first boot.");
2310 log_debug("Detected initialized system, this is not the first boot.");
2314 assert_se(uname(&uts
) >= 0);
2316 if (strverscmp_improved(uts
.release
, KERNEL_BASELINE_VERSION
) < 0)
2317 log_warning("Warning! Reported kernel version %s is older than systemd's required baseline kernel version %s. "
2318 "Your mileage may vary.", uts
.release
, KERNEL_BASELINE_VERSION
);
2320 log_debug("Kernel version %s, our baseline is %s", uts
.release
, KERNEL_BASELINE_VERSION
);
2325 case RUNTIME_SCOPE_USER
:
2326 if (DEBUG_LOGGING
) {
2327 _cleanup_free_
char *t
= NULL
;
2329 t
= uid_to_name(getuid());
2330 log_debug("systemd " GIT_VERSION
" running in %suser mode for user " UID_FMT
"/%s. (%s)",
2331 arg_action
== ACTION_TEST
? " test" : "",
2332 getuid(), strna(t
), systemd_features
);
2338 assert_not_reached();
2341 *ret_first_boot
= first_boot
;
2344 static int initialize_runtime(
2347 struct rlimit
*saved_rlimit_nofile
,
2348 struct rlimit
*saved_rlimit_memlock
,
2349 const char **ret_error_message
) {
2352 assert(ret_error_message
);
2354 /* Sets up various runtime parameters. Many of these initializations are conditionalized:
2356 * - Some only apply to --system instances
2357 * - Some only apply to --user instances
2358 * - Some only apply when we first start up, but not when we reexecute
2361 if (arg_action
!= ACTION_RUN
)
2364 update_cpu_affinity(skip_setup
);
2365 update_numa_policy(skip_setup
);
2367 switch (arg_runtime_scope
) {
2369 case RUNTIME_SCOPE_SYSTEM
:
2370 /* Make sure we leave a core dump without panicking the kernel. */
2371 install_crash_handler();
2374 /* Pull credentials from various sources into a common credential directory (we do
2375 * this here, before setting up the machine ID, so that we can use credential info
2376 * for setting up the machine ID) */
2377 (void) import_credentials();
2379 (void) os_release_status();
2380 (void) hostname_setup(true);
2381 /* Force transient machine-id on first boot. */
2382 machine_id_setup(/* root= */ NULL
, /* force_transient= */ first_boot
, arg_machine_id
, /* ret_machine_id */ NULL
);
2383 (void) loopback_setup();
2384 bump_unix_max_dgram_qlen();
2385 bump_file_max_and_nr_open();
2387 write_container_id();
2389 /* Copy os-release to the propagate directory, so that we update it for services running
2390 * under RootDirectory=/RootImage= when we do a soft reboot. */
2391 r
= setup_os_release(RUNTIME_SCOPE_SYSTEM
);
2393 log_warning_errno(r
, "Failed to copy os-release for propagation, ignoring: %m");
2396 r
= watchdog_set_device(arg_watchdog_device
);
2398 log_warning_errno(r
, "Failed to set watchdog device to %s, ignoring: %m", arg_watchdog_device
);
2402 case RUNTIME_SCOPE_USER
: {
2403 _cleanup_free_
char *p
= NULL
;
2405 /* Create the runtime directory and place the inaccessible device nodes there, if we run in
2406 * user mode. In system mode mount_setup() already did that. */
2408 r
= xdg_user_runtime_dir(&p
, "/systemd");
2410 *ret_error_message
= "$XDG_RUNTIME_DIR is not set";
2411 return log_struct_errno(LOG_EMERG
, r
,
2412 LOG_MESSAGE("Failed to determine $XDG_RUNTIME_DIR path: %m"),
2413 "MESSAGE_ID=" SD_MESSAGE_CORE_NO_XDGDIR_PATH_STR
);
2416 (void) mkdir_p_label(p
, 0755);
2417 (void) make_inaccessible_nodes(p
, UID_INVALID
, GID_INVALID
);
2418 r
= setup_os_release(RUNTIME_SCOPE_USER
);
2420 log_warning_errno(r
, "Failed to copy os-release for propagation, ignoring: %m");
2425 assert_not_reached();
2428 if (arg_timer_slack_nsec
!= NSEC_INFINITY
)
2429 if (prctl(PR_SET_TIMERSLACK
, arg_timer_slack_nsec
) < 0)
2430 log_warning_errno(errno
, "Failed to adjust timer slack, ignoring: %m");
2432 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2434 if (!cap_test_all(arg_capability_bounding_set
)) {
2435 r
= capability_bounding_set_drop_usermode(arg_capability_bounding_set
);
2437 *ret_error_message
= "Failed to drop capability bounding set of usermode helpers";
2438 return log_struct_errno(LOG_EMERG
, r
,
2439 LOG_MESSAGE("Failed to drop capability bounding set of usermode helpers: %m"),
2440 "MESSAGE_ID=" SD_MESSAGE_CORE_CAPABILITY_BOUNDING_USER_STR
);
2443 r
= capability_bounding_set_drop(arg_capability_bounding_set
, true);
2445 *ret_error_message
= "Failed to drop capability bounding set";
2446 return log_struct_errno(LOG_EMERG
, r
,
2447 LOG_MESSAGE("Failed to drop capability bounding set: %m"),
2448 "MESSAGE_ID=" SD_MESSAGE_CORE_CAPABILITY_BOUNDING_STR
);
2452 if (arg_no_new_privs
) {
2453 if (prctl(PR_SET_NO_NEW_PRIVS
, 1, 0, 0, 0) < 0) {
2454 *ret_error_message
= "Failed to disable new privileges";
2455 return log_struct_errno(LOG_EMERG
, errno
,
2456 LOG_MESSAGE("Failed to disable new privileges: %m"),
2457 "MESSAGE_ID=" SD_MESSAGE_CORE_DISABLE_PRIVILEGES_STR
);
2462 if (arg_syscall_archs
) {
2463 r
= enforce_syscall_archs(arg_syscall_archs
);
2465 *ret_error_message
= "Failed to set syscall architectures";
2470 r
= make_reaper_process(true);
2472 log_warning_errno(r
, "Failed to make us a subreaper, ignoring: %m");
2474 /* Bump up RLIMIT_NOFILE for systemd itself */
2475 (void) bump_rlimit_nofile(saved_rlimit_nofile
);
2476 (void) bump_rlimit_memlock(saved_rlimit_memlock
);
2481 static int do_queue_default_job(
2483 const char **ret_error_message
) {
2485 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2491 if (arg_default_unit
)
2492 unit
= arg_default_unit
;
2493 else if (in_initrd())
2494 unit
= SPECIAL_INITRD_TARGET
;
2496 unit
= SPECIAL_DEFAULT_TARGET
;
2498 log_debug("Activating default unit: %s", unit
);
2500 r
= manager_load_startable_unit_or_warn(m
, unit
, NULL
, &target
);
2501 if (r
< 0 && in_initrd() && !arg_default_unit
) {
2502 /* Fall back to default.target, which we used to always use by default. Only do this if no
2503 * explicit configuration was given. */
2505 log_info("Falling back to " SPECIAL_DEFAULT_TARGET
".");
2507 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_DEFAULT_TARGET
, NULL
, &target
);
2510 log_info("Falling back to " SPECIAL_RESCUE_TARGET
".");
2512 r
= manager_load_startable_unit_or_warn(m
, SPECIAL_RESCUE_TARGET
, NULL
, &target
);
2514 *ret_error_message
= r
== -ERFKILL
? SPECIAL_RESCUE_TARGET
" masked"
2515 : "Failed to load " SPECIAL_RESCUE_TARGET
;
2520 assert(target
->load_state
== UNIT_LOADED
);
2522 r
= manager_add_job(m
, JOB_START
, target
, JOB_ISOLATE
, NULL
, &error
, &job
);
2524 log_debug_errno(r
, "Default target could not be isolated, starting instead: %s", bus_error_message(&error
, r
));
2526 sd_bus_error_free(&error
);
2528 r
= manager_add_job(m
, JOB_START
, target
, JOB_REPLACE
, NULL
, &error
, &job
);
2530 *ret_error_message
= "Failed to start default target";
2531 return log_struct_errno(LOG_EMERG
, r
,
2532 LOG_MESSAGE("Failed to start default target: %s", bus_error_message(&error
, r
)),
2533 "MESSAGE_ID=" SD_MESSAGE_CORE_START_TARGET_FAILED_STR
);
2537 *ret_error_message
= "Failed to isolate default target";
2538 return log_struct_errno(LOG_EMERG
, r
,
2539 LOG_MESSAGE("Failed to isolate default target: %s", bus_error_message(&error
, r
)),
2540 "MESSAGE_ID=" SD_MESSAGE_CORE_ISOLATE_TARGET_FAILED_STR
);
2542 log_info("Queued %s job for default target %s.",
2543 job_type_to_string(job
->type
),
2544 unit_status_string(job
->unit
, NULL
));
2546 m
->default_unit_job_id
= job
->id
;
2551 static void save_rlimits(struct rlimit
*saved_rlimit_nofile
,
2552 struct rlimit
*saved_rlimit_memlock
) {
2554 assert(saved_rlimit_nofile
);
2555 assert(saved_rlimit_memlock
);
2557 if (getrlimit(RLIMIT_NOFILE
, saved_rlimit_nofile
) < 0)
2558 log_warning_errno(errno
, "Reading RLIMIT_NOFILE failed, ignoring: %m");
2560 if (getrlimit(RLIMIT_MEMLOCK
, saved_rlimit_memlock
) < 0)
2561 log_warning_errno(errno
, "Reading RLIMIT_MEMLOCK failed, ignoring: %m");
2564 static void fallback_rlimit_nofile(const struct rlimit
*saved_rlimit_nofile
) {
2567 if (arg_defaults
.rlimit
[RLIMIT_NOFILE
])
2570 /* Make sure forked processes get limits based on the original kernel setting */
2572 rl
= newdup(struct rlimit
, saved_rlimit_nofile
, 1);
2578 /* Bump the hard limit for system services to a substantially higher value. The default
2579 * hard limit current kernels set is pretty low (4K), mostly for historical
2580 * reasons. According to kernel developers, the fd handling in recent kernels has been
2581 * optimized substantially enough, so that we can bump the limit now, without paying too
2582 * high a price in memory or performance. Note however that we only bump the hard limit,
2583 * not the soft limit. That's because select() works the way it works, and chokes on fds
2584 * >= 1024. If we'd bump the soft limit globally, it might accidentally happen to
2585 * unexpecting programs that they get fds higher than what they can process using
2586 * select(). By only bumping the hard limit but leaving the low limit as it is we avoid
2587 * this pitfall: programs that are written by folks aware of the select() problem in mind
2588 * (and thus use poll()/epoll instead of select(), the way everybody should) can
2589 * explicitly opt into high fds by bumping their soft limit beyond 1024, to the hard limit
2591 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2594 /* Get the underlying absolute limit the kernel enforces */
2595 nr
= read_nr_open();
2597 rl
->rlim_max
= MIN((rlim_t
) nr
, MAX(rl
->rlim_max
, (rlim_t
) HIGH_RLIMIT_NOFILE
));
2600 /* If for some reason we were invoked with a soft limit above 1024 (which should never
2601 * happen!, but who knows what we get passed in from pam_limit when invoked as --user
2602 * instance), then lower what we pass on to not confuse our children */
2603 rl
->rlim_cur
= MIN(rl
->rlim_cur
, (rlim_t
) FD_SETSIZE
);
2605 arg_defaults
.rlimit
[RLIMIT_NOFILE
] = rl
;
2608 static void fallback_rlimit_memlock(const struct rlimit
*saved_rlimit_memlock
) {
2611 /* Pass the original value down to invoked processes */
2613 if (arg_defaults
.rlimit
[RLIMIT_MEMLOCK
])
2616 rl
= newdup(struct rlimit
, saved_rlimit_memlock
, 1);
2622 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2623 /* Raise the default limit to 8M also on old kernels and in containers (8M is the kernel
2624 * default for this since kernel 5.16) */
2625 rl
->rlim_max
= MAX(rl
->rlim_max
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2626 rl
->rlim_cur
= MAX(rl
->rlim_cur
, (rlim_t
) DEFAULT_RLIMIT_MEMLOCK
);
2629 arg_defaults
.rlimit
[RLIMIT_MEMLOCK
] = rl
;
2632 static void setenv_manager_environment(void) {
2635 STRV_FOREACH(p
, arg_manager_environment
) {
2636 log_debug("Setting '%s' in our own environment.", *p
);
2638 r
= putenv_dup(*p
, true);
2640 log_warning_errno(r
, "Failed to setenv \"%s\", ignoring: %m", *p
);
2644 static void reset_arguments(void) {
2645 /* Frees/resets arg_* variables, with a few exceptions commented below. */
2647 arg_default_unit
= mfree(arg_default_unit
);
2649 /* arg_runtime_scope — ignore */
2651 arg_dump_core
= true;
2652 arg_crash_chvt
= -1;
2653 arg_crash_shell
= false;
2654 arg_crash_action
= CRASH_FREEZE
;
2655 arg_confirm_spawn
= mfree(arg_confirm_spawn
);
2656 arg_show_status
= _SHOW_STATUS_INVALID
;
2657 arg_status_unit_format
= STATUS_UNIT_FORMAT_DEFAULT
;
2658 arg_switched_root
= false;
2659 arg_pager_flags
= 0;
2660 arg_service_watchdogs
= true;
2662 unit_defaults_done(&arg_defaults
);
2663 unit_defaults_init(&arg_defaults
, arg_runtime_scope
);
2665 arg_runtime_watchdog
= 0;
2666 arg_reboot_watchdog
= 10 * USEC_PER_MINUTE
;
2667 arg_kexec_watchdog
= 0;
2668 arg_pretimeout_watchdog
= 0;
2669 arg_early_core_pattern
= mfree(arg_early_core_pattern
);
2670 arg_watchdog_device
= mfree(arg_watchdog_device
);
2671 arg_watchdog_pretimeout_governor
= mfree(arg_watchdog_pretimeout_governor
);
2673 arg_default_environment
= strv_free(arg_default_environment
);
2674 arg_manager_environment
= strv_free(arg_manager_environment
);
2676 arg_capability_bounding_set
= CAP_MASK_UNSET
;
2677 arg_no_new_privs
= false;
2678 arg_protect_system
= -1;
2679 arg_timer_slack_nsec
= NSEC_INFINITY
;
2681 arg_syscall_archs
= set_free(arg_syscall_archs
);
2683 /* arg_serialization — ignore */
2685 arg_machine_id
= (sd_id128_t
) {};
2686 arg_cad_burst_action
= EMERGENCY_ACTION_REBOOT_FORCE
;
2688 cpu_set_reset(&arg_cpu_affinity
);
2689 numa_policy_reset(&arg_numa_policy
);
2691 arg_random_seed
= mfree(arg_random_seed
);
2692 arg_random_seed_size
= 0;
2695 arg_reload_limit_interval_sec
= 0;
2696 arg_reload_limit_burst
= 0;
2699 static void determine_default_oom_score_adjust(void) {
2702 /* Run our services at slightly higher OOM score than ourselves. But let's be conservative here, and
2703 * do this only if we don't run as root (i.e. only if we are run in user mode, for an unprivileged
2706 if (arg_defaults
.oom_score_adjust_set
)
2712 r
= get_oom_score_adjust(&a
);
2714 return (void) log_warning_errno(r
, "Failed to determine current OOM score adjustment value, ignoring: %m");
2716 assert_cc(100 <= OOM_SCORE_ADJ_MAX
);
2717 b
= a
>= OOM_SCORE_ADJ_MAX
- 100 ? OOM_SCORE_ADJ_MAX
: a
+ 100;
2722 arg_defaults
.oom_score_adjust
= b
;
2723 arg_defaults
.oom_score_adjust_set
= true;
2726 static int parse_configuration(const struct rlimit
*saved_rlimit_nofile
,
2727 const struct rlimit
*saved_rlimit_memlock
) {
2730 assert(saved_rlimit_nofile
);
2731 assert(saved_rlimit_memlock
);
2733 /* Assign configuration defaults */
2736 r
= parse_config_file();
2738 log_warning_errno(r
, "Failed to parse config file, ignoring: %m");
2740 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
) {
2741 r
= proc_cmdline_parse(parse_proc_cmdline_item
, NULL
, 0);
2743 log_warning_errno(r
, "Failed to parse kernel command line, ignoring: %m");
2746 /* Initialize some default rlimits for services if they haven't been configured */
2747 fallback_rlimit_nofile(saved_rlimit_nofile
);
2748 fallback_rlimit_memlock(saved_rlimit_memlock
);
2750 /* Note that this also parses bits from the kernel command line, including "debug". */
2751 log_parse_environment();
2753 /* Initialize the show status setting if it hasn't been set explicitly yet */
2754 if (arg_show_status
== _SHOW_STATUS_INVALID
)
2755 arg_show_status
= SHOW_STATUS_YES
;
2757 /* Slightly raise the OOM score for our services if we are running for unprivileged users. */
2758 determine_default_oom_score_adjust();
2760 /* Push variables into the manager environment block */
2761 setenv_manager_environment();
2763 /* Parse log environment variables again to take into account any new environment variables. */
2764 log_parse_environment();
2769 static int safety_checks(void) {
2771 if (getpid_cached() == 1 &&
2772 arg_action
!= ACTION_RUN
)
2773 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2774 "Unsupported execution mode while PID 1.");
2776 if (getpid_cached() == 1 &&
2777 arg_runtime_scope
== RUNTIME_SCOPE_USER
)
2778 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2779 "Can't run --user mode as PID 1.");
2781 if (arg_action
== ACTION_RUN
&&
2782 arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
2783 getpid_cached() != 1)
2784 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2785 "Can't run system mode unless PID 1.");
2787 if (arg_action
== ACTION_TEST
&&
2789 return log_error_errno(SYNTHETIC_ERRNO(EPERM
),
2790 "Don't run test mode as root.");
2792 switch (arg_runtime_scope
) {
2794 case RUNTIME_SCOPE_USER
:
2796 if (arg_action
== ACTION_RUN
&&
2798 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2799 "Trying to run as user instance, but the system has not been booted with systemd.");
2801 if (arg_action
== ACTION_RUN
&&
2802 !getenv("XDG_RUNTIME_DIR"))
2803 return log_error_errno(SYNTHETIC_ERRNO(EUNATCH
),
2804 "Trying to run as user instance, but $XDG_RUNTIME_DIR is not set.");
2808 case RUNTIME_SCOPE_SYSTEM
:
2809 if (arg_action
== ACTION_RUN
&&
2810 running_in_chroot() > 0)
2811 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP
),
2812 "Cannot be run in a chroot() environment.");
2816 assert_not_reached();
2822 static int initialize_security(
2823 bool *loaded_policy
,
2824 dual_timestamp
*security_start_timestamp
,
2825 dual_timestamp
*security_finish_timestamp
,
2826 const char **ret_error_message
) {
2830 assert(loaded_policy
);
2831 assert(security_start_timestamp
);
2832 assert(security_finish_timestamp
);
2833 assert(ret_error_message
);
2835 dual_timestamp_now(security_start_timestamp
);
2837 r
= mac_selinux_setup(loaded_policy
);
2839 *ret_error_message
= "Failed to load SELinux policy";
2843 r
= mac_smack_setup(loaded_policy
);
2845 *ret_error_message
= "Failed to load SMACK policy";
2849 r
= mac_apparmor_setup();
2851 *ret_error_message
= "Failed to load AppArmor policy";
2857 *ret_error_message
= "Failed to load IMA policy";
2861 dual_timestamp_now(security_finish_timestamp
);
2865 static int collect_fds(FDSet
**ret_fds
, const char **ret_error_message
) {
2869 assert(ret_error_message
);
2871 /* Pick up all fds passed to us. We apply a filter here: we only take the fds that have O_CLOEXEC
2872 * off. All fds passed via execve() to us must have O_CLOEXEC off, and our own code and dependencies
2873 * should be clean enough to set O_CLOEXEC universally. Thus checking the bit should be a safe
2874 * mechanism to distinguish passed in fds from our own.
2876 * Why bother? Some subsystems we initialize early, specifically selinux might keep fds open in our
2877 * process behind our back. We should not take possession of that (and then accidentally close
2878 * it). SELinux thankfully sets O_CLOEXEC on its fds, so this test should work. */
2879 r
= fdset_new_fill(/* filter_cloexec= */ 0, ret_fds
);
2881 *ret_error_message
= "Failed to allocate fd set";
2882 return log_struct_errno(LOG_EMERG
, r
,
2883 LOG_MESSAGE("Failed to allocate fd set: %m"),
2884 "MESSAGE_ID=" SD_MESSAGE_CORE_FD_SET_FAILED_STR
);
2887 /* The serialization fd should have O_CLOEXEC turned on already, let's verify that we didn't pick it up here */
2888 assert_se(!arg_serialization
|| !fdset_contains(*ret_fds
, fileno(arg_serialization
)));
2893 static void setup_console_terminal(bool skip_setup
) {
2895 if (arg_runtime_scope
!= RUNTIME_SCOPE_SYSTEM
)
2898 /* Become a session leader if we aren't one yet. */
2901 /* If we are init, we connect stdin/stdout/stderr to /dev/null and make sure we don't have a
2902 * controlling tty. */
2903 (void) release_terminal();
2905 /* Reset the console, but only if this is really init and we are freshly booted */
2906 if (getpid_cached() == 1 && !skip_setup
)
2907 (void) console_setup();
2910 static bool early_skip_setup_check(int argc
, char *argv
[]) {
2911 bool found_deserialize
= false;
2913 /* Determine if this is a reexecution or normal bootup. We do the full command line parsing much
2914 * later, so let's just have a quick peek here. Note that if we have switched root, do all the
2915 * special setup things anyway, even if in that case we also do deserialization. */
2917 for (int i
= 1; i
< argc
; i
++)
2918 if (streq(argv
[i
], "--switched-root"))
2919 return false; /* If we switched root, don't skip the setup. */
2920 else if (startswith(argv
[i
], "--deserialize=") || streq(argv
[i
], "--deserialize"))
2921 found_deserialize
= true;
2923 return found_deserialize
; /* When we are deserializing, then we are reexecuting, hence avoid the extensive setup */
2926 static int save_env(void) {
2929 l
= strv_copy(environ
);
2933 strv_free_and_replace(saved_env
, l
);
2937 int main(int argc
, char *argv
[]) {
2939 initrd_timestamp
= DUAL_TIMESTAMP_NULL
,
2940 userspace_timestamp
= DUAL_TIMESTAMP_NULL
,
2941 kernel_timestamp
= DUAL_TIMESTAMP_NULL
,
2942 security_start_timestamp
= DUAL_TIMESTAMP_NULL
,
2943 security_finish_timestamp
= DUAL_TIMESTAMP_NULL
;
2944 struct rlimit saved_rlimit_nofile
= RLIMIT_MAKE_CONST(0),
2945 saved_rlimit_memlock
= RLIMIT_MAKE_CONST(RLIM_INFINITY
); /* The original rlimits we passed
2946 * in. Note we use different values
2947 * for the two that indicate whether
2948 * these fields are initialized! */
2949 bool skip_setup
, loaded_policy
= false, queue_default_job
= false, first_boot
= false;
2950 char *switch_root_dir
= NULL
, *switch_root_init
= NULL
;
2951 usec_t before_startup
, after_startup
;
2952 static char systemd
[] = "systemd";
2953 const char *error_message
= NULL
;
2954 int r
, retval
= EXIT_FAILURE
;
2958 assert_se(argc
> 0 && !isempty(argv
[0]));
2960 /* SysV compatibility: redirect init → telinit */
2961 redirect_telinit(argc
, argv
);
2963 /* Take timestamps early on */
2964 dual_timestamp_from_monotonic(&kernel_timestamp
, 0);
2965 dual_timestamp_now(&userspace_timestamp
);
2967 /* Figure out whether we need to do initialize the system, or if we already did that because we are
2969 skip_setup
= early_skip_setup_check(argc
, argv
);
2971 /* If we get started via the /sbin/init symlink then we are called 'init'. After a subsequent
2972 * reexecution we are then called 'systemd'. That is confusing, hence let's call us systemd
2974 program_invocation_short_name
= systemd
;
2975 (void) prctl(PR_SET_NAME
, systemd
);
2977 /* Save the original command line */
2978 save_argc_argv(argc
, argv
);
2980 /* Save the original environment as we might need to restore it if we're requested to execute another
2981 * system manager later. */
2984 error_message
= "Failed to copy environment block";
2988 /* Make sure that if the user says "syslog" we actually log to the journal. */
2989 log_set_upgrade_syslog_to_journal(true);
2991 if (getpid_cached() == 1) {
2992 /* When we run as PID 1 force system mode */
2993 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
2995 /* Disable the umask logic */
2998 /* Make sure that at least initially we do not ever log to journald/syslogd, because it might
2999 * not be activated yet (even though the log socket for it exists). */
3000 log_set_prohibit_ipc(true);
3002 /* Always reopen /dev/console when running as PID 1 or one of its pre-execve() children. This
3003 * is important so that we never end up logging to any foreign stderr, for example if we have
3004 * to log in a child process right before execve()'ing the actual binary, at a point in time
3005 * where socket activation stderr/stdout area already set up. */
3006 log_set_always_reopen_console(true);
3008 if (detect_container() <= 0) {
3010 /* Running outside of a container as PID 1 */
3011 log_set_target_and_open(LOG_TARGET_KMSG
);
3014 initrd_timestamp
= userspace_timestamp
;
3017 r
= mount_setup_early();
3019 error_message
= "Failed to mount early API filesystems";
3024 /* We might have just mounted /proc, so let's try to parse the kernel
3025 * command line log arguments immediately. */
3026 log_parse_environment();
3028 /* Let's open the log backend a second time, in case the first time didn't
3029 * work. Quite possibly we have mounted /dev just now, so /dev/kmsg became
3030 * available, and it previously wasn't. */
3034 disable_printk_ratelimit();
3036 r
= initialize_security(
3038 &security_start_timestamp
,
3039 &security_finish_timestamp
,
3045 if (mac_init() < 0) {
3046 error_message
= "Failed to initialize MAC support";
3053 /* Set the default for later on, but don't actually open the logs like this for
3054 * now. Note that if we are transitioning from the initrd there might still be
3055 * journal fd open, and we shouldn't attempt opening that before we parsed
3056 * /proc/cmdline which might redirect output elsewhere. */
3057 log_set_target(LOG_TARGET_JOURNAL_OR_KMSG
);
3060 /* Running inside a container, as PID 1 */
3061 log_set_target_and_open(LOG_TARGET_CONSOLE
);
3063 /* For later on, see above... */
3064 log_set_target(LOG_TARGET_JOURNAL
);
3066 /* clear the kernel timestamp, because we are in a container */
3067 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
3070 initialize_coredump(skip_setup
);
3072 r
= fixup_environment();
3074 log_struct_errno(LOG_EMERG
, r
,
3075 LOG_MESSAGE("Failed to fix up PID 1 environment: %m"),
3076 "MESSAGE_ID=" SD_MESSAGE_CORE_PID1_ENVIRONMENT_STR
);
3077 error_message
= "Failed to fix up PID1 environment";
3081 /* Try to figure out if we can use colors with the console. No need to do that for user
3082 * instances since they never log into the console. */
3083 log_show_color(colors_enabled());
3085 r
= make_null_stdio();
3087 log_warning_errno(r
, "Failed to redirect standard streams to /dev/null, ignoring: %m");
3089 /* Load the kernel modules early. */
3091 (void) kmod_setup();
3093 /* Mount /proc, /sys and friends, so that /proc/cmdline and /proc/$PID/fd is available. */
3094 r
= mount_setup(loaded_policy
, skip_setup
);
3096 error_message
= "Failed to mount API filesystems";
3101 /* Before we actually start deleting cgroup v1 code, make it harder to boot
3102 * in cgroupv1 mode first. See also #30852. */
3104 r
= mount_cgroup_legacy_controllers(loaded_policy
);
3107 error_message
= "Refusing to run under cgroup v1, SYSTEMD_CGROUP_ENABLE_LEGACY_FORCE=1 not specified on kernel command line";
3109 error_message
= "Failed to mount cgroup v1 hierarchy";
3113 log_full(LOG_CRIT
, "Legacy cgroup v1 support selected. This is no longer supported. Will proceed anyway after 30s.");
3114 (void) usleep_safe(30 * USEC_PER_SEC
);
3118 /* The efivarfs is now mounted, let's lock down the system token. */
3119 lock_down_efi_variables();
3121 /* Cache command-line options passed from EFI variables */
3123 (void) cache_efi_options_variable();
3125 /* Running as user instance */
3126 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
3127 log_set_always_reopen_console(true);
3128 log_set_target_and_open(LOG_TARGET_AUTO
);
3130 /* clear the kernel timestamp, because we are not PID 1 */
3131 kernel_timestamp
= DUAL_TIMESTAMP_NULL
;
3133 /* Clear ambient capabilities, so services do not inherit them implicitly. Dropping them does
3134 * not affect the permitted and effective sets which are important for the manager itself to
3136 capability_ambient_set_apply(0, /* also_inherit= */ false);
3138 if (mac_init() < 0) {
3139 error_message
= "Failed to initialize MAC support";
3144 /* Save the original RLIMIT_NOFILE/RLIMIT_MEMLOCK so that we can reset it later when
3145 * transitioning from the initrd to the main systemd or suchlike. */
3146 save_rlimits(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
3148 /* Reset all signal handlers. */
3149 (void) reset_all_signal_handlers();
3150 (void) ignore_signals(SIGNALS_IGNORE
);
3152 (void) parse_configuration(&saved_rlimit_nofile
, &saved_rlimit_memlock
);
3154 r
= parse_argv(argc
, argv
);
3156 error_message
= "Failed to parse command line arguments";
3160 r
= safety_checks();
3164 if (IN_SET(arg_action
, ACTION_TEST
, ACTION_HELP
, ACTION_DUMP_CONFIGURATION_ITEMS
, ACTION_DUMP_BUS_PROPERTIES
, ACTION_BUS_INTROSPECT
))
3165 pager_open(arg_pager_flags
);
3167 if (arg_action
!= ACTION_RUN
)
3170 if (arg_action
== ACTION_HELP
) {
3171 retval
= help() < 0 ? EXIT_FAILURE
: EXIT_SUCCESS
;
3173 } else if (arg_action
== ACTION_VERSION
) {
3176 } else if (arg_action
== ACTION_DUMP_CONFIGURATION_ITEMS
) {
3177 unit_dump_config_items(stdout
);
3178 retval
= EXIT_SUCCESS
;
3180 } else if (arg_action
== ACTION_DUMP_BUS_PROPERTIES
) {
3181 dump_bus_properties(stdout
);
3182 retval
= EXIT_SUCCESS
;
3184 } else if (arg_action
== ACTION_BUS_INTROSPECT
) {
3185 r
= bus_manager_introspect_implementations(stdout
, arg_bus_introspect
);
3186 retval
= r
>= 0 ? EXIT_SUCCESS
: EXIT_FAILURE
;
3190 assert_se(IN_SET(arg_action
, ACTION_RUN
, ACTION_TEST
));
3192 /* Move out of the way, so that we won't block unmounts */
3193 assert_se(chdir("/") == 0);
3195 if (arg_action
== ACTION_RUN
) {
3197 /* Apply the systemd.clock_usec= kernel command line switch */
3198 apply_clock_update();
3200 /* Apply random seed from kernel command line */
3201 cmdline_take_random_seed();
3204 /* A core pattern might have been specified via the cmdline. */
3205 initialize_core_pattern(skip_setup
);
3207 /* Make /usr/ read-only */
3208 apply_protect_system(skip_setup
);
3210 /* Close logging fds, in order not to confuse collecting passed fds and terminal logic below */
3213 /* Remember open file descriptors for later deserialization */
3214 r
= collect_fds(&fds
, &error_message
);
3218 /* Give up any control of the console, but make sure its initialized. */
3219 setup_console_terminal(skip_setup
);
3221 /* Open the logging devices, if possible and necessary */
3225 log_execution_mode(&first_boot
);
3227 r
= initialize_runtime(skip_setup
,
3229 &saved_rlimit_nofile
,
3230 &saved_rlimit_memlock
,
3235 r
= manager_new(arg_runtime_scope
,
3236 arg_action
== ACTION_TEST
? MANAGER_TEST_FULL
: 0,
3239 log_struct_errno(LOG_EMERG
, r
,
3240 LOG_MESSAGE("Failed to allocate manager object: %m"),
3241 "MESSAGE_ID=" SD_MESSAGE_CORE_MANAGER_ALLOCATE_STR
);
3242 error_message
= "Failed to allocate manager object";
3246 m
->timestamps
[MANAGER_TIMESTAMP_KERNEL
] = kernel_timestamp
;
3247 m
->timestamps
[MANAGER_TIMESTAMP_INITRD
] = initrd_timestamp
;
3248 m
->timestamps
[MANAGER_TIMESTAMP_USERSPACE
] = userspace_timestamp
;
3249 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_START
)] = security_start_timestamp
;
3250 m
->timestamps
[manager_timestamp_initrd_mangle(MANAGER_TIMESTAMP_SECURITY_FINISH
)] = security_finish_timestamp
;
3252 set_manager_defaults(m
);
3253 set_manager_settings(m
);
3254 manager_set_first_boot(m
, first_boot
);
3255 manager_set_switching_root(m
, arg_switched_root
);
3257 /* Remember whether we should queue the default job */
3258 queue_default_job
= !arg_serialization
|| arg_switched_root
;
3260 before_startup
= now(CLOCK_MONOTONIC
);
3262 r
= manager_startup(m
, arg_serialization
, fds
, /* root= */ NULL
);
3264 error_message
= "Failed to start up manager";
3268 /* This will close all file descriptors that were opened, but not claimed by any unit. */
3269 fds
= fdset_free(fds
);
3270 arg_serialization
= safe_fclose(arg_serialization
);
3272 if (queue_default_job
) {
3273 r
= do_queue_default_job(m
, &error_message
);
3278 after_startup
= now(CLOCK_MONOTONIC
);
3280 log_full(arg_action
== ACTION_TEST
? LOG_INFO
: LOG_DEBUG
,
3281 "Loaded units and determined initial transaction in %s.",
3282 FORMAT_TIMESPAN(after_startup
- before_startup
, 100 * USEC_PER_MSEC
));
3284 if (arg_action
== ACTION_TEST
) {
3285 manager_test_summary(m
);
3286 retval
= EXIT_SUCCESS
;
3290 r
= invoke_main_loop(m
,
3291 &saved_rlimit_nofile
,
3292 &saved_rlimit_memlock
,
3298 assert(r
< 0 || IN_SET(r
, MANAGER_EXIT
, /* MANAGER_OK is not expected here. */
3302 MANAGER_SOFT_REBOOT
,
3306 MANAGER_SWITCH_ROOT
));
3312 arg_reboot_watchdog
= manager_get_watchdog(m
, WATCHDOG_REBOOT
);
3313 arg_kexec_watchdog
= manager_get_watchdog(m
, WATCHDOG_KEXEC
);
3314 m
= manager_free(m
);
3317 mac_selinux_finish();
3319 if (IN_SET(r
, MANAGER_REEXECUTE
, MANAGER_SWITCH_ROOT
, MANAGER_SOFT_REBOOT
))
3322 &saved_rlimit_nofile
,
3323 &saved_rlimit_memlock
,
3327 &error_message
); /* This only returns if reexecution failed */
3329 arg_serialization
= safe_fclose(arg_serialization
);
3330 fds
= fdset_free(fds
);
3332 saved_env
= strv_free(saved_env
);
3334 #if HAVE_VALGRIND_VALGRIND_H
3335 /* If we are PID 1 and running under valgrind, then let's exit
3336 * here explicitly. valgrind will only generate nice output on
3337 * exit(), not on exec(), hence let's do the former not the
3339 if (getpid_cached() == 1 && RUNNING_ON_VALGRIND
) {
3340 /* Cleanup watchdog_device strings for valgrind. We need them
3341 * in become_shutdown() so normally we cannot free them yet. */
3342 watchdog_free_device();
3348 #if HAS_FEATURE_ADDRESS_SANITIZER
3349 /* At this stage we most likely don't have stdio/stderr open, so the following
3350 * LSan check would not print any actionable information and would just crash
3351 * PID 1. To make this a bit more helpful, let's try to open /dev/console,
3352 * and if we succeed redirect LSan's report there. */
3353 if (getpid_cached() == 1) {
3354 _cleanup_close_
int tty_fd
= -EBADF
;
3356 tty_fd
= open_terminal("/dev/console", O_WRONLY
|O_NOCTTY
|O_CLOEXEC
);
3358 __sanitizer_set_report_fd((void*) (intptr_t) tty_fd
);
3360 __lsan_do_leak_check();
3365 (void) sd_notifyf(/* unset_environment= */ false,
3368 /* Try to invoke the shutdown binary unless we already failed.
3369 * If we failed above, we want to freeze after finishing cleanup. */
3370 if (arg_runtime_scope
== RUNTIME_SCOPE_SYSTEM
&&
3371 IN_SET(r
, MANAGER_EXIT
, MANAGER_REBOOT
, MANAGER_POWEROFF
, MANAGER_HALT
, MANAGER_KEXEC
)) {
3372 r
= become_shutdown(r
, retval
);
3373 log_error_errno(r
, "Failed to execute shutdown binary, %s: %m", getpid_cached() == 1 ? "freezing" : "quitting");
3374 error_message
= "Failed to execute shutdown binary";
3377 /* This is primarily useful when running systemd in a VM, as it provides the user running the VM with
3378 * a mechanism to pick up systemd's exit status in the VM. */
3379 (void) sd_notifyf(/* unset_environment= */ false,
3380 "EXIT_STATUS=%i", retval
);
3382 watchdog_free_device();
3383 arg_watchdog_device
= mfree(arg_watchdog_device
);
3385 if (getpid_cached() == 1) {
3387 manager_status_printf(NULL
, STATUS_TYPE_EMERGENCY
,
3388 ANSI_HIGHLIGHT_RED
"!!!!!!" ANSI_NORMAL
,
3389 "%s.", error_message
);
3390 freeze_or_exit_or_reboot();