chiark / gitweb /
remove unused includes
[elogind.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 <stdio.h>
23 #include <errno.h>
24 #include <stdlib.h>
25
26 #include "hostname-setup.h"
27 #include "macro.h"
28 #include "util.h"
29 #include "log.h"
30 #include "fileio.h"
31
32 static int read_and_strip_hostname(const char *path, char **hn) {
33         char *s;
34         int r;
35
36         assert(path);
37         assert(hn);
38
39         r = read_one_line_file(path, &s);
40         if (r < 0)
41                 return r;
42
43         hostname_cleanup(s, false);
44
45         if (isempty(s)) {
46                 free(s);
47                 return -ENOENT;
48         }
49
50         *hn = s;
51         return 0;
52 }
53
54 int hostname_setup(void) {
55         int r;
56         _cleanup_free_ char *b = NULL;
57         const char *hn;
58         bool enoent = false;
59
60         r = read_and_strip_hostname("/etc/hostname", &b);
61         if (r < 0) {
62                 if (r == -ENOENT)
63                         enoent = true;
64                 else
65                         log_warning_errno(r, "Failed to read configured hostname: %m");
66
67                 hn = NULL;
68         } else
69                 hn = b;
70
71         if (isempty(hn)) {
72                 /* Don't override the hostname if it is already set
73                  * and not explicitly configured */
74                 if (hostname_is_set())
75                         return 0;
76
77                 if (enoent)
78                         log_info("No hostname configured.");
79
80                 hn = "localhost";
81         }
82
83         if (sethostname_idempotent(hn) < 0)
84                 return log_warning_errno(errno, "Failed to set hostname to <%s>: %m", hn);
85
86         log_info("Set hostname to <%s>.", hn);
87         return 0;
88 }