b7c0179e180d26ae26e846410c088d2e2e6374e8
[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-2010 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         if(!x) {                                /* System error: complain */
382                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
383         }
384
385         free(fname);
386
387         return x;
388 }
389
390 bool read_connection_config(connection_t *c) {
391         char *fname;
392         bool x;
393
394         read_config_options(c->config_tree, c->name);
395
396         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
397         x = read_config_file(c->config_tree, fname);
398         free(fname);
399
400         return x;
401 }
402
403 static void disable_old_keys(const char *filename) {
404         char tmpfile[PATH_MAX] = "";
405         char buf[1024];
406         bool disabled = false;
407         FILE *r, *w;
408
409         r = fopen(filename, "r");
410         if(!r)
411                 return;
412
413         snprintf(tmpfile, sizeof tmpfile, "%s.tmp", filename);
414
415         w = fopen(tmpfile, "w");
416
417         while(fgets(buf, sizeof buf, r)) {
418                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {       
419                         buf[11] = 'O';
420                         buf[12] = 'L';
421                         buf[13] = 'D';
422                         disabled = true;
423                 }
424                 else if(!strncmp(buf, "-----END RSA", 12)) {    
425                         buf[ 9] = 'O';
426                         buf[10] = 'L';
427                         buf[11] = 'D';
428                         disabled = true;
429                 }
430                 if(w && fputs(buf, w) < 0) {
431                         disabled = false;
432                         break;
433                 }
434         }
435
436         if(w)
437                 fclose(w);
438         fclose(r);
439
440         if(!w && disabled) {
441                 fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
442                 return;
443         }
444
445         if(disabled) {
446 #ifdef HAVE_MINGW
447                 // We cannot atomically replace files on Windows.
448                 char bakfile[PATH_MAX] = "";
449                 snprintf(bakfile, sizeof bakfile, "%s.bak", filename);
450                 if(rename(filename, bakfile) || rename(tmpfile, filename)) {
451                         rename(bakfile, filename);
452 #else
453                 if(rename(tmpfile, filename)) {
454 #endif
455                         fprintf(stderr, "Warning: old key(s) found, remove them by hand!\n");
456                 } else  {
457 #ifdef HAVE_MINGW
458                         unlink(bakfile);
459 #endif
460                         fprintf(stderr, "Warning: old key(s) found and disabled.\n");
461                 }
462         }
463
464         unlink(tmpfile);
465 }
466
467 FILE *ask_and_open(const char *filename, const char *what) {
468         FILE *r;
469         char *directory;
470         char line[PATH_MAX];
471         const char *fn;
472
473         /* Check stdin and stdout */
474         if(!isatty(0) || !isatty(1)) {
475                 /* Argh, they are running us from a script or something.  Write
476                    the files to the current directory and let them burn in hell
477                    for ever. */
478                 fn = filename;
479         } else {
480                 /* Ask for a file and/or directory name. */
481                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
482                                 what, filename);
483                 fflush(stdout);
484
485                 fn = readline(stdin, line, sizeof line);
486
487                 if(!fn) {
488                         fprintf(stderr, "Error while reading stdin: %s\n",
489                                         strerror(errno));
490                         return NULL;
491                 }
492
493                 if(!strlen(fn))
494                         /* User just pressed enter. */
495                         fn = filename;
496         }
497
498 #ifdef HAVE_MINGW
499         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
500 #else
501         if(fn[0] != '/') {
502 #endif
503                 /* The directory is a relative path or a filename. */
504                 char *p;
505
506                 directory = get_current_dir_name();
507                 xasprintf(&p, "%s/%s", directory, fn);
508                 free(directory);
509                 fn = p;
510         }
511
512         umask(0077);                            /* Disallow everything for group and other */
513
514         disable_old_keys(fn);
515
516         /* Open it first to keep the inode busy */
517
518         r = fopen(fn, "a");
519
520         if(!r) {
521                 fprintf(stderr, "Error opening file `%s': %s\n",
522                                 fn, strerror(errno));
523                 return NULL;
524         }
525
526         return r;
527 }
528
529