Convert sizeof foo to sizeof(foo).
[oweals/tinc.git] / src / conf.c
1 /*
2     conf.c -- configuration code
3     Copyright (C) 1998 Robert van der Meulen
4                   1998-2005 Ivo Timmermans
5                   2000-2014 Guus Sliepen <guus@tinc-vpn.org>
6                   2010-2011 Julien Muchembled <jm@jmuchemb.eu>
7                   2000 Cris van Pelt
8
9     This program is free software; you can redistribute it and/or modify
10     it under the terms of the GNU General Public License as published by
11     the Free Software Foundation; either version 2 of the License, or
12     (at your option) any later version.
13
14     This program is distributed in the hope that it will be useful,
15     but WITHOUT ANY WARRANTY; without even the implied warranty of
16     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17     GNU General Public License for more details.
18
19     You should have received a copy of the GNU General Public License along
20     with this program; if not, write to the Free Software Foundation, Inc.,
21     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 */
23
24 #include "system.h"
25
26 #include "avl_tree.h"
27 #include "connection.h"
28 #include "conf.h"
29 #include "list.h"
30 #include "logger.h"
31 #include "netutl.h"                             /* for str2address */
32 #include "protocol.h"
33 #include "utils.h"                              /* for cp */
34 #include "xalloc.h"
35
36 avl_tree_t *config_tree;
37
38 int pinginterval = 0;                   /* seconds between pings */
39 int pingtimeout = 0;                    /* seconds to wait for response */
40 char *confbase = NULL;                  /* directory in which all config files are */
41 char *netname = NULL;                   /* name of the vpn network */
42 list_t *cmdline_conf = NULL;    /* global/host configuration values given at the command line */
43
44
45 static int config_compare(const config_t *a, const config_t *b) {
46         int result;
47
48         result = strcasecmp(a->variable, b->variable);
49
50         if(result)
51                 return result;
52
53         /* give priority to command line options */
54         result = !b->file - !a->file;
55         if (result)
56                 return result;
57
58         result = a->line - b->line;
59
60         if(result)
61                 return result;
62         else
63                 return a->file ? strcmp(a->file, b->file) : 0;
64 }
65
66 void init_configuration(avl_tree_t ** config_tree) {
67         *config_tree = avl_alloc_tree((avl_compare_t) config_compare, (avl_action_t) free_config);
68 }
69
70 void exit_configuration(avl_tree_t ** config_tree) {
71         avl_delete_tree(*config_tree);
72         *config_tree = NULL;
73 }
74
75 config_t *new_config(void) {
76         return xmalloc_and_zero(sizeof(config_t));
77 }
78
79 void free_config(config_t *cfg) {
80         if(cfg->variable)
81                 free(cfg->variable);
82
83         if(cfg->value)
84                 free(cfg->value);
85
86         if(cfg->file)
87                 free(cfg->file);
88
89         free(cfg);
90 }
91
92 void config_add(avl_tree_t *config_tree, config_t *cfg) {
93         avl_insert(config_tree, cfg);
94 }
95
96 config_t *lookup_config(const avl_tree_t *config_tree, char *variable) {
97         config_t cfg, *found;
98
99         cfg.variable = variable;
100         cfg.file = NULL;
101         cfg.line = 0;
102
103         found = avl_search_closest_greater(config_tree, &cfg);
104
105         if(!found)
106                 return NULL;
107
108         if(strcasecmp(found->variable, variable))
109                 return NULL;
110
111         return found;
112 }
113
114 config_t *lookup_config_next(const avl_tree_t *config_tree, const config_t *cfg) {
115         avl_node_t *node;
116         config_t *found;
117
118         node = avl_search_node(config_tree, cfg);
119
120         if(node) {
121                 if(node->next) {
122                         found = node->next->data;
123
124                         if(!strcasecmp(found->variable, cfg->variable))
125                                 return found;
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         if(!strcasecmp(cfg->value, "yes")) {
137                 *result = true;
138                 return true;
139         } else if(!strcasecmp(cfg->value, "no")) {
140                 *result = false;
141                 return true;
142         }
143
144         logger(LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
145                    cfg->variable, cfg->file, cfg->line);
146
147         return false;
148 }
149
150 bool get_config_int(const config_t *cfg, int *result) {
151         if(!cfg)
152                 return false;
153
154         if(sscanf(cfg->value, "%d", result) == 1)
155                 return true;
156
157         logger(LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
158                    cfg->variable, cfg->file, cfg->line);
159
160         return false;
161 }
162
163 bool get_config_string(const config_t *cfg, char **result) {
164         if(!cfg)
165                 return false;
166
167         *result = xstrdup(cfg->value);
168
169         return true;
170 }
171
172 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
173         struct addrinfo *ai;
174
175         if(!cfg)
176                 return false;
177
178         ai = str2addrinfo(cfg->value, NULL, 0);
179
180         if(ai) {
181                 *result = ai;
182                 return true;
183         }
184
185         logger(LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
186                    cfg->variable, cfg->file, cfg->line);
187
188         return false;
189 }
190
191 bool get_config_subnet(const config_t *cfg, subnet_t ** result) {
192         subnet_t subnet = {NULL};
193
194         if(!cfg)
195                 return false;
196
197         if(!str2net(&subnet, cfg->value)) {
198                 logger(LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
199                            cfg->variable, cfg->file, cfg->line);
200                 return false;
201         }
202
203         /* Teach newbies what subnets are... */
204
205         if(((subnet.type == SUBNET_IPV4)
206                 && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(ipv4_t)))
207                 || ((subnet.type == SUBNET_IPV6)
208                 && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(ipv6_t)))) {
209                 logger(LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
210                            cfg->variable, cfg->file, cfg->line);
211                 return false;
212         }
213
214         *(*result = new_subnet()) = subnet;
215
216         return true;
217 }
218
219 /*
220   Read exactly one line and strip the trailing newline if any.
221 */
222 static char *readline(FILE * fp, char *buf, size_t buflen) {
223         char *newline = NULL;
224         char *p;
225
226         if(feof(fp))
227                 return NULL;
228
229         p = fgets(buf, buflen, fp);
230
231         if(!p)
232                 return NULL;
233
234         newline = strchr(p, '\n');
235
236         if(!newline)
237                 return buf;
238
239         *newline = '\0';        /* kill newline */
240         if(newline > p && newline[-1] == '\r')  /* and carriage return if necessary */
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(LOG_ERR, "%s `%s' on line %d while reading config file %s",
269                                 err, variable, lineno, fname);
270                 else
271                         logger(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(avl_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(LOG_ERR, "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(avl_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
347                 if(!prefix) {
348                         if(strchr(cfg->variable, '.'))
349                                 continue;
350                 } else {
351                         if(strncmp(prefix, cfg->variable, prefix_len) ||
352                            cfg->variable[prefix_len] != '.')
353                                 continue;
354                 }
355
356                 config_t *new = new_config();
357
358                 if(prefix) {
359                         new->variable = xstrdup(cfg->variable + prefix_len + 1);
360                 } else {
361                         new->variable = xstrdup(cfg->variable);
362                 }
363
364                 new->value = xstrdup(cfg->value);
365                 new->file = NULL;
366                 new->line = cfg->line;
367
368                 config_add(config_tree, new);
369         }
370 }
371
372 bool read_server_config(void) {
373         char fname[PATH_MAX];
374         bool x;
375
376         read_config_options(config_tree, NULL);
377
378         snprintf(fname, sizeof(fname), "%s/tinc.conf", confbase);
379         errno = 0;
380         x = read_config_file(config_tree, fname);
381
382         // We will try to read the conf files in the "conf.d" dir
383         if (x) {
384                 char dname[PATH_MAX];
385                 snprintf(dname, sizeof(dname), "%s/conf.d", confbase);
386                 DIR *dir = opendir (dname);
387                 // If we can find this dir
388                 if (dir) { 
389                         struct dirent *ep;
390                         // We list all the files in it
391                         while (x && (ep = readdir (dir))) {
392                                 size_t l = strlen(ep->d_name);
393                                 // And we try to read the ones that end with ".conf"
394                                 if (l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
395                                         snprintf(fname, sizeof(fname), "%s/%s", dname, ep->d_name);
396                                         x = read_config_file(config_tree, fname);
397                                 }
398                         }
399                         closedir (dir);
400                 }
401         }
402
403         if(!x && errno) {
404                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
405         }
406
407         return x;
408 }
409
410 bool read_connection_config(connection_t *c) {
411         char fname[PATH_MAX];
412         bool x;
413
414         read_config_options(c->config_tree, c->name);
415
416         snprintf(fname, sizeof(fname), "%s/hosts/%s", confbase, c->name);
417         x = read_config_file(c->config_tree, fname);
418
419         return x;
420 }
421
422 static void disable_old_keys(const char *filename) {
423         char tmpfile[PATH_MAX] = "";
424         char buf[1024];
425         bool disabled = false;
426         FILE *r, *w;
427
428         r = fopen(filename, "r");
429         if(!r)
430                 return;
431
432         snprintf(tmpfile, sizeof(tmpfile), "%s.tmp", filename);
433
434         w = fopen(tmpfile, "w");
435
436         while(fgets(buf, sizeof(buf), r)) {
437                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {       
438                         buf[11] = 'O';
439                         buf[12] = 'L';
440                         buf[13] = 'D';
441                         disabled = true;
442                 }
443                 else if(!strncmp(buf, "-----END RSA", 12)) {    
444                         buf[ 9] = 'O';
445                         buf[10] = 'L';
446                         buf[11] = 'D';
447                         disabled = true;
448                 }
449                 if(w && fputs(buf, w) < 0) {
450                         disabled = false;
451                         break;
452                 }
453         }
454
455         if(w)
456                 fclose(w);
457         fclose(r);
458
459         if(!w && disabled) {
460                 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
461                 return;
462         }
463
464         if(disabled) {
465 #ifdef HAVE_MINGW
466                 // We cannot atomically replace files on Windows.
467                 char bakfile[PATH_MAX] = "";
468                 snprintf(bakfile, sizeof(bakfile), "%s.bak", filename);
469                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
470                         rename(bakfile, filename);
471 #else
472                 if(rename(tmpfile, filename)) {
473 #endif
474                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
475                 } else  {
476 #ifdef HAVE_MINGW
477                         unlink(bakfile);
478 #endif
479                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
480                 }
481         }
482
483         unlink(tmpfile);
484 }
485
486 FILE *ask_and_open(const char *filename, const char *what) {
487         FILE *r;
488         char directory[PATH_MAX];
489         char line[PATH_MAX];
490         char abspath[PATH_MAX];
491         const char *fn;
492
493         /* Check stdin and stdout */
494         if(!isatty(0) || !isatty(1)) {
495                 /* Argh, they are running us from a script or something.  Write
496                    the files to the current directory and let them burn in hell
497                    for ever. */
498                 fn = filename;
499         } else {
500                 /* Ask for a file and/or directory name. */
501                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
502                                 what, filename);
503                 fflush(stdout);
504
505                 fn = readline(stdin, line, sizeof(line));
506
507                 if(!fn) {
508                         fprintf(stderr, "Error while reading stdin: %s\n",
509                                         strerror(errno));
510                         return NULL;
511                 }
512
513                 if(!strlen(fn))
514                         /* User just pressed enter. */
515                         fn = filename;
516         }
517
518 #ifdef HAVE_MINGW
519         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
520 #else
521         if(fn[0] != '/') {
522 #endif
523                 /* The directory is a relative path or a filename. */
524                 getcwd(directory, sizeof(directory));
525                 snprintf(abspath, sizeof(abspath), "%s/%s", directory, fn);
526                 fn = abspath;
527         }
528
529         umask(0077);                            /* Disallow everything for group and other */
530
531         disable_old_keys(fn);
532
533         /* Open it first to keep the inode busy */
534
535         r = fopen(fn, "a");
536
537         if(!r) {
538                 fprintf(stderr, "Error opening file `%s': %s\n",
539                                 fn, strerror(errno));
540                 return NULL;
541         }
542
543         return r;
544 }
545
546