Releasing 1.0.35.
[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-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
54         /* give priority to command line options */
55         result = !b->file - !a->file;
56
57         if(result) {
58                 return result;
59         }
60
61         result = a->line - b->line;
62
63         if(result) {
64                 return result;
65         } else {
66                 return a->file ? strcmp(a->file, b->file) : 0;
67         }
68 }
69
70 void init_configuration(avl_tree_t **config_tree) {
71         *config_tree = avl_alloc_tree((avl_compare_t) config_compare, (avl_action_t) free_config);
72 }
73
74 void exit_configuration(avl_tree_t **config_tree) {
75         avl_delete_tree(*config_tree);
76         *config_tree = NULL;
77 }
78
79 config_t *new_config(void) {
80         return xmalloc_and_zero(sizeof(config_t));
81 }
82
83 void free_config(config_t *cfg) {
84         free(cfg->variable);
85         free(cfg->value);
86         free(cfg->file);
87         free(cfg);
88 }
89
90 void config_add(avl_tree_t *config_tree, config_t *cfg) {
91         avl_insert(config_tree, cfg);
92 }
93
94 config_t *lookup_config(const avl_tree_t *config_tree, char *variable) {
95         config_t cfg, *found;
96
97         cfg.variable = variable;
98         cfg.file = NULL;
99         cfg.line = 0;
100
101         found = avl_search_closest_greater(config_tree, &cfg);
102
103         if(!found) {
104                 return NULL;
105         }
106
107         if(strcasecmp(found->variable, variable)) {
108                 return NULL;
109         }
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
130         return NULL;
131 }
132
133 bool get_config_bool(const config_t *cfg, bool *result) {
134         if(!cfg) {
135                 return false;
136         }
137
138         if(!strcasecmp(cfg->value, "yes")) {
139                 *result = true;
140                 return true;
141         } else if(!strcasecmp(cfg->value, "no")) {
142                 *result = false;
143                 return true;
144         }
145
146         logger(LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
147                cfg->variable, cfg->file, cfg->line);
148
149         return false;
150 }
151
152 bool get_config_int(const config_t *cfg, int *result) {
153         if(!cfg) {
154                 return false;
155         }
156
157         if(sscanf(cfg->value, "%d", result) == 1) {
158                 return true;
159         }
160
161         logger(LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
162                cfg->variable, cfg->file, cfg->line);
163
164         return false;
165 }
166
167 bool get_config_string(const config_t *cfg, char **result) {
168         if(!cfg) {
169                 return false;
170         }
171
172         *result = xstrdup(cfg->value);
173
174         return true;
175 }
176
177 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
178         struct addrinfo *ai;
179
180         if(!cfg) {
181                 return false;
182         }
183
184         ai = str2addrinfo(cfg->value, NULL, 0);
185
186         if(ai) {
187                 *result = ai;
188                 return true;
189         }
190
191         logger(LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
192                cfg->variable, cfg->file, cfg->line);
193
194         return false;
195 }
196
197 bool get_config_subnet(const config_t *cfg, subnet_t **result) {
198         subnet_t subnet = {0};
199
200         if(!cfg) {
201                 return false;
202         }
203
204         if(!str2net(&subnet, cfg->value)) {
205                 logger(LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
206                        cfg->variable, cfg->file, cfg->line);
207                 return false;
208         }
209
210         /* Teach newbies what subnets are... */
211
212         if(((subnet.type == SUBNET_IPV4)
213                         && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(ipv4_t)))
214                         || ((subnet.type == SUBNET_IPV6)
215                             && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(ipv6_t)))) {
216                 logger(LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
217                        cfg->variable, cfg->file, cfg->line);
218                 return false;
219         }
220
221         *(*result = new_subnet()) = subnet;
222
223         return true;
224 }
225
226 /*
227   Read exactly one line and strip the trailing newline if any.
228 */
229 static char *readline(FILE *fp, char *buf, size_t buflen) {
230         char *newline = NULL;
231         char *p;
232
233         if(feof(fp)) {
234                 return NULL;
235         }
236
237         p = fgets(buf, buflen, fp);
238
239         if(!p) {
240                 return NULL;
241         }
242
243         newline = strchr(p, '\n');
244
245         if(!newline) {
246                 return buf;
247         }
248
249         *newline = '\0';        /* kill newline */
250
251         if(newline > p && newline[-1] == '\r') { /* and carriage return if necessary */
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(LOG_ERR, "%s `%s' on line %d while reading config file %s",
286                                err, variable, lineno, fname);
287                 else
288                         logger(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(avl_tree_t *config_tree, const char *fname) {
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(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(avl_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
373                 if(!prefix) {
374                         if(strchr(cfg->variable, '.')) {
375                                 continue;
376                         }
377                 } else {
378                         if(strncmp(prefix, cfg->variable, prefix_len) ||
379                                         cfg->variable[prefix_len] != '.') {
380                                 continue;
381                         }
382                 }
383
384                 config_t *new = new_config();
385
386                 if(prefix) {
387                         new->variable = xstrdup(cfg->variable + prefix_len + 1);
388                 } else {
389                         new->variable = xstrdup(cfg->variable);
390                 }
391
392                 new->value = xstrdup(cfg->value);
393                 new->file = NULL;
394                 new->line = cfg->line;
395
396                 config_add(config_tree, new);
397         }
398 }
399
400 bool read_server_config(void) {
401         char fname[PATH_MAX];
402         bool x;
403
404         read_config_options(config_tree, NULL);
405
406         snprintf(fname, sizeof(fname), "%s/tinc.conf", confbase);
407         errno = 0;
408         x = read_config_file(config_tree, fname);
409
410         // We will try to read the conf files in the "conf.d" dir
411         if(x) {
412                 char dname[PATH_MAX];
413                 snprintf(dname, sizeof(dname), "%s/conf.d", confbase);
414                 DIR *dir = opendir(dname);
415
416                 // If we can find this dir
417                 if(dir) {
418                         struct dirent *ep;
419
420                         // We list all the files in it
421                         while(x && (ep = readdir(dir))) {
422                                 size_t l = strlen(ep->d_name);
423
424                                 // And we try to read the ones that end with ".conf"
425                                 if(l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
426                                         if((size_t)snprintf(fname, sizeof(fname), "%s/%s", dname, ep->d_name) >= sizeof(fname)) {
427                                                 logger(LOG_ERR, "Pathname too long: %s/%s", dname, ep->d_name);
428                                                 return false;
429                                         }
430
431                                         x = read_config_file(config_tree, fname);
432                                 }
433                         }
434
435                         closedir(dir);
436                 }
437         }
438
439         if(!x && errno) {
440                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
441         }
442
443         return x;
444 }
445
446 bool read_connection_config(connection_t *c) {
447         char fname[PATH_MAX];
448         bool x;
449
450         read_config_options(c->config_tree, c->name);
451
452         snprintf(fname, sizeof(fname), "%s/hosts/%s", confbase, c->name);
453         x = read_config_file(c->config_tree, fname);
454
455         return x;
456 }
457
458 static void disable_old_keys(const char *filename) {
459         char tmpfile[PATH_MAX] = "";
460         char buf[1024];
461         bool disabled = false;
462         FILE *r, *w;
463
464         r = fopen(filename, "r");
465
466         if(!r) {
467                 return;
468         }
469
470         snprintf(tmpfile, sizeof(tmpfile), "%s.tmp", filename);
471
472         w = fopen(tmpfile, "w");
473
474         while(fgets(buf, sizeof(buf), r)) {
475                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {
476                         buf[11] = 'O';
477                         buf[12] = 'L';
478                         buf[13] = 'D';
479                         disabled = true;
480                 } else if(!strncmp(buf, "-----END RSA", 12)) {
481                         buf[ 9] = 'O';
482                         buf[10] = 'L';
483                         buf[11] = 'D';
484                         disabled = true;
485                 }
486
487                 if(w && fputs(buf, w) < 0) {
488                         disabled = false;
489                         break;
490                 }
491         }
492
493         if(w) {
494                 fclose(w);
495         }
496
497         fclose(r);
498
499         if(!w && disabled) {
500                 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
501                 return;
502         }
503
504         if(disabled) {
505 #ifdef HAVE_MINGW
506                 // We cannot atomically replace files on Windows.
507                 char bakfile[PATH_MAX] = "";
508                 snprintf(bakfile, sizeof(bakfile), "%s.bak", filename);
509
510                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
511                         rename(bakfile, filename);
512 #else
513
514                 if(rename(tmpfile, filename)) {
515 #endif
516                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
517                 } else  {
518 #ifdef HAVE_MINGW
519                         unlink(bakfile);
520 #endif
521                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
522                 }
523         }
524
525         unlink(tmpfile);
526 }
527
528 FILE *ask_and_open(const char *filename, const char *what) {
529         FILE *r;
530         char directory[PATH_MAX];
531         char line[PATH_MAX];
532         char abspath[PATH_MAX];
533         const char *fn;
534
535         /* Check stdin and stdout */
536         if(!isatty(0) || !isatty(1)) {
537                 /* Argh, they are running us from a script or something.  Write
538                    the files to the current directory and let them burn in hell
539                    for ever. */
540                 fn = filename;
541         } else {
542                 /* Ask for a file and/or directory name. */
543                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
544                         what, filename);
545                 fflush(stdout);
546
547                 fn = readline(stdin, line, sizeof(line));
548
549                 if(!fn) {
550                         fprintf(stderr, "Error while reading stdin: %s\n",
551                                 strerror(errno));
552                         return NULL;
553                 }
554
555                 if(!strlen(fn))
556                         /* User just pressed enter. */
557                 {
558                         fn = filename;
559                 }
560         }
561
562 #ifdef HAVE_MINGW
563
564         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
565 #else
566
567         if(fn[0] != '/') {
568 #endif
569                 /* The directory is a relative path or a filename. */
570                 getcwd(directory, sizeof(directory));
571
572                 if((size_t)snprintf(abspath, sizeof(abspath), "%s/%s", directory, fn) >= sizeof(abspath)) {
573                         fprintf(stderr, "Pathname too long: %s/%s\n", directory, fn);
574                         return NULL;
575                 }
576
577                 fn = abspath;
578         }
579
580         umask(0077);                            /* Disallow everything for group and other */
581
582         disable_old_keys(fn);
583
584         /* Open it first to keep the inode busy */
585
586         r = fopen(fn, "a");
587
588         if(!r) {
589                 fprintf(stderr, "Error opening file `%s': %s\n",
590                         fn, strerror(errno));
591                 return NULL;
592         }
593
594         return r;
595 }
596
597