HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/core/main.c
Git blob: 7887e0f02d9696e736ccfb06986d5d50dcb1cfc6
Lines 1001–2000 of 4,044
m->event_loop_ratelimit.interval = arg_event_loop_ratelimit_interval_sec;
m->event_loop_ratelimit.burst = arg_event_loop_ratelimit_burst;
manager_set_watchdog(m, WATCHDOG_RUNTIME, arg_runtime_watchdog);
manager_set_watchdog(m, WATCHDOG_REBOOT, arg_reboot_watchdog);
manager_set_watchdog(m, WATCHDOG_KEXEC, arg_kexec_watchdog);
manager_set_watchdog(m, WATCHDOG_PRETIMEOUT, arg_pretimeout_watchdog);
r = manager_set_watchdog_pretimeout_governor(m, arg_watchdog_pretimeout_governor);
if (r < 0)
log_warning_errno(r, "Failed to set watchdog pretimeout governor to '%s', ignoring: %m", arg_watchdog_pretimeout_governor);
manager_set_show_status(m, arg_show_status, "command line");
m->status_unit_format = arg_status_unit_format;
m->restrict_filesystem_access = arg_restrict_filesystem_access;
}
static int redirect_telinit(char *argv[], char **args) {
/* Check if we are invoked through the legacy interface, where init would be symlinked as telinit
* and allow users to call 'init 0' and such. If we detect such use, tell the user that this is not
* supported anymore. */
if (getpid_cached() == 1 || !invoked_as(argv, "init"))
return 0;
/* Check if the user specified one of the telinit commands in args. */
if (!strv_overlap(args,
STRV_MAKE("0", "1", "2", "3", "4", "5", "6",
"s", "S", "q", "Q", "u", "U")))
return 0;
_cleanup_free_ char *a = NULL, *b = NULL, *c = NULL;
(void) terminal_urlify_man_full("shutdown", "8", /* suffix= */ NULL, &a);
(void) terminal_urlify_man_full("reboot", "8", /* suffix= */ NULL, &b);
(void) terminal_urlify_man_full("systemctl", "1", /* suffix= */ NULL, &c);
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"Program 'systemd' called as 'init' with a legacy telinit command.\n"
"Call %s, %s, or %s instead.",
strnull(a), strnull(b), strnull(c));
}
COMMAND(
"systemd\0",
"Start and monitor system and user services.",
.man_pages = "systemd(1)\0",
.option_namespace = "systemd",
.pager_flags = &arg_pager_flags,
);
static int parse_argv(int argc, char *argv[]) {
bool user_arg_seen = false;
int r;
assert(argc >= 1);
assert(argv);
int log_level_shift = getpid_cached() == 1 ? LOG_DEBUG - LOG_ERR : 0;
OptionParser opts = {
argc, argv,
.namespace = "systemd",
.log_level_shift = log_level_shift,
};
/* Note: when new options are added here, also add them to the exclusion list in proc-cmdline.c! */
FOREACH_OPTION(c, &opts)
switch (c) {
OPTION_NAMESPACE("systemd"): {}
OPTION_COMMON_HELP:
arg_action = ACTION_HELP;
break;
OPTION_COMMON_VERSION:
arg_action = ACTION_VERSION;
break;
OPTION_COMMON_INTROSPECT_CLI:
arg_action = ACTION_INTROSPECT_CLI;
break;
OPTION_LONG("test", NULL, "Determine initial transaction, dump it and exit"):
arg_action = ACTION_TEST;
break;
OPTION_LONG("system", NULL, "Combined with --test: operate in system mode"):
arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
break;
OPTION_LONG("user", NULL, "Combined with --test: operate in user mode"):
arg_runtime_scope = RUNTIME_SCOPE_USER;
user_arg_seen = true;
break;
OPTION_LONG("dump-configuration-items", NULL, "Dump understood unit configuration items"):
arg_action = ACTION_DUMP_CONFIGURATION_ITEMS;
break;
OPTION_LONG("dump-bus-properties", NULL, "Dump exposed bus properties"):
arg_action = ACTION_DUMP_BUS_PROPERTIES;
break;
OPTION_LONG("bus-introspect", "PATH", "Write XML introspection data"):
arg_bus_introspect = opts.arg;
arg_action = ACTION_BUS_INTROSPECT;
break;
OPTION_LONG("unit", "UNIT", "Set default unit"):
r = free_and_strdup(&arg_default_unit, opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to set default unit \"%s\": %m", opts.arg);
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "dump-core", "BOOL", "Dump core on crash"):
r = parse_boolean_argument("--dump-core", opts.arg, &arg_dump_core);
if (r < 0)
return r;
break;
OPTION_LONG("crash-chvt", "NR", "Change to specified VT on crash"): {}
OPTION_LONG("crash-vt", "NR", /* help= */ NULL): /* compat option that was previously documented in --help */
r = parse_crash_chvt(opts.arg, &arg_crash_chvt);
if (r < 0)
return log_error_errno(r, "Failed to parse crash virtual terminal index '%s': %m",
opts.arg);
break;
OPTION_LONG("crash-action", "ACTION", "Specify what to do on crash"):
r = crash_action_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse crash action \"%s\": %m", opts.arg);
arg_crash_action = r;
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "crash-shell", "BOOL", "Run shell on crash"):
r = parse_boolean_argument("--crash-shell", opts.arg, &arg_crash_shell);
if (r < 0)
return r;
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "confirm-spawn", "BOOL",
"Ask for confirmation when spawning processes"):
arg_confirm_spawn = mfree(arg_confirm_spawn);
r = parse_confirm_spawn(opts.arg, &arg_confirm_spawn);
if (r < 0)
return log_error_errno(r, "Failed to parse confirm spawn option: \"%s\": %m",
opts.arg);
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "show-status", "BOOL",
"Show status updates on the console during boot"):
if (opts.arg) {
r = parse_show_status(opts.arg, &arg_show_status);
if (r < 0)
return log_error_errno(r, "Failed to parse show status boolean: \"%s\": %m",
opts.arg);
} else
arg_show_status = SHOW_STATUS_YES;
break;
OPTION_LONG("log-target", "TARGET",
"Set log target (console, journal, kmsg, journal-or-kmsg, null)"):
r = log_set_target_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse log target \"%s\": %m", opts.arg);
break;
OPTION_LONG("log-level", "LEVEL",
"Set log level (debug, info, notice, warning, err, crit, alert, emerg)"):
r = log_set_max_level_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse log level \"%s\": %m", opts.arg);
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "log-color", "BOOL", "Highlight important log messages"):
if (opts.arg) {
r = log_show_color_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse log color setting \"%s\": %m",
opts.arg);
} else
log_show_color(true);
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "log-location", "BOOL",
"Include code location in log messages"):
if (opts.arg) {
r = log_show_location_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse log location setting \"%s\": %m",
opts.arg);
} else
log_show_location(true);
break;
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "log-time", "BOOL", "Prefix log messages with current time"):
if (opts.arg) {
r = log_show_time_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse log time setting \"%s\": %m",
opts.arg);
} else
log_show_time(true);
break;
OPTION_LONG("default-standard-output", "…", "Set default standard output for services"):
r = exec_output_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse default standard output setting \"%s\": %m",
opts.arg);
arg_defaults.std_output = r;
break;
OPTION_LONG("default-standard-error", "…", "Set default standard error output for services"):
r = exec_output_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Failed to parse default standard error output setting \"%s\": %m",
opts.arg);
arg_defaults.std_error = r;
break;
OPTION_COMMON_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
/* Options not shown in --help. */
OPTION_LONG_FLAGS(OPTION_OPTIONAL_ARG, "crash-reboot", "BOOL", /* help= */ NULL):
r = parse_boolean_argument("--crash-reboot", opts.arg, NULL);
if (r < 0)
return r;
arg_crash_action = r > 0 ? CRASH_REBOOT : CRASH_FREEZE;
break;
OPTION_LONG("service-watchdogs", "BOOL", /* help= */ NULL):
r = parse_boolean_argument("--service-watchdogs=", opts.arg, &arg_service_watchdogs);
if (r < 0)
return r;
break;
OPTION_LONG("deserialize", "FD", /* help= */ NULL): {
int fd = parse_fd(opts.arg);
if (fd < 0)
return log_error_errno(fd, "Failed to parse serialization fd \"%s\": %m", opts.arg);
(void) fd_cloexec(fd, true);
FILE *f = fdopen(fd, "r");
if (!f)
return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
safe_fclose(arg_serialization);
arg_serialization = f;
break;
}
OPTION_LONG("switched-root", NULL, /* help= */ NULL):
arg_switched_root = true;
break;
OPTION_LONG("machine-id", "ID", /* help= */ NULL):
r = id128_from_string_nonzero(opts.arg, &arg_machine_id);
if (r < 0)
return log_error_errno(r, "MachineID '%s' is not valid: %m", opts.arg);
break;
OPTION_SHORT('D', NULL, /* help= */ NULL):
log_set_max_level(LOG_DEBUG);
break;
/* Eat the sysvinit kernel cmdline args that we'll parse in
* parse_proc_cmdline_item() or ignore. */
OPTION_SHORT('b', NULL, /* help= */ NULL): {}
OPTION_SHORT('s', NULL, /* help= */ NULL): {}
OPTION_SHORT('z', "ARG", /* help= */ NULL):
if (getpid_cached() != 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Switch -%c is only supported when running as PID 1.", opts.opt->short_code);
/* In PID1, do nothing and continue with option parsing. */
break;
OPTION_ERROR:
if (getpid_cached() != 1)
return -EINVAL;
/* In PID1, silently terminate option parsing. */
return 0;
}
r = redirect_telinit(argv, option_parser_get_args(&opts));
if (r < 0)
return r;
if (option_parser_get_n_args(&opts) > 0 && getpid_cached() != 1)
/* Hmm, when we aren't run as init system let's complain about excess arguments */
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Excess arguments.");
if (arg_action == ACTION_RUN && arg_runtime_scope == RUNTIME_SCOPE_USER && !user_arg_seen)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Explicit --user argument required to run as user manager.");
return 0;
}
static int prepare_reexecute(
Manager *m,
FILE **ret_f,
FDSet **ret_fds,
bool switching_root) {
_cleanup_fdset_free_ FDSet *fds = NULL;
_cleanup_fclose_ FILE *f = NULL;
int r;
assert(m);
assert(ret_f);
assert(ret_fds);
/* Make sure nothing is really destructed when we shut down */
m->n_reloading++;
bus_manager_send_reloading(m, true);
/* Only close the initramfs trust window when actually switching root.
* During a plain daemon-reexec in the initrd, PID1 still needs to
* execv() itself from the initramfs — clearing trust here would cause
* the BPF bprm_check_security hook to deny the exec. */
if (switching_root) {
r = bpf_restrict_fsaccess_close_initramfs_trust(m);
if (r < 0)
return r;
}
r = manager_open_serialization(m, &f);
if (r < 0)
return log_error_errno(r, "Failed to create serialization file: %m");
fds = fdset_new();
if (!fds)
return log_oom();
r = manager_serialize(m, f, fds, switching_root);
if (r < 0)
return r;
r = finish_serialization_file(f);
if (r < 0)
return log_error_errno(r, "Failed to finish serialization file: %m");
r = fd_cloexec(fileno(f), false);
if (r < 0)
return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization: %m");
r = fdset_cloexec(fds, false);
if (r < 0)
return log_error_errno(r, "Failed to disable O_CLOEXEC for serialization fds: %m");
*ret_f = TAKE_PTR(f);
*ret_fds = TAKE_PTR(fds);
return 0;
}
static void bump_file_max_and_nr_open(void) {
/* Let's bump fs.file-max and fs.nr_open to their respective maximums. On current kernels large
* numbers of file descriptors are no longer a performance problem and their memory is properly
* tracked by memcg, thus counting them and limiting them in another two layers of limits is
* unnecessary and just complicates things. This function hence turns off 2 of the 4 levels of limits
* on file descriptors, and makes RLIMIT_NOLIMIT (soft + hard) the only ones that really matter. */
#if BUMP_PROC_SYS_FS_FILE_MAX || BUMP_PROC_SYS_FS_NR_OPEN
int r;
#endif
#if BUMP_PROC_SYS_FS_FILE_MAX
/* The maximum the kernel allows for this since 5.2 is LONG_MAX, use that. (Previously things were
* different, but the operation would fail silently.) */
r = sysctl_write("fs/file-max", LONG_MAX_STR);
if (r < 0)
log_full_errno(ERRNO_IS_NEG_FS_WRITE_REFUSED(r) ? LOG_DEBUG : LOG_WARNING, r,
"Failed to bump fs.file-max, ignoring: %m");
#endif
#if BUMP_PROC_SYS_FS_NR_OPEN
/* The kernel enforces maximum and minimum values on the fs.nr_open, but they are not directly
* exposed, but hardcoded in fs/file.c. Hopefully, these values will not be changed, but not sure.
* Let's first try the hardcoded maximum value, and if it does not work, try the half of it. */
for (unsigned v = NR_OPEN_MAXIMUM; v >= NR_OPEN_MINIMUM; v /= 2) {
unsigned k = read_nr_open();
if (k >= v) { /* Already larger */
log_debug("Skipping bump, value is already larger.");
break;
}
r = sysctl_writef("fs/nr_open", "%u", v);
if (r == -EINVAL) {
log_debug("Couldn't write fs.nr_open as %u, halving it.", v);
continue;
}
if (r < 0) {
log_full_errno(ERRNO_IS_NEG_FS_WRITE_REFUSED(r) ? LOG_DEBUG : LOG_WARNING, r,
"Failed to bump fs.nr_open, ignoring: %m");
break;
}
log_debug("Successfully bumped fs.nr_open to %u", v);
break;
}
#endif
}
static int bump_rlimit_nofile(const struct rlimit *saved_rlimit) {
struct rlimit new_rlimit;
int r;
/* Get the underlying absolute limit the kernel enforces */
unsigned nr = read_nr_open();
/* Calculate the new limits to use for us. Never lower from what we inherited. */
new_rlimit = (struct rlimit) {
.rlim_cur = MAX((rlim_t) nr, saved_rlimit->rlim_cur),
.rlim_max = MAX((rlim_t) nr, saved_rlimit->rlim_max),
};
/* Shortcut if nothing changes. */
if (saved_rlimit->rlim_max >= new_rlimit.rlim_max &&
saved_rlimit->rlim_cur >= new_rlimit.rlim_cur) {
log_debug("RLIMIT_NOFILE is already as high or higher than we need it, not bumping.");
return 0;
}
/* Bump up the resource limit for ourselves substantially, all the way to the maximum the kernel allows, for
* both hard and soft. */
r = setrlimit_closest(RLIMIT_NOFILE, &new_rlimit);
if (r < 0)
return log_warning_errno(r, "Setting RLIMIT_NOFILE failed, ignoring: %m");
return 0;
}
static int bump_rlimit_memlock(const struct rlimit *saved_rlimit) {
struct rlimit new_rlimit;
uint64_t mm;
int r;
/* BPF_MAP_TYPE_LPM_TRIE bpf maps are charged against RLIMIT_MEMLOCK, even if we have CAP_IPC_LOCK
* which should normally disable such checks. We need them to implement IPAddressAllow= and
* IPAddressDeny=, hence let's bump the value high enough for our user. */
/* Using MAX() on resource limits only is safe if RLIM_INFINITY is > 0. POSIX declares that rlim_t
* must be unsigned, hence this is a given, but let's make this clear here. */
assert_cc(RLIM_INFINITY > 0);
mm = physical_memory_scale(1, 8); /* Let's scale how much we allow to be locked by the amount of
* physical RAM. We allow an eighth to be locked by us, just to
* pick a value. */
new_rlimit = (struct rlimit) {
.rlim_cur = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_cur, mm),
.rlim_max = MAX3(HIGH_RLIMIT_MEMLOCK, saved_rlimit->rlim_max, mm),
};
if (saved_rlimit->rlim_max >= new_rlimit.rlim_cur &&
saved_rlimit->rlim_cur >= new_rlimit.rlim_max) {
log_debug("RLIMIT_MEMLOCK is already as high or higher than we need it, not bumping.");
return 0;
}
r = setrlimit_closest(RLIMIT_MEMLOCK, &new_rlimit);
if (r < 0)
return log_warning_errno(r, "Setting RLIMIT_MEMLOCK failed, ignoring: %m");
return 0;
}
static int enforce_syscall_archs(Set *archs) {
#if HAVE_SECCOMP
int r;
if (!is_seccomp_available())
return 0;
r = seccomp_restrict_archs(arg_syscall_archs);
if (r < 0)
return log_error_errno(r, "Failed to enforce system call architecture restriction: %m");
#endif
return 0;
}
static int os_release_status(void) {
_cleanup_free_ char *pretty_name = NULL, *fancy_name = NULL,
*name = NULL, *version = NULL, *ansi_color = NULL, *support_end = NULL, *codename = NULL;
int r;
r = parse_os_release(NULL,
"PRETTY_NAME", &pretty_name,
"FANCY_NAME", &fancy_name,
"NAME", &name,
"VERSION", &version,
"VERSION_CODENAME", &codename,
"ANSI_COLOR", &ansi_color,
"SUPPORT_END", &support_end);
if (r < 0)
return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
"Failed to read os-release file, ignoring: %m");
const char *label = os_release_pretty_name(pretty_name, name);
if (show_status_on(arg_show_status)) {
const char *color = empty_to_null(ansi_color) ?: "1";
/* The fancy name may contain emoji characters and ANSI sequences. Don't use it if our locale
* doesn't allow that, or ANSI sequences are off, or if it is empty. */
if (!isempty(fancy_name)) {
_cleanup_free_ char *unescaped = NULL;
/* Undo one level of C-style unescaping for this one */
ssize_t l = cunescape(fancy_name, /* flags= */ 0, &unescaped);
if (l < 0) {
log_debug_errno(l, "Failed to unescape FANCY_NAME=, ignoring: %m");
fancy_name = mfree(fancy_name);
} else if (!utf8_is_valid(fancy_name)) {
log_debug("Unescaped FANCY_NAME= contains invalid UTF-8, ignoring.");
fancy_name = mfree(fancy_name);
} else {
free_and_replace(fancy_name, unescaped);
/* FANCY_NAME= does not contain version/codename info (unlike PRETTY_NAME=),
* but in this context it makes sense to show them if defined, hence append
* them here. */
if (version && !strextend(&fancy_name, " ", version))
return log_oom();
if (codename && !strextend(&fancy_name, " (", codename, ")"))
return log_oom();
}
}
if (isempty(fancy_name) ||
(!emoji_enabled() && !ascii_is_valid(fancy_name)) ||
!log_get_show_color())
fancy_name = mfree(fancy_name);
if (!fancy_name && log_get_show_color()) {
fancy_name = strjoin("\x1B[", color, "m", label);
if (!fancy_name)
return log_oom();
}
if (in_initrd()) {
if (log_get_show_color())
status_printf(NULL, 0,
ANSI_HIGHLIGHT "Booting initrd of " ANSI_NORMAL "%s" ANSI_NORMAL ANSI_HIGHLIGHT "." ANSI_NORMAL,
fancy_name);
else
status_printf(NULL, 0,
"Booting initrd of %s...", label);
} else {
if (log_get_show_color())
status_printf(NULL, 0,
"\n" ANSI_HIGHLIGHT "Welcome to " ANSI_NORMAL "%s" ANSI_NORMAL ANSI_HIGHLIGHT "!" ANSI_NORMAL "\n",
fancy_name);
else
status_printf(NULL, 0,
"\nWelcome to %s!\n",
label);
}
}
if (support_end && os_release_support_ended(support_end, /* quiet= */ false, /* ret_eol= */ NULL) > 0)
/* pretty_name may include the version already, so we'll print the version only if we
* have it and we're not using pretty_name. */
status_printf(ANSI_HIGHLIGHT_RED " !! " ANSI_NORMAL, 0,
"This OS version (%s%s%s) is past its end-of-support date (%s)",
label,
(pretty_name || !version) ? "" : " version ",
(pretty_name || !version) ? "" : version,
support_end);
return 0;
}
static int setup_os_release(RuntimeScope scope) {
char os_release_dst[STRLEN("/run/user//systemd/propagate/.os-release-stage/os-release") + DECIMAL_STR_MAX(uid_t)] =
"/run/systemd/propagate/.os-release-stage/os-release";
const char *os_release_src = "/etc/os-release";
int r;
assert(IN_SET(scope, RUNTIME_SCOPE_SYSTEM, RUNTIME_SCOPE_USER));
if (access("/etc/os-release", F_OK) < 0) {
if (errno != ENOENT)
log_debug_errno(errno, "Failed to check if /etc/os-release exists, ignoring: %m");
os_release_src = "/usr/lib/os-release";
}
if (scope == RUNTIME_SCOPE_USER)
xsprintf(os_release_dst, "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage/os-release", geteuid());
r = mkdir_parents_label(os_release_dst, 0755);
if (r < 0)
return log_debug_errno(r, "Failed to create parent directory of '%s', ignoring: %m", os_release_dst);
r = copy_file_atomic(os_release_src, os_release_dst, 0644, COPY_MAC_CREATE|COPY_REPLACE);
if (r < 0)
return log_debug_errno(r, "Failed to copy '%s' to '%s', ignoring: %m",
os_release_src, os_release_dst);
return 0;
}
static int write_container_id(void) {
const char *c;
int r = 0; /* avoid false maybe-uninitialized warning */
c = getenv("container");
if (isempty(c))
return 0;
WITH_UMASK(0022)
r = write_string_file("/run/systemd/container", c, WRITE_STRING_FILE_CREATE);
if (r < 0)
return log_warning_errno(r, "Failed to write /run/systemd/container, ignoring: %m");
return 1;
}
static int write_boot_or_shutdown_osc(const char *type) {
int r;
assert(STRPTR_IN_SET(type, "boot", "shutdown"));
if (getenv_terminal_is_dumb())
return 0;
_cleanup_close_ int fd = open_terminal("/dev/console", O_WRONLY|O_NOCTTY|O_CLOEXEC);
if (fd < 0)
return log_debug_errno(fd, "Failed to open /dev/console to print %s OSC, ignoring: %m", type);
_cleanup_free_ char *seq = NULL;
if (streq(type, "boot"))
r = osc_context_open_boot(&seq);
else
r = osc_context_close(SD_ID128_ALLF, &seq);
if (r < 0)
return log_debug_errno(r, "Failed to acquire %s OSC sequence, ignoring: %m", type);
r = loop_write(fd, seq, SIZE_MAX);
if (r < 0)
return log_debug_errno(r, "Failed to write %s OSC sequence, ignoring: %m", type);
if (DEBUG_LOGGING) {
_cleanup_free_ char *h = cescape(seq);
log_debug("OSC sequence for %s successfully written: %s", type, strna(h));
}
return 0;
}
static int bump_unix_max_dgram_qlen(void) {
unsigned long v;
int r;
/* Let's bump the net.unix.max_dgram_qlen sysctl. The kernel default of 16 is simply too low. We set
* the value really really early during boot, so that it is actually applied to all our sockets,
* including the $NOTIFY_SOCKET one. */
r = sysctl_read_lu("net/unix/max_dgram_qlen", &v);
if (r < 0)
return log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
"Failed to read AF_UNIX datagram queue length, ignoring: %m");
if (v >= DEFAULT_UNIX_MAX_DGRAM_QLEN)
return 0;
r = sysctl_write("net/unix/max_dgram_qlen", STRINGIFY(DEFAULT_UNIX_MAX_DGRAM_QLEN));
if (r < 0)
return log_full_errno(ERRNO_IS_NEG_FS_WRITE_REFUSED(r) ? LOG_DEBUG : LOG_WARNING, r,
"Failed to bump AF_UNIX datagram queue length, ignoring: %m");
return 1;
}
static int fixup_environment(void) {
int r;
/* Only fix up the environment when we are started as PID 1 */
if (getpid_cached() != 1)
return 0;
/* We expect the environment to be set correctly if run inside a container. */
if (detect_container() > 0)
return 0;
/* When started as PID1, the kernel uses /dev/console for our stdios and uses TERM=linux whatever the
* backend device used by the console. We try to make a better guess here since some consoles might
* not have support for color mode for example.
*
* However if TERM was configured through the kernel command line then leave it alone. */
_cleanup_free_ char *term = NULL;
r = proc_cmdline_get_key("TERM", 0, &term);
if (r < 0)
return r;
if (r > 0) {
/* If we pick up $TERM, then also pick up $COLORTERM, $NO_COLOR */
FOREACH_STRING(v, "COLORTERM", "NO_COLOR") {
_cleanup_free_ char *vv = NULL;
r = proc_cmdline_get_key(v, 0, &vv);
if (r < 0)
return r;
if (r > 0 && setenv(v, vv, /* overwrite= */ true) < 0)
return -errno;
}
} else {
/* If no $TERM is set then look for the per-tty variable instead */
r = proc_cmdline_get_key("systemd.tty.term.console", 0, &term);
if (r < 0)
return r;
}
if (!term)
(void) query_term_for_tty("/dev/console", &term);
if (setenv("TERM", term ?: FALLBACK_TERM, /* overwrite= */ true) < 0)
return -errno;
/* The kernels sets HOME=/ for init. Let's undo this. */
if (path_equal(getenv("HOME"), "/"))
assert_se(unsetenv("HOME") == 0);
return 0;
}
static int become_shutdown(int objective, int retval) {
static const char* const table[_MANAGER_OBJECTIVE_MAX] = {
[MANAGER_EXIT] = "exit",
[MANAGER_REBOOT] = "reboot",
[MANAGER_POWEROFF] = "poweroff",
[MANAGER_HALT] = "halt",
[MANAGER_KEXEC] = "kexec",
};
char timeout[STRLEN("--timeout=") + DECIMAL_STR_MAX(usec_t) + STRLEN("us")],
exit_code[STRLEN("--exit-code=") + DECIMAL_STR_MAX(uint8_t)];
_cleanup_strv_free_ char **env_block = NULL;
_cleanup_free_ char *max_log_levels = NULL;
usec_t watchdog_timer = 0;
int r;
assert(objective >= 0 && objective < _MANAGER_OBJECTIVE_MAX);
assert(table[objective]);
xsprintf(timeout, "--timeout=%" PRI_USEC "us", arg_defaults.timeout_stop_usec);
const char* command_line[11] = {
SYSTEMD_SHUTDOWN_BINARY_PATH,
table[objective],
timeout,
/* Note that the last position is a terminator and must contain NULL. */
};
size_t pos = 3;
assert(command_line[pos-1]);
assert(!command_line[pos]);
(void) log_max_levels_to_string(log_get_max_level(), &max_log_levels);
if (max_log_levels) {
command_line[pos++] = "--log-level";
command_line[pos++] = max_log_levels;
}
switch (log_get_target()) {
case LOG_TARGET_KMSG:
case LOG_TARGET_JOURNAL_OR_KMSG:
case LOG_TARGET_SYSLOG_OR_KMSG:
command_line[pos++] = "--log-target=kmsg";
break;
case LOG_TARGET_NULL:
command_line[pos++] = "--log-target=null";
break;
case LOG_TARGET_CONSOLE:
default:
command_line[pos++] = "--log-target=console";
};
if (log_get_show_color())
command_line[pos++] = "--log-color";
if (log_get_show_location())
command_line[pos++] = "--log-location";
if (log_get_show_time())
command_line[pos++] = "--log-time";
xsprintf(exit_code, "--exit-code=%d", retval);
command_line[pos++] = exit_code;
assert(pos < ELEMENTSOF(command_line));
/* The watchdog: */
if (objective == MANAGER_REBOOT)
watchdog_timer = arg_reboot_watchdog;
else if (objective == MANAGER_KEXEC)
watchdog_timer = arg_kexec_watchdog;
/* If we reboot or kexec let's set the shutdown watchdog and tell the
* shutdown binary to repeatedly ping it.
* Disable the pretimeout watchdog, as we do not support it from the shutdown binary. */
(void) watchdog_setup_pretimeout(0);
(void) watchdog_setup_pretimeout_governor(NULL);
r = watchdog_setup(watchdog_timer);
watchdog_close(/* disarm= */ r < 0);
/* The environment block: */
env_block = strv_copy(environ);
/* Tell the binary how often to ping, ignore failure */
(void) strv_extendf(&env_block, "WATCHDOG_USEC="USEC_FMT, watchdog_timer);
/* Make sure that tools that look for $WATCHDOG_USEC (and might get started by the exitrd) don't get
* confused by the variable, because the sd_watchdog_enabled() protocol uses the same variable for
* the same purposes. */
(void) strv_extendf(&env_block, "WATCHDOG_PID=" PID_FMT, getpid_cached());
if (arg_watchdog_device)
(void) strv_extendf(&env_block, "WATCHDOG_DEVICE=%s", arg_watchdog_device);
if (arg_minimum_uptime_usec != USEC_INFINITY)
(void) strv_extendf(&env_block, "MINIMUM_UPTIME_USEC=" USEC_FMT, arg_minimum_uptime_usec);
/* If we have a LUO serialization file, pass the fd to systemd-shutdown so it can
* preserve FD store entries across kexec via the kernel Live Update Orchestrator. */
if (arg_luo_serialization) {
log_debug("Passing LUO serialization fd to systemd-shutdown.");
(void) strv_extendf(&env_block, "SYSTEMD_LUO_SERIALIZE_FD=%i", fileno(arg_luo_serialization));
}
(void) write_boot_or_shutdown_osc("shutdown");
execve(SYSTEMD_SHUTDOWN_BINARY_PATH, (char **) command_line, env_block);
return -errno;
}
static int fallback_shutdown(ManagerObjective objective, int retval) {
int cmd;
/* Perform the requested shutdown operation ourselves, by issuing the matching reboot() directly.
* This skips the cleanup systemd-shutdown normally does (unmounting file systems, detaching storage,
* killing remaining processes, switching into the exitrd). */
switch (objective) {
case MANAGER_KEXEC:
log_info("Rebooting with kexec.");
(void) kexec();
/* If we are still here kexec didn't work, fall back to a plain reboot. */
_fallthrough_;
case MANAGER_REBOOT:
(void) reboot_with_parameter(REBOOT_LOG);
log_info("Rebooting.");
cmd = RB_AUTOBOOT;
break;
case MANAGER_EXIT:
if (detect_container() > 0) {
log_info("Exiting container.");
exit(retval);
}
_fallthrough_;
case MANAGER_POWEROFF:
log_info("Powering off.");
cmd = RB_POWER_OFF;
break;
case MANAGER_HALT:
log_info("Halting system.");
cmd = RB_HALT_SYSTEM;
break;
default:
assert_not_reached();
}
(void) reboot(cmd);
return log_error_errno(errno, "Failed to shut down: %m");
}
static void initialize_clock_timewarp(void) {
int r;
/* This is called very early on, before we parse the kernel command line or otherwise figure out why
* we are running, but only once. */
if (clock_is_localtime(NULL) > 0) {
int min;
/* The very first call of settimeofday() also does a time warp in the kernel.
*
* In the rtc-in-local time mode, we set the kernel's timezone, and rely on external tools to
* take care of maintaining the RTC and do all adjustments. This matches the behavior of
* Windows, which leaves the RTC alone if the registry tells that the RTC runs in UTC.
*/
r = clock_set_timezone(&min);
if (r < 0)
log_error_errno(r, "Failed to apply local time delta, ignoring: %m");
else
log_info("RTC configured in localtime, applying delta of %i minutes to system time.", min);
} else if (!in_initrd())
/*
* Do a dummy very first call to seal the kernel's time warp magic.
*
* Do not call this from inside the initrd. The initrd might not carry /etc/adjtime with
* LOCAL, but the real system could be set up that way. In such case, we need to delay the
* time-warp or the sealing until we reach the real system.
*
* Do no set the kernel's timezone. The concept of local time cannot be supported reliably,
* the time will jump or be incorrect at every daylight saving time change. All kernel local
* time concepts will be treated as UTC that way.
*/
(void) clock_reset_timewarp();
}
static void apply_clock_update(void) {
/* This is called later than clock_apply_epoch(), i.e. after we have parsed
* configuration files/kernel command line and such. */
if (arg_clock_usec == 0)
return;
if (getpid_cached() != 1)
return;
if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(arg_clock_usec)) < 0)
log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m");
else
log_info("Set system clock to %s, as specified on the kernel command line.",
FORMAT_TIMESTAMP(arg_clock_usec));
}
static void cmdline_take_random_seed(void) {
size_t suggested;
int r;
if (arg_random_seed_size == 0)
return;
if (getpid_cached() != 1)
return;
assert(arg_random_seed);
suggested = random_pool_size();
if (arg_random_seed_size < suggested)
log_warning("Random seed specified on kernel command line has size %zu, but %zu bytes required to fill entropy pool.",
arg_random_seed_size, suggested);
r = random_write_entropy(-1, arg_random_seed, arg_random_seed_size, true);
if (r < 0) {
log_warning_errno(r, "Failed to credit entropy specified on kernel command line, ignoring: %m");
return;
}
log_notice("Successfully credited entropy passed on kernel command line.\n"
"Note that the seed provided this way is accessible to unprivileged programs. "
"This functionality should not be used outside of testing environments.");
}
static void initialize_coredump(bool skip_setup) {
if (getpid_cached() != 1)
return;
/* Don't limit the core dump size, so that coredump handlers such as systemd-coredump (which honour
* the limit) will process core dumps for system services by default. */
if (setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(RLIM_INFINITY)) < 0)
log_warning_errno(errno, "Failed to set RLIMIT_CORE: %m");
/* But at the same time, turn off the core_pattern logic by default, so that no coredumps are stored
* until the systemd-coredump tool is enabled via sysctl. However it can be changed via the kernel
* command line later so core dumps can still be generated during early startup and in initrd. */
if (!skip_setup)
disable_coredumps();
}
static void initialize_core_pattern(bool skip_setup) {
int r;