tinc-gui: Reformat codebase according to PEP8
[tinc] / src / conf.c
1 /*
2     conf.c -- configuration code
3     Copyright (C) 1998      Robert van der Meulen
4                   1998-2005 Ivo Timmermans
5                   2000      Cris van Pelt
6                   2010-2011 Julien Muchembled <jm@jmuchemb.eu>
7                   2000-2015 Guus Sliepen <guus@tinc-vpn.org>
8                   2013      Florent Clairambault <florent@clairambault.fr>
9
10     This program is free software; you can redistribute it and/or modify
11     it under the terms of the GNU General Public License as published by
12     the Free Software Foundation; either version 2 of the License, or
13     (at your option) any later version.
14
15     This program is distributed in the hope that it will be useful,
16     but WITHOUT ANY WARRANTY; without even the implied warranty of
17     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18     GNU General Public License for more details.
19
20     You should have received a copy of the GNU General Public License along
21     with this program; if not, write to the Free Software Foundation, Inc.,
22     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 */
24
25 #include "system.h"
26
27 #include "splay_tree.h"
28 #include "connection.h"
29 #include "conf.h"
30 #include "list.h"
31 #include "logger.h"
32 #include "names.h"
33 #include "netutl.h"             /* for str2address */
34 #include "protocol.h"
35 #include "utils.h"              /* for cp */
36 #include "xalloc.h"
37
38 splay_tree_t *config_tree;
39
40 int pinginterval = 0;           /* seconds between pings */
41 int pingtimeout = 0;            /* seconds to wait for response */
42 list_t *cmdline_conf = NULL;    /* global/host configuration values given at the command line */
43
44 static int config_compare(const config_t *a, const config_t *b) {
45         int result;
46
47         result = strcasecmp(a->variable, b->variable);
48
49         if(result)
50                 return result;
51
52         /* give priority to command line options */
53         result = !b->file - !a->file;
54         if (result)
55                 return result;
56
57         result = a->line - b->line;
58
59         if(result)
60                 return result;
61         else
62                 return a->file ? strcmp(a->file, b->file) : 0;
63 }
64
65 void init_configuration(splay_tree_t ** config_tree) {
66         *config_tree = splay_alloc_tree((splay_compare_t) config_compare, (splay_action_t) free_config);
67 }
68
69 void exit_configuration(splay_tree_t ** config_tree) {
70         splay_delete_tree(*config_tree);
71         *config_tree = NULL;
72 }
73
74 config_t *new_config(void) {
75         return xzalloc(sizeof(config_t));
76 }
77
78 void free_config(config_t *cfg) {
79         if(cfg->variable)
80                 free(cfg->variable);
81
82         if(cfg->value)
83                 free(cfg->value);
84
85         if(cfg->file)
86                 free(cfg->file);
87
88         free(cfg);
89 }
90
91 void config_add(splay_tree_t *config_tree, config_t *cfg) {
92         splay_insert(config_tree, cfg);
93 }
94
95 config_t *lookup_config(splay_tree_t *config_tree, char *variable) {
96         config_t cfg, *found;
97
98         cfg.variable = variable;
99         cfg.file = NULL;
100         cfg.line = 0;
101
102         found = splay_search_closest_greater(config_tree, &cfg);
103
104         if(!found)
105                 return NULL;
106
107         if(strcasecmp(found->variable, variable))
108                 return NULL;
109
110         return found;
111 }
112
113 config_t *lookup_config_next(splay_tree_t *config_tree, const config_t *cfg) {
114         splay_node_t *node;
115         config_t *found;
116
117         node = splay_search_node(config_tree, cfg);
118
119         if(node) {
120                 if(node->next) {
121                         found = node->next->data;
122
123                         if(!strcasecmp(found->variable, cfg->variable))
124                                 return found;
125                 }
126         }
127
128         return NULL;
129 }
130
131 bool get_config_bool(const config_t *cfg, bool *result) {
132         if(!cfg)
133                 return false;
134
135         if(!strcasecmp(cfg->value, "yes")) {
136                 *result = true;
137                 return true;
138         } else if(!strcasecmp(cfg->value, "no")) {
139                 *result = false;
140                 return true;
141         }
142
143         logger(DEBUG_ALWAYS, LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
144                    cfg->variable, cfg->file, cfg->line);
145
146         return false;
147 }
148
149 bool get_config_int(const config_t *cfg, int *result) {
150         if(!cfg)
151                 return false;
152
153         if(sscanf(cfg->value, "%d", result) == 1)
154                 return true;
155
156         logger(DEBUG_ALWAYS, LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
157                    cfg->variable, cfg->file, cfg->line);
158
159         return false;
160 }
161
162 bool get_config_string(const config_t *cfg, char **result) {
163         if(!cfg)
164                 return false;
165
166         *result = xstrdup(cfg->value);
167
168         return true;
169 }
170
171 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
172         struct addrinfo *ai;
173
174         if(!cfg)
175                 return false;
176
177         ai = str2addrinfo(cfg->value, NULL, 0);
178
179         if(ai) {
180                 *result = ai;
181                 return true;
182         }
183
184         logger(DEBUG_ALWAYS, LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
185                    cfg->variable, cfg->file, cfg->line);
186
187         return false;
188 }
189
190 bool get_config_subnet(const config_t *cfg, subnet_t ** result) {
191         subnet_t subnet = {NULL};
192
193         if(!cfg)
194                 return false;
195
196         if(!str2net(&subnet, cfg->value)) {
197                 logger(DEBUG_ALWAYS, LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
198                            cfg->variable, cfg->file, cfg->line);
199                 return false;
200         }
201
202         /* Teach newbies what subnets are... */
203
204         if(((subnet.type == SUBNET_IPV4)
205                 && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof subnet.net.ipv4.address))
206                 || ((subnet.type == SUBNET_IPV6)
207                 && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof subnet.net.ipv6.address))) {
208                 logger(DEBUG_ALWAYS, LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
209                            cfg->variable, cfg->file, cfg->line);
210                 return false;
211         }
212
213         *(*result = new_subnet()) = subnet;
214
215         return true;
216 }
217
218 /*
219   Read exactly one line and strip the trailing newline if any.
220 */
221 static char *readline(FILE * fp, char *buf, size_t buflen) {
222         char *newline = NULL;
223         char *p;
224
225         if(feof(fp))
226                 return NULL;
227
228         p = fgets(buf, buflen, fp);
229
230         if(!p)
231                 return NULL;
232
233         newline = strchr(p, '\n');
234
235         if(!newline)
236                 return buf;
237
238         /* kill newline and carriage return if necessary */
239         *newline = '\0';
240         if(newline > p && newline[-1] == '\r')
241                 newline[-1] = '\0';
242
243         return buf;
244 }
245
246 config_t *parse_config_line(char *line, const char *fname, int lineno) {
247         config_t *cfg;
248         int len;
249         char *variable, *value, *eol;
250         variable = value = line;
251
252         eol = line + strlen(line);
253         while(strchr("\t ", *--eol))
254                 *eol = '\0';
255
256         len = strcspn(value, "\t =");
257         value += len;
258         value += strspn(value, "\t ");
259         if(*value == '=') {
260                 value++;
261                 value += strspn(value, "\t ");
262         }
263         variable[len] = '\0';
264
265         if(!*value) {
266                 const char err[] = "No value for variable";
267                 if (fname)
268                         logger(DEBUG_ALWAYS, LOG_ERR, "%s `%s' on line %d while reading config file %s",
269                                 err, variable, lineno, fname);
270                 else
271                         logger(DEBUG_ALWAYS, LOG_ERR, "%s `%s' in command line option %d",
272                                 err, variable, lineno);
273                 return NULL;
274         }
275
276         cfg = new_config();
277         cfg->variable = xstrdup(variable);
278         cfg->value = xstrdup(value);
279         cfg->file = fname ? xstrdup(fname) : NULL;
280         cfg->line = lineno;
281
282         return cfg;
283 }
284
285 /*
286   Parse a configuration file and put the results in the configuration tree
287   starting at *base.
288 */
289 bool read_config_file(splay_tree_t *config_tree, const char *fname) {
290         FILE *fp;
291         char buffer[MAX_STRING_SIZE];
292         char *line;
293         int lineno = 0;
294         bool ignore = false;
295         config_t *cfg;
296         bool result = false;
297
298         fp = fopen(fname, "r");
299
300         if(!fp) {
301                 logger(DEBUG_ALWAYS, LOG_DEBUG, "Cannot open config file %s: %s", fname, strerror(errno));
302                 return false;
303         }
304
305         for(;;) {
306                 line = readline(fp, buffer, sizeof buffer);
307
308                 if(!line) {
309                         if(feof(fp))
310                                 result = true;
311                         break;
312                 }
313
314                 lineno++;
315
316                 if(!*line || *line == '#')
317                         continue;
318
319                 if(ignore) {
320                         if(!strncmp(line, "-----END", 8))
321                                 ignore = false;
322                         continue;
323                 }
324
325                 if(!strncmp(line, "-----BEGIN", 10)) {
326                         ignore = true;
327                         continue;
328                 }
329
330                 cfg = parse_config_line(line, fname, lineno);
331                 if (!cfg)
332                         break;
333                 config_add(config_tree, cfg);
334         }
335
336         fclose(fp);
337
338         return result;
339 }
340
341 void read_config_options(splay_tree_t *config_tree, const char *prefix) {
342         size_t prefix_len = prefix ? strlen(prefix) : 0;
343
344         for(const list_node_t *node = cmdline_conf->tail; node; node = node->prev) {
345                 const config_t *cfg = node->data;
346                 config_t *new;
347
348                 if(!prefix) {
349                         if(strchr(cfg->variable, '.'))
350                                 continue;
351                 } else {
352                         if(strncmp(prefix, cfg->variable, prefix_len) ||
353                            cfg->variable[prefix_len] != '.')
354                                 continue;
355                 }
356
357                 new = new_config();
358                 if(prefix)
359                         new->variable = xstrdup(cfg->variable + prefix_len + 1);
360                 else
361                         new->variable = xstrdup(cfg->variable);
362                 new->value = xstrdup(cfg->value);
363                 new->file = NULL;
364                 new->line = cfg->line;
365
366                 config_add(config_tree, new);
367         }
368 }
369
370 bool read_server_config(void) {
371         char fname[PATH_MAX];
372         bool x;
373
374         read_config_options(config_tree, NULL);
375
376         snprintf(fname, sizeof fname, "%s" SLASH "tinc.conf", confbase);
377         errno = 0;
378         x = read_config_file(config_tree, fname);
379
380         // We will try to read the conf files in the "conf.d" dir
381         if (x) {
382                 char dname[PATH_MAX];
383                 snprintf(dname, sizeof dname, "%s" SLASH "conf.d", confbase);
384                 DIR *dir = opendir (dname);
385                 // If we can find this dir
386                 if (dir) { 
387                         struct dirent *ep;
388                         // We list all the files in it
389                         while (x && (ep = readdir (dir))) {
390                                 size_t l = strlen(ep->d_name);
391                                 // And we try to read the ones that end with ".conf"
392                                 if (l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
393                                         snprintf(fname, sizeof fname, "%s" SLASH "%s", dname, ep->d_name);
394                                         x = read_config_file(config_tree, fname);
395                                 }
396                         }
397                         closedir (dir);
398                 }
399         }
400
401         if(!x && errno)
402                 logger(DEBUG_ALWAYS, LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
403
404         return x;
405 }
406
407 bool read_host_config(splay_tree_t *config_tree, const char *name) {
408         char fname[PATH_MAX];
409         bool x;
410
411         read_config_options(config_tree, name);
412
413         snprintf(fname, sizeof fname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
414         x = read_config_file(config_tree, fname);
415
416         return x;
417 }
418
419 bool append_config_file(const char *name, const char *key, const char *value) {
420         char fname[PATH_MAX];
421         snprintf(fname, sizeof fname, "%s" SLASH "hosts" SLASH "%s", confbase, name);
422
423         FILE *fp = fopen(fname, "a");
424
425         if(!fp) {
426                 logger(DEBUG_ALWAYS, LOG_DEBUG, "Cannot open config file %s: %s", fname, strerror(errno));
427                 return false;
428         }
429
430         fprintf(fp, "\n# The following line was automatically added by tinc\n%s = %s\n", key, value);
431         fclose(fp);
432         return true;
433 }