]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/core/hostname-setup.c
treewide: use log_*_errno whenever %m is in the format string
[thirdparty/systemd.git] / src / core / hostname-setup.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <unistd.h>
23 #include <stdio.h>
24 #include <errno.h>
25 #include <string.h>
26 #include <stdlib.h>
27
28 #include "hostname-setup.h"
29 #include "macro.h"
30 #include "util.h"
31 #include "log.h"
32 #include "fileio.h"
33
34 static int read_and_strip_hostname(const char *path, char **hn) {
35 char *s;
36 int r;
37
38 assert(path);
39 assert(hn);
40
41 r = read_one_line_file(path, &s);
42 if (r < 0)
43 return r;
44
45 hostname_cleanup(s, false);
46
47 if (isempty(s)) {
48 free(s);
49 return -ENOENT;
50 }
51
52 *hn = s;
53 return 0;
54 }
55
56 int hostname_setup(void) {
57 int r;
58 _cleanup_free_ char *b = NULL;
59 const char *hn;
60 bool enoent = false;
61
62 r = read_and_strip_hostname("/etc/hostname", &b);
63 if (r < 0) {
64 if (r == -ENOENT)
65 enoent = true;
66 else
67 log_warning_errno(r, "Failed to read configured hostname: %m");
68
69 hn = NULL;
70 } else
71 hn = b;
72
73 if (isempty(hn)) {
74 /* Don't override the hostname if it is already set
75 * and not explicitly configured */
76 if (hostname_is_set())
77 return 0;
78
79 if (enoent)
80 log_info("No hostname configured.");
81
82 hn = "localhost";
83 }
84
85 if (sethostname_idempotent(hn) < 0) {
86 log_warning_errno(errno, "Failed to set hostname to <%s>: %m", hn);
87 return -errno;
88 }
89
90 log_info("Set hostname to <%s>.", hn);
91 return 0;
92 }