]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/hostname-setup.c
tree-wide: drop 'This file is part of systemd' blurb
[thirdparty/systemd.git] / src / core / hostname-setup.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
302e8c4c 2/***
302e8c4c 3 Copyright 2010 Lennart Poettering
302e8c4c
LP
4***/
5
302e8c4c 6#include <errno.h>
07630cea 7#include <stdio.h>
302e8c4c
LP
8#include <stdlib.h>
9
b5efdb8a 10#include "alloc-util.h"
a5c32cff 11#include "fileio.h"
cf0fbc49 12#include "hostname-setup.h"
958b66ea 13#include "hostname-util.h"
07630cea
LP
14#include "log.h"
15#include "macro.h"
16#include "string-util.h"
17#include "util.h"
302e8c4c 18
302e8c4c 19int hostname_setup(void) {
46a2911b 20 _cleanup_free_ char *b = NULL;
fb3d2b8f 21 bool enoent = false;
8341d4fa
LP
22 const char *hn;
23 int r;
302e8c4c 24
f35cb39e 25 r = read_etc_hostname(NULL, &b);
fb3d2b8f 26 if (r < 0) {
28695e0f 27 if (r == -ENOENT)
fb3d2b8f 28 enoent = true;
28695e0f 29 else
da927ba9 30 log_warning_errno(r, "Failed to read configured hostname: %m");
46a2911b
LP
31
32 hn = NULL;
28695e0f
LP
33 } else
34 hn = b;
302e8c4c 35
344de609
LP
36 if (isempty(hn)) {
37 /* Don't override the hostname if it is already set
38 * and not explicitly configured */
39 if (hostname_is_set())
46a2911b 40 return 0;
9bec0b1e 41
fb3d2b8f
LP
42 if (enoent)
43 log_info("No hostname configured.");
44
8341d4fa 45 hn = FALLBACK_HOSTNAME;
9bec0b1e
LP
46 }
47
709f6e46
MS
48 r = sethostname_idempotent(hn);
49 if (r < 0)
50 return log_warning_errno(r, "Failed to set hostname to <%s>: %m", hn);
302e8c4c 51
46a2911b
LP
52 log_info("Set hostname to <%s>.", hn);
53 return 0;
302e8c4c 54}