]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/hostname-setup.c
Merge pull request #17732 from yuwata/core-use-synthetic_errno
[thirdparty/systemd.git] / src / core / hostname-setup.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
302e8c4c 2
302e8c4c 3#include <errno.h>
07630cea 4#include <stdio.h>
302e8c4c
LP
5#include <stdlib.h>
6
b5efdb8a 7#include "alloc-util.h"
a5c32cff 8#include "fileio.h"
cf0fbc49 9#include "hostname-setup.h"
958b66ea 10#include "hostname-util.h"
07630cea
LP
11#include "log.h"
12#include "macro.h"
34293dfa 13#include "proc-cmdline.h"
07630cea
LP
14#include "string-util.h"
15#include "util.h"
302e8c4c 16
302e8c4c 17int hostname_setup(void) {
46a2911b 18 _cleanup_free_ char *b = NULL;
34293dfa 19 const char *hn = NULL;
fb3d2b8f 20 bool enoent = false;
8341d4fa 21 int r;
302e8c4c 22
34293dfa
LP
23 r = proc_cmdline_get_key("systemd.hostname", 0, &b);
24 if (r < 0)
25 log_warning_errno(r, "Failed to retrieve system hostname from kernel command line, ignoring: %m");
26 else if (r > 0) {
27 if (hostname_is_valid(b, true))
28 hn = b;
29 else {
30 log_warning("Hostname specified on kernel command line is invalid, ignoring: %s", b);
31 b = mfree(b);
32 }
33 }
46a2911b 34
34293dfa
LP
35 if (!hn) {
36 r = read_etc_hostname(NULL, &b);
37 if (r < 0) {
38 if (r == -ENOENT)
39 enoent = true;
40 else
41 log_warning_errno(r, "Failed to read configured hostname: %m");
42 } else
43 hn = b;
44 }
302e8c4c 45
344de609 46 if (isempty(hn)) {
34293dfa 47 /* Don't override the hostname if it is already set and not explicitly configured */
344de609 48 if (hostname_is_set())
46a2911b 49 return 0;
9bec0b1e 50
fb3d2b8f
LP
51 if (enoent)
52 log_info("No hostname configured.");
53
8341d4fa 54 hn = FALLBACK_HOSTNAME;
9bec0b1e
LP
55 }
56
709f6e46
MS
57 r = sethostname_idempotent(hn);
58 if (r < 0)
59 return log_warning_errno(r, "Failed to set hostname to <%s>: %m", hn);
302e8c4c 60
46a2911b
LP
61 log_info("Set hostname to <%s>.", hn);
62 return 0;
302e8c4c 63}