Remember ToS/Diffserv priority for each socket individually.
[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         /* 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         list_node_t *node, *next;
343         size_t prefix_len = prefix ? strlen(prefix) : 0;
344
345         for(node = cmdline_conf->tail; node; node = next) {
346                 config_t *orig_cfg, *cfg = (config_t *)node->data;
347                 next = node->prev;
348
349                 if(!prefix) {
350                         if(strchr(cfg->variable, '.'))
351                                 continue;
352                         node->data = NULL;
353                         list_unlink_node(cmdline_conf, node);
354                 } else {
355                         if(strncmp(prefix, cfg->variable, prefix_len) ||
356                            cfg->variable[prefix_len] != '.')
357                                 continue;
358                         /* Because host configuration is parsed again when
359                            reconnecting, nodes must not be freed when a prefix
360                            is given. */
361                         orig_cfg = cfg;
362                         cfg = new_config();
363                         cfg->variable = xstrdup(orig_cfg->variable + prefix_len + 1);
364                         cfg->value = xstrdup(orig_cfg->value);
365                         cfg->file = NULL;
366                         cfg->line = orig_cfg->line;
367                 }
368                 config_add(config_tree, cfg);
369         }
370 }
371
372 bool read_server_config(void) {
373         char *fname;
374         bool x;
375
376         read_config_options(config_tree, NULL);
377
378         xasprintf(&fname, "%s/tinc.conf", confbase);
379         x = read_config_file(config_tree, fname);
380
381         // We will try to read the conf files in the "conf.d" dir
382         if (x) {
383                 char * dname;
384                 xasprintf(&dname, "%s/conf.d", confbase);
385                 DIR *dir = opendir (dname);
386                 // If we can find this dir
387                 if (dir) { 
388                         struct dirent *ep;
389                         // We list all the files in it
390                         while (x && (ep = readdir (dir))) {
391                                 size_t l = strlen(ep->d_name);
392                                 // And we try to read the ones that end with ".conf"
393                                 if (l > 5 && !strcmp(".conf", & ep->d_name[ l - 5 ])) {
394                                         free(fname);
395                                         xasprintf(&fname, "%s/%s", dname, ep->d_name);
396                                         x = read_config_file(config_tree, fname);
397                                 }
398                         }
399                         closedir (dir);
400                 }
401                 free(dname);
402         }
403
404         if(!x) {                                /* System error: complain */
405                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
406         }
407
408         free(fname);
409
410         return x;
411 }
412
413 bool read_connection_config(connection_t *c) {
414         char *fname;
415         bool x;
416
417         read_config_options(c->config_tree, c->name);
418
419         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
420         x = read_config_file(c->config_tree, fname);
421         free(fname);
422
423         return x;
424 }
425
426 static void disable_old_keys(const char *filename) {
427         char tmpfile[PATH_MAX] = "";
428         char buf[1024];
429         bool disabled = false;
430         FILE *r, *w;
431
432         r = fopen(filename, "r");
433         if(!r)
434                 return;
435
436         snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
437
438         w = fopen(tmpfile, "w");
439
440         while(fgets(buf, sizeof buf, r)) {
441                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {       
442                         buf[11] = 'O';
443                         buf[12] = 'L';
444                         buf[13] = 'D';
445                         disabled = true;
446                 }
447                 else if(!strncmp(buf, "-----END RSA", 12)) {    
448                         buf[ 9] = 'O';
449                         buf[10] = 'L';
450                         buf[11] = 'D';
451                         disabled = true;
452                 }
453                 if(w && fputs(buf, w) < 0) {
454                         disabled = false;
455                         break;
456                 }
457         }
458
459         if(w)
460                 fclose(w);
461         fclose(r);
462
463         if(!w && disabled) {
464                 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
465                 return;
466         }
467
468         if(disabled) {
469 #ifdef HAVE_MINGW
470                 // We cannot atomically replace files on Windows.
471                 char bakfile[PATH_MAX] = "";
472                 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
473                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
474                         rename(bakfile, filename);
475 #else
476                 if(rename(tmpfile, filename)) {
477 #endif
478                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
479                 } else  {
480 #ifdef HAVE_MINGW
481                         unlink(bakfile);
482 #endif
483                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
484                 }
485         }
486
487         unlink(tmpfile);
488 }
489
490 FILE *ask_and_open(const char *filename, const char *what) {
491         FILE *r;
492         char *directory;
493         char line[PATH_MAX];
494         const char *fn;
495
496         /* Check stdin and stdout */
497         if(!isatty(0) || !isatty(1)) {
498                 /* Argh, they are running us from a script or something.  Write
499                    the files to the current directory and let them burn in hell
500                    for ever. */
501                 fn = filename;
502         } else {
503                 /* Ask for a file and/or directory name. */
504                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
505                                 what, filename);
506                 fflush(stdout);
507
508                 fn = readline(stdin, line, sizeof line);
509
510                 if(!fn) {
511                         fprintf(stderr, "Error while reading stdin: %s\n",
512                                         strerror(errno));
513                         return NULL;
514                 }
515
516                 if(!strlen(fn))
517                         /* User just pressed enter. */
518                         fn = filename;
519         }
520
521 #ifdef HAVE_MINGW
522         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
523 #else
524         if(fn[0] != '/') {
525 #endif
526                 /* The directory is a relative path or a filename. */
527                 char *p;
528
529                 directory = get_current_dir_name();
530                 xasprintf(&p, "%s/%s", directory, fn);
531                 free(directory);
532                 fn = p;
533         }
534
535         umask(0077);                            /* Disallow everything for group and other */
536
537         disable_old_keys(fn);
538
539         /* Open it first to keep the inode busy */
540
541         r = fopen(fn, "a");
542
543         if(!r) {
544                 fprintf(stderr, "Error opening file `%s': %s\n",
545                                 fn, strerror(errno));
546                 return NULL;
547         }
548
549         return r;
550 }
551
552