| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include "alloc-util.h" |
| 4 |
#include "dns-def.h" |
| 5 |
#include "dns-domain.h" |
| 6 |
#include "hostname-setup.h" |
| 7 |
#include "hostname-util.h" |
| 8 |
#include "idn-util.h" |
| 9 |
#include "log.h" |
| 10 |
#include "resolved-util.h" |
| 11 |
#include "utf8.h" |
| 12 |
|
| 13 |
int resolve_system_hostname(char **full_hostname, char **first_label) { |
| 14 |
_cleanup_free_ char *h = NULL, *n = NULL; |
| 15 |
char label[DNS_LABEL_MAX+1]; |
| 16 |
const char *p, *decoded; |
| 17 |
int r; |
| 18 |
|
| 19 |
/* Return the full hostname in *full_hostname, if nonnull. |
| 20 |
* |
| 21 |
* Extract and normalize the first label of the locally configured hostname, check it's not |
| 22 |
* "localhost", and return it in *first_label, if nonnull. */ |
| 23 |
|
| 24 |
r = gethostname_strict(&h); |
| 25 |
if (r < 0) |
| 26 |
return log_debug_errno(r, "Can't determine system hostname: %m"); |
| 27 |
|
| 28 |
p = h; |
| 29 |
r = dns_label_unescape(&p, label, sizeof label, 0); |
| 30 |
if (r < 0) |
| 31 |
return log_debug_errno(r, "Failed to unescape hostname: %m"); |
| 32 |
if (r == 0) |
| 33 |
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), |
| 34 |
"Couldn't find a single label in hostname."); |
| 35 |
|
| 36 |
#if HAVE_LIBIDN2 |
| 37 |
_cleanup_free_ char *utf8 = NULL; |
| 38 |
|
| 39 |
if (DLOPEN_IDN(LOG_DEBUG, SD_ELF_NOTE_DLOPEN_PRIORITY_RECOMMENDED) >= 0) { |
| 40 |
r = sym_idn2_to_unicode_8z8z(label, &utf8, 0); |
| 41 |
if (r != IDN2_OK) |
| 42 |
return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN), |
| 43 |
"Failed to undo IDNA: %s", sym_idn2_strerror(r)); |
| 44 |
assert(utf8_is_valid(utf8)); |
| 45 |
|
| 46 |
r = strlen(utf8); |
| 47 |
decoded = utf8; |
| 48 |
} else |
| 49 |
#endif |
| 50 |
decoded = label; /* no decoding */ |
| 51 |
|
| 52 |
r = dns_label_escape_new(decoded, r, &n); |
| 53 |
if (r < 0) |
| 54 |
return log_debug_errno(r, "Failed to escape hostname: %m"); |
| 55 |
|
| 56 |
if (is_localhost(n)) |
| 57 |
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), |
| 58 |
"System hostname is 'localhost', ignoring."); |
| 59 |
|
| 60 |
if (full_hostname) |
| 61 |
*full_hostname = TAKE_PTR(h); |
| 62 |
if (first_label) |
| 63 |
*first_label = TAKE_PTR(n); |
| 64 |
return 0; |
| 65 |
} |