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
boot. It is not propagated to the hardware clock (RTC).</para></listitem>
</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>
</refsect1>

View File

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