2017-11-18 17:09:20 +01:00
|
|
|
/* SPDX-License-Identifier: LGPL-2.1+ */
|
2010-04-10 05:00:38 +02:00
|
|
|
|
|
|
|
#include <errno.h>
|
2015-10-24 22:58:24 +02:00
|
|
|
#include <stdio.h>
|
2010-04-10 05:00:38 +02:00
|
|
|
#include <stdlib.h>
|
|
|
|
|
2015-10-27 03:01:06 +01:00
|
|
|
#include "alloc-util.h"
|
2013-02-14 12:26:13 +01:00
|
|
|
#include "fileio.h"
|
2015-11-16 22:09:36 +01:00
|
|
|
#include "hostname-setup.h"
|
2015-05-18 17:10:07 +02:00
|
|
|
#include "hostname-util.h"
|
2015-10-24 22:58:24 +02:00
|
|
|
#include "log.h"
|
|
|
|
#include "macro.h"
|
2020-05-14 11:01:31 +02:00
|
|
|
#include "proc-cmdline.h"
|
2015-10-24 22:58:24 +02:00
|
|
|
#include "string-util.h"
|
|
|
|
#include "util.h"
|
2010-04-10 05:00:38 +02:00
|
|
|
|
|
|
|
int hostname_setup(void) {
|
2013-01-04 18:37:49 +01:00
|
|
|
_cleanup_free_ char *b = NULL;
|
2020-05-14 11:01:31 +02:00
|
|
|
const char *hn = NULL;
|
2012-04-22 15:47:38 +02:00
|
|
|
bool enoent = false;
|
2017-02-16 12:03:39 +01:00
|
|
|
int r;
|
2010-04-10 05:00:38 +02:00
|
|
|
|
2020-05-14 11:01:31 +02:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|
2013-01-04 18:37:49 +01:00
|
|
|
|
2020-05-14 11:01:31 +02:00
|
|
|
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;
|
|
|
|
}
|
2010-04-10 05:00:38 +02:00
|
|
|
|
2012-05-21 17:19:58 +02:00
|
|
|
if (isempty(hn)) {
|
2020-05-14 11:01:31 +02:00
|
|
|
/* Don't override the hostname if it is already set and not explicitly configured */
|
2012-05-21 17:19:58 +02:00
|
|
|
if (hostname_is_set())
|
2013-01-04 18:37:49 +01:00
|
|
|
return 0;
|
2011-03-14 18:05:52 +01:00
|
|
|
|
2012-04-22 15:47:38 +02:00
|
|
|
if (enoent)
|
|
|
|
log_info("No hostname configured.");
|
|
|
|
|
2017-02-16 12:03:39 +01:00
|
|
|
hn = FALLBACK_HOSTNAME;
|
2011-03-14 18:05:52 +01:00
|
|
|
}
|
|
|
|
|
2015-11-05 13:44:06 +01:00
|
|
|
r = sethostname_idempotent(hn);
|
|
|
|
if (r < 0)
|
|
|
|
return log_warning_errno(r, "Failed to set hostname to <%s>: %m", hn);
|
2010-04-10 05:00:38 +02:00
|
|
|
|
2013-01-04 18:37:49 +01:00
|
|
|
log_info("Set hostname to <%s>.", hn);
|
|
|
|
return 0;
|
2010-04-10 05:00:38 +02:00
|
|
|
}
|