]> git.ipfire.org Git - people/ms/systemd.git/blob - hostname-setup.c
service: treat 0 timeouts as no timeouts
[people/ms/systemd.git] / hostname-setup.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 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.
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 General Public License for more details.
17
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/>.
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
33 #define LINE_MAX 4096
34
35 static int read_hostname(char **hn) {
36
37 #if defined(TARGET_FEDORA)
38 int r;
39 FILE *f;
40
41 assert(hn);
42
43 if (!(f = fopen("/etc/sysconfig/network", "re")))
44 return -errno;
45
46 for (;;) {
47 char line[LINE_MAX];
48 char *s, *k;
49
50 if (!fgets(line, sizeof(line), f)) {
51 if (feof(f))
52 break;
53
54 r = -errno;
55 goto finish;
56 }
57
58 s = strstrip(line);
59
60 if (!startswith(s, "HOSTNAME="))
61 continue;
62
63 if (!(k = strdup(s+9))) {
64 r = -ENOMEM;
65 goto finish;
66 }
67
68 *hn = k;
69 break;
70 }
71
72 r = 0;
73
74 finish:
75 fclose(f);
76 return r;
77
78 #elif defined(TARGET_SUSE)
79 int r;
80 char *s, *k;
81
82 assert(hn);
83
84 if ((r = read_one_line_file("/etc/HOSTNAME", &s)) < 0)
85 return r;
86
87 k = strdup(strstrip(s));
88 free(s);
89
90 if (!k)
91 return -ENOMEM;
92
93 *hn = k;
94
95 #elif defined(TARGET_DEBIAN)
96 int r;
97 char *s, *k;
98
99 assert(hn);
100
101 if ((r = read_one_line_file("/etc/hostname", &s)) < 0)
102 return r;
103
104 k = strdup(strstrip(s));
105 free(s);
106
107 if (!k)
108 return -ENOMEM;
109
110 *hn = k;
111 #else
112 #warning "Don't know how to read the hostname"
113
114 return -ENOENT;
115 #endif
116
117 return 0;
118 }
119
120 int hostname_setup(void) {
121 int r;
122 char *hn;
123
124 if ((r = read_hostname(&hn)) < 0) {
125 if (r != -ENOENT)
126 log_warning("Failed to read configured hostname: %s", strerror(-r));
127
128 return r;
129 }
130
131 r = sethostname(hn, strlen(hn)) < 0 ? -errno : 0;
132
133 if (r < 0)
134 log_warning("Failed to set hostname to <%s>: %s", hn, strerror(-r));
135 else
136 log_info("Set hostname to <%s>.", hn);
137
138 free(hn);
139
140 return r;
141 }