hostname: introduce gethostname_full() and use it in various gethostname() variants

This commit is contained in:
Yu Watanabe
2021-08-12 13:48:15 +09:00
parent ccdf235464
commit 0995accdfd
5 changed files with 64 additions and 78 deletions
+11 -25
View File
@@ -20,12 +20,14 @@
#include "util.h"
static int sethostname_idempotent_full(const char *s, bool really) {
char buf[HOST_NAME_MAX + 1];
_cleanup_free_ char *buf = NULL;
int r;
assert(s);
if (gethostname(buf, sizeof(buf)) < 0)
return -errno;
r = gethostname_full(GET_HOSTNAME_ALLOW_NONE | GET_HOSTNAME_ALLOW_LOCALHOST, &buf);
if (r < 0)
return r;
if (streq(buf, s))
return 0;
@@ -41,26 +43,6 @@ int sethostname_idempotent(const char *s) {
return sethostname_idempotent_full(s, true);
}
bool get_hostname_filtered(char ret[static HOST_NAME_MAX + 1]) {
char buf[HOST_NAME_MAX + 1];
/* Returns true if we got a good hostname, false otherwise. */
if (gethostname(buf, sizeof(buf)) < 0)
return false; /* This can realistically only fail with ENAMETOOLONG.
* Let's treat that case the same as an invalid hostname. */
if (isempty(buf))
return false;
/* This is the built-in kernel default hostname */
if (streq(buf, "(none)"))
return false;
memcpy(ret, buf, sizeof buf);
return true;
}
int shorten_overlong(const char *s, char **ret) {
char *h, *p;
@@ -195,10 +177,14 @@ int hostname_setup(bool really) {
}
if (!hn) {
_cleanup_free_ char *buf = NULL;
/* Don't override the hostname if it is already set and not explicitly configured */
char buf[HOST_NAME_MAX + 1] = {};
if (get_hostname_filtered(buf)) {
r = gethostname_full(GET_HOSTNAME_ALLOW_LOCALHOST, &buf);
if (r == -ENOMEM)
return log_oom();
if (r >= 0) {
log_debug("No hostname configured, leaving existing hostname <%s> in place.", buf);
return 0;
}