]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/hostname-setup.c
Always check asprintf return code
[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"
a5c32cff 32#include "fileio.h"
302e8c4c 33
28695e0f 34static int read_and_strip_hostname(const char *path, char **hn) {
9beb3f4d 35 char *s;
28695e0f
LP
36 int r;
37
38 assert(path);
39 assert(hn);
40
fb3d2b8f
LP
41 r = read_one_line_file(path, &s);
42 if (r < 0)
28695e0f
LP
43 return r;
44
e724b063 45 hostname_cleanup(s, false);
28695e0f 46
9beb3f4d
LP
47 if (isempty(s)) {
48 free(s);
28695e0f
LP
49 return -ENOENT;
50 }
51
9beb3f4d 52 *hn = s;
302e8c4c
LP
53 return 0;
54}
55
56int hostname_setup(void) {
57 int r;
46a2911b
LP
58 _cleanup_free_ char *b = NULL;
59 const char *hn;
fb3d2b8f 60 bool enoent = false;
302e8c4c 61
46a2911b 62 r = read_and_strip_hostname("/etc/hostname", &b);
fb3d2b8f 63 if (r < 0) {
28695e0f 64 if (r == -ENOENT)
fb3d2b8f 65 enoent = true;
28695e0f 66 else
302e8c4c 67 log_warning("Failed to read configured hostname: %s", strerror(-r));
46a2911b
LP
68
69 hn = NULL;
28695e0f
LP
70 } else
71 hn = b;
302e8c4c 72
344de609
LP
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())
46a2911b 77 return 0;
9bec0b1e 78
fb3d2b8f
LP
79 if (enoent)
80 log_info("No hostname configured.");
81
9bec0b1e
LP
82 hn = "localhost";
83 }
84
28695e0f
LP
85 if (sethostname(hn, strlen(hn)) < 0) {
86 log_warning("Failed to set hostname to <%s>: %m", hn);
46a2911b
LP
87 return -errno;
88 }
302e8c4c 89
46a2911b
LP
90 log_info("Set hostname to <%s>.", hn);
91 return 0;
302e8c4c 92}