1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include "dns-domain.h"
5 #include "hostname-util.h"
7 #include "resolved-util.h"
10 int resolve_system_hostname(char **full_hostname
, char **first_label
) {
11 _cleanup_free_
char *h
= NULL
, *n
= NULL
;
13 _cleanup_free_
char *utf8
= NULL
;
17 char label
[DNS_LABEL_MAX
];
18 const char *p
, *decoded
;
21 /* Return the full hostname in *full_hostname, if nonnull.
23 * Extract and normalize the first label of the locally configured hostname, check it's not
24 * "localhost", and return it in *first_label, if nonnull. */
26 r
= gethostname_strict(&h
);
28 return log_debug_errno(r
, "Can't determine system hostname: %m");
31 r
= dns_label_unescape(&p
, label
, sizeof label
, 0);
33 return log_debug_errno(r
, "Failed to unescape hostname: %m");
35 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
36 "Couldn't find a single label in hostname.");
38 #if HAVE_LIBIDN || HAVE_LIBIDN2
41 log_debug_errno(r
, "Failed to initialize IDN support, ignoring: %m");
42 decoded
= label
; /* no decoding */
47 r
= sym_idn2_to_unicode_8z8z(label
, &utf8
, 0);
49 return log_debug_errno(SYNTHETIC_ERRNO(EUCLEAN
),
50 "Failed to undo IDNA: %s", sym_idn2_strerror(r
));
51 assert(utf8_is_valid(utf8
));
56 k
= dns_label_undo_idna(label
, r
, label
, sizeof label
);
58 return log_debug_errno(k
, "Failed to undo IDNA: %m");
62 if (!utf8_is_valid(label
))
63 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
64 "System hostname is not UTF-8 clean.");
67 decoded
= label
; /* no decoding */
71 r
= dns_label_escape_new(decoded
, r
, &n
);
73 return log_debug_errno(r
, "Failed to escape hostname: %m");
76 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
77 "System hostname is 'localhost', ignoring.");
80 *full_hostname
= TAKE_PTR(h
);
82 *first_label
= TAKE_PTR(n
);