Don't check for NULL-pointers before calling free().
[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
53         /* give priority to command line options */
54         result = !b->file - !a->file;
55
56         if(result) {
57                 return result;
58         }
59
60         result = a->line - b->line;
61
62         if(result) {
63                 return result;
64         } else {
65                 return a->file ? strcmp(a->file, b->file) : 0;
66         }
67 }
68
69 void init_configuration(splay_tree_t **config_tree) {
70         *config_tree = splay_alloc_tree((splay_compare_t) config_compare, (splay_action_t) free_config);
71 }
72
73 void exit_configuration(splay_tree_t **config_tree) {
74         splay_delete_tree(*config_tree);
75         *config_tree = NULL;
76 }
77
78 config_t *new_config(void) {
79         return xzalloc(sizeof(config_t));
80 }
81
82 void free_config(config_t *cfg) {
83         free(cfg->variable);
84         free(cfg->value);
85         free(cfg->file);
86         free(cfg);
87 }
88
89 void config_add(splay_tree_t *config_tree, config_t *cfg) {
90         splay_insert(config_tree, cfg);
91 }
92
93 config_t *lookup_config(splay_tree_t *config_tree, char *variable) {
94         config_t cfg, *found;
95
96         cfg.variable = variable;
97         cfg.file = NULL;
98         cfg.line = 0;
99
100         found = splay_search_closest_greater(config_tree, &cfg);
101
102         if(!found) {
103                 return NULL;
104         }
105
106         if(strcasecmp(found->variable, variable)) {
107                 return NULL;
108         }
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
129         return NULL;
130 }
131
132 bool get_config_bool(const config_t *cfg, bool *result) {
133         if(!cfg) {
134                 return false;
135         }
136
137         if(!strcasecmp(cfg->value, "yes")) {
138                 *result = true;
139                 return true;
140         } else if(!strcasecmp(cfg->value, "no")) {
141                 *result = false;
142                 return true;
143         }
144
145         logger(DEBUG_ALWAYS, LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
146                cfg->variable, cfg->file, cfg->line);
147
148         return false;
149 }
150
151 bool get_config_int(const config_t *cfg, int *result) {
152         if(!cfg) {
153                 return false;
154         }
155
156         if(sscanf(cfg->value, "%d", result) == 1) {
157                 return true;
158         }
159
160         logger(DEBUG_ALWAYS, LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
161                cfg->variable, cfg->file, cfg->line);
162
163         return false;
164 }
165
166 bool get_config_string(const config_t *cfg, char **result) {
167         if(!cfg) {
168                 return false;
169         }
170
171         *result = xstrdup(cfg->value);
172
173         return true;
174 }
175
176 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
177         struct addrinfo *ai;
178
179         if(!cfg) {
180                 return false;
181         }
182
183         ai = str2addrinfo(cfg->value, NULL, 0);
184
185         if(ai) {
186                 *result = ai;
187                 return true;
188         }
189
190         logger(DEBUG_ALWAYS, LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
191                cfg->variable, cfg->file, cfg->line);
192
193         return false;
194 }
195
196 bool get_config_subnet(const config_t *cfg, subnet_t **result) {
197         subnet_t subnet = {0};
198
199         if(!cfg) {
200                 return false;
201         }
202
203         if(!str2net(&subnet, cfg->value)) {
204                 logger(DEBUG_ALWAYS, LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
205                        cfg->variable, cfg->file, cfg->line);
206                 return false;
207         }
208
209         /* Teach newbies what subnets are... */
210
211         if(((subnet.type == SUBNET_IPV4)
212                         && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(subnet.net.ipv4.address)))
213                         || ((subnet.type == SUBNET_IPV6)
214                             && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(subnet.net.ipv6.address)))) {
215                 logger(DEBUG_ALWAYS, LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
216                        cfg->variable, cfg->file, cfg->line);
217                 return false;
218         }
219
220         *(*result = new_subnet()) = subnet;
221
222         return true;
223 }
224
225 /*
226   Read exactly one line and strip the trailing newline if any.
227 */
228 static char *readline(FILE *fp, char *buf, size_t buflen) {
229         char *newline = NULL;
230         char *p;
231
232         if(feof(fp)) {
233                 return NULL;
234         }
235
236         p = fgets(buf, buflen, fp);
237
238         if(!p) {
239                 return NULL;
240         }
241
242         newline = strchr(p, '\n');
243
244         if(!newline) {
245                 return buf;
246         }
247
248         /* kill newline and carriage return if necessary */
249         *newline = '\0';
250
251         if(newline > p && newline[-1] == '\r') {
252                 newline[-1] = '\0';
253         }
254
255         return buf;
256 }
257
258 config_t *parse_config_line(char *line, const char *fname, int lineno) {
259         config_t *cfg;
260         int len;
261         char *variable, *value, *eol;
262         variable = value = line;
263
264         eol = line + strlen(line);
265
266         while(strchr("\t ", *--eol)) {
267                 *eol = '\0';
268         }
269
270         len = strcspn(value, "\t =");
271         value += len;
272         value += strspn(value, "\t ");
273
274         if(*value == '=') {
275                 value++;
276                 value += strspn(value, "\t ");
277         }
278
279         variable[len] = '\0';
280
281         if(!*value) {
282                 const char err[] = "No value for variable";
283
284                 if(fname)
285                         logger(DEBUG_ALWAYS, LOG_ERR, "%s `%s' on line %d while reading config file %s",
286                                err, variable, lineno, fname);
287                 else
288                         logger(DEBUG_ALWAYS, LOG_ERR, "%s `%s' in command line option %d",
289                                err, variable, lineno);
290
291                 return NULL;
292         }
293
294         cfg = new_config();
295         cfg->variable = xstrdup(variable);
296         cfg->value = xstrdup(value);
297         cfg->file = fname ? xstrdup(fname) : NULL;
298         cfg->line = lineno;
299
300         return cfg;
301 }
302
303 /*
304   Parse a configuration file and put the results in the configuration tree
305   starting at *base.
306 */
307 bool read_config_file(splay_tree_t *config_tree, const char *fname, bool verbose) {
308         FILE *fp;
309         char buffer[MAX_STRING_SIZE];
310         char *line;
311         int lineno = 0;
312         bool ignore = false;
313         config_t *cfg;
314         bool result = false;
315
316         fp = fopen(fname, "r");
317
318         if(!fp) {
319                 logger(verbose ? DEBUG_ALWAYS : DEBUG_CONNECTIONS, LOG_ERR, "Cannot open config file %s: %s", fname, strerror(errno));
320                 return false;
321         }
322
323         for(;;) {
324                 line = readline(fp, buffer, sizeof(buffer));
325
326                 if(!line) {
327                         if(feof(fp)) {
328                                 result = true;
329                         }
330
331                         break;
332                 }
333
334                 lineno++;
335
336                 if(!*line || *line == '#') {
337                         continue;
338                 }
339
340                 if(ignore) {
341                         if(!strncmp(line, "-----END", 8)) {
342                                 ignore = false;
343                         }
344
345                         continue;
346                 }
347
348                 if(!strncmp(line, "-----BEGIN", 10)) {
349                         ignore = true;
350                         continue;
351                 }
352
353                 cfg = parse_config_line(line, fname, lineno);
354
355                 if(!cfg) {
356                         break;
357                 }
358
359                 config_add(config_tree, cfg);
360         }
361
362         fclose(fp);
363
364         return result;
365 }
366
367 void read_config_options(splay_tree_t *config_tree, const char *prefix) {
368         size_t prefix_len = prefix ? strlen(prefix) : 0;
369
370         for(const list_node_t *node = cmdline_conf->tail; node; node = node->prev) {
371                 const config_t *cfg = node->data;
372                 config_t *new;
373
374                 if(!prefix) {
375                         if(strchr(cfg->variable, '.')) {
376                                 continue;
377                         }
378                 } else {
379                         if(strncmp(prefix, cfg->variable, prefix_len) ||
380                                         cfg->variable[prefix_len] != '.') {
381                                 continue;
382                         }
383                 }
384
385                 new = new_config();
386
387                 if(prefix) {
388                         new->variable = xstrdup(cfg->variable + prefix_len + 1);
389                 } else {
390                         new->variable = xstrdup(cfg->variable);
391                 }
392
393                 new->value = xstrdup(cfg->value);
394                 new->file = NULL;
395                 new->line = cfg->line;
396
397                 config_add(config_tree, new);
398         }
399 }
400
401 bool read_server_config(void) {
402         char fname[PATH_MAX];
403         bool x;
404
405         read_config_options(config_tree, NULL);
406
407         snprintf(fname, sizeof(fname), "%s" SLASH "tinc.conf", confbase);
408         errno = 0;
409         x = read_config_file(config_tree, fname, true);
410
411         // We will try to read the conf files in the "conf.d" dir
412         if(x) {
413                 char dname[PATH_MAX];
414                 snprintf(dname, sizeof(dname), "%s" SLASH "conf.d", confbase);
415                 DIR *dir = opendir(dname);
416
417                 // If we can find this dir
418                 if(dir) {
419                         struct dirent *ep;
420
421                         // We list all the files in it
422                         while(x && (ep = readdir(dir))) {
423                                 size_t l = strlen(ep->d_name);
424
425                                 // And we try to read the ones that end with ".conf"
426                                 if(l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
427                                         if((size_t)snprintf(fname, sizeof(fname), "%s" SLASH "%s", dname, ep->d_name) >= sizeof(fname)) {
428                                                 logger(DEBUG_ALWAYS, LOG_ERR, "Pathname too long: %s/%s", dname, ep->d_name);
429                                                 return false;
430                                         }
431
432                                         x = read_config_file(config_tree, fname, true);
433                                 }
434                         }
435
436                         closedir(dir);
437                 }
438         }
439
440         if(!x && errno) {
441                 logger(DEBUG_ALWAYS, LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
442         }
443
444         return x;
445 }
446
447 bool read_host_config(splay_tree_t *config_tree, const char *name, bool verbose) {
448         read_config_options(config_tree, name);
449
450         char fname[PATH_MAX];
451         snprintf(fname, sizeof(fname), "%s" SLASH "hosts" SLASH "%s", confbase, name);
452         return read_config_file(config_tree, fname, verbose);
453 }
454
455 bool append_config_file(const char *name, const char *key, const char *value) {
456         char fname[PATH_MAX];
457         snprintf(fname, sizeof(fname), "%s" SLASH "hosts" SLASH "%s", confbase, name);
458
459         FILE *fp = fopen(fname, "a");
460
461         if(!fp) {
462                 logger(DEBUG_ALWAYS, LOG_DEBUG, "Cannot open config file %s: %s", fname, strerror(errno));
463                 return false;
464         }
465
466         fprintf(fp, "\n# The following line was automatically added by tinc\n%s = %s\n", key, value);
467         fclose(fp);
468         return true;
469 }