1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
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 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 #include "hostname-setup.h"
33 #if defined(TARGET_FEDORA)
34 #define FILENAME "/etc/sysconfig/network"
35 #elif defined(TARGET_SUSE) || defined(TARGET_SLACKWARE)
36 #define FILENAME "/etc/HOSTNAME"
37 #elif defined(TARGET_DEBIAN)
38 #define FILENAME "/etc/hostname"
39 #elif defined(TARGET_ARCH)
40 #define FILENAME "/etc/rc.conf"
41 #elif defined(TARGET_GENTOO)
42 #define FILENAME "/etc/conf.d/hostname"
45 static char* strip_bad_chars(char *s) {
48 for (p = s, d = s; *p; p++)
49 if ((*p >= 'a' && *p <= 'z') ||
50 (*p >= 'A' && *p <= 'Z') ||
51 (*p >= '0' && *p <= '9') ||
62 static int read_hostname(char **hn) {
64 #if defined(TARGET_FEDORA) || defined(TARGET_ARCH) || defined(TARGET_GENTOO)
70 if (!(f = fopen(FILENAME, "re")))
77 if (!fgets(line, sizeof(line), f)) {
87 if (!startswith_no_case(s, "HOSTNAME="))
90 if (!(k = strdup(s+9))) {
114 #elif defined(TARGET_SUSE) || defined(TARGET_DEBIAN) || defined(TARGET_SLACKWARE)
120 if ((r = read_one_line_file(FILENAME, &s)) < 0)
123 k = strdup(strstrip(s));
139 #warning "Don't know how to read the hostname"
147 int hostname_setup(void) {
151 if ((r = read_hostname(&hn)) < 0) {
153 log_warning("Failed to read configured hostname: %s", strerror(-r));
158 r = sethostname(hn, strlen(hn)) < 0 ? -errno : 0;
161 log_warning("Failed to set hostname to <%s>: %s", hn, strerror(-r));
163 log_info("Set hostname to <%s>.", hn);