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