]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/hostname-setup.c
bootchart items
[thirdparty/systemd.git] / src / core / hostname-setup.c
CommitLineData
d6c9574f 1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
302e8c4c
LP
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
5430f7f2
LP
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
302e8c4c
LP
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
5430f7f2 16 Lesser General Public License for more details.
302e8c4c 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
302e8c4c
LP
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
28695e0f 33static int read_and_strip_hostname(const char *path, char **hn) {
9beb3f4d 34 char *s;
28695e0f
LP
35 int r;
36
37 assert(path);
38 assert(hn);
39
fb3d2b8f
LP
40 r = read_one_line_file(path, &s);
41 if (r < 0)
28695e0f
LP
42 return r;
43
9beb3f4d 44 hostname_cleanup(s);
28695e0f 45
9beb3f4d
LP
46 if (isempty(s)) {
47 free(s);
28695e0f
LP
48 return -ENOENT;
49 }
50
9beb3f4d 51 *hn = s;
302e8c4c
LP
52 return 0;
53}
54
55int hostname_setup(void) {
56 int r;
46a2911b
LP
57 _cleanup_free_ char *b = NULL;
58 const char *hn;
fb3d2b8f 59 bool enoent = false;
302e8c4c 60
46a2911b 61 r = read_and_strip_hostname("/etc/hostname", &b);
fb3d2b8f 62 if (r < 0) {
28695e0f 63 if (r == -ENOENT)
fb3d2b8f 64 enoent = true;
28695e0f 65 else
302e8c4c 66 log_warning("Failed to read configured hostname: %s", strerror(-r));
46a2911b
LP
67
68 hn = NULL;
28695e0f
LP
69 } else
70 hn = b;
302e8c4c 71
344de609
LP
72 if (isempty(hn)) {
73 /* Don't override the hostname if it is already set
74 * and not explicitly configured */
75 if (hostname_is_set())
46a2911b 76 return 0;
9bec0b1e 77
fb3d2b8f
LP
78 if (enoent)
79 log_info("No hostname configured.");
80
9bec0b1e
LP
81 hn = "localhost";
82 }
83
28695e0f
LP
84 if (sethostname(hn, strlen(hn)) < 0) {
85 log_warning("Failed to set hostname to <%s>: %m", hn);
46a2911b
LP
86 return -errno;
87 }
302e8c4c 88
46a2911b
LP
89 log_info("Set hostname to <%s>.", hn);
90 return 0;
302e8c4c 91}