core: allow overriding the system hostname with systemd.hostname= on the kernel command line

This commit is contained in:
Lennart Poettering 2020-05-14 11:01:31 +02:00
parent 3753325bef
commit 34293dfafd
2 changed files with 32 additions and 12 deletions

View File

@ -467,6 +467,14 @@
system clock to. The system time is set to the specified timestamp early during system clock to. The system time is set to the specified timestamp early during
boot. It is not propagated to the hardware clock (RTC).</para></listitem> boot. It is not propagated to the hardware clock (RTC).</para></listitem>
</varlistentry> </varlistentry>
<varlistentry>
<term><varname>systemd.hostname=</varname></term>
<listitem><para>Accepts a hostname to set during early boot. If specified takes precedence over what
is set in <filename>/etc/hostname</filename>. Note that this does not bar later runtime changes to
the hostname, it simply controls the initial hostname set during early boot.</para></listitem>
</varlistentry>
</variablelist> </variablelist>
</refsect1> </refsect1>

View File

@ -10,29 +10,41 @@
#include "hostname-util.h" #include "hostname-util.h"
#include "log.h" #include "log.h"
#include "macro.h" #include "macro.h"
#include "proc-cmdline.h"
#include "string-util.h" #include "string-util.h"
#include "util.h" #include "util.h"
int hostname_setup(void) { int hostname_setup(void) {
_cleanup_free_ char *b = NULL; _cleanup_free_ char *b = NULL;
const char *hn = NULL;
bool enoent = false; bool enoent = false;
const char *hn;
int r; int r;
r = read_etc_hostname(NULL, &b); r = proc_cmdline_get_key("systemd.hostname", 0, &b);
if (r < 0) { if (r < 0)
if (r == -ENOENT) log_warning_errno(r, "Failed to retrieve system hostname from kernel command line, ignoring: %m");
enoent = true; else if (r > 0) {
else if (hostname_is_valid(b, true))
log_warning_errno(r, "Failed to read configured hostname: %m"); hn = b;
else {
log_warning("Hostname specified on kernel command line is invalid, ignoring: %s", b);
b = mfree(b);
}
}
hn = NULL; if (!hn) {
} else r = read_etc_hostname(NULL, &b);
hn = b; if (r < 0) {
if (r == -ENOENT)
enoent = true;
else
log_warning_errno(r, "Failed to read configured hostname: %m");
} else
hn = b;
}
if (isempty(hn)) { if (isempty(hn)) {
/* Don't override the hostname if it is already set /* Don't override the hostname if it is already set and not explicitly configured */
* and not explicitly configured */
if (hostname_is_set()) if (hostname_is_set())
return 0; return 0;