Rename connection_t *broadcast to everyone.
[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 FILE *ask_and_open(const char *filename, const char *what) {
404         FILE *r;
405         char *directory;
406         char line[PATH_MAX];
407         const char *fn;
408
409         /* Check stdin and stdout */
410         if(!isatty(0) || !isatty(1)) {
411                 /* Argh, they are running us from a script or something.  Write
412                    the files to the current directory and let them burn in hell
413                    for ever. */
414                 fn = filename;
415         } else {
416                 /* Ask for a file and/or directory name. */
417                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
418                                 what, filename);
419                 fflush(stdout);
420
421                 fn = readline(stdin, line, sizeof line);
422
423                 if(!fn) {
424                         fprintf(stderr, "Error while reading stdin: %s\n",
425                                         strerror(errno));
426                         return NULL;
427                 }
428
429                 if(!strlen(fn))
430                         /* User just pressed enter. */
431                         fn = filename;
432         }
433
434 #ifdef HAVE_MINGW
435         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
436 #else
437         if(fn[0] != '/') {
438 #endif
439                 /* The directory is a relative path or a filename. */
440                 char *p;
441
442                 directory = get_current_dir_name();
443                 xasprintf(&p, "%s/%s", directory, fn);
444                 free(directory);
445                 fn = p;
446         }
447
448         umask(0077);                            /* Disallow everything for group and other */
449
450         /* Open it first to keep the inode busy */
451
452         r = fopen(fn, "r+") ?: fopen(fn, "w+");
453
454         if(!r) {
455                 fprintf(stderr, "Error opening file `%s': %s\n",
456                                 fn, strerror(errno));
457                 return NULL;
458         }
459
460         return r;
461 }
462
463 bool disable_old_keys(FILE *f) {
464         char buf[100];
465         long pos;
466         bool disabled = false;
467
468         rewind(f);
469         pos = ftell(f);
470
471         if(pos < 0)
472                 return false;
473
474         while(fgets(buf, sizeof buf, f)) {
475                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {       
476                         buf[11] = 'O';
477                         buf[12] = 'L';
478                         buf[13] = 'D';
479                         if(fseek(f, pos, SEEK_SET))
480                                 break;
481                         if(fputs(buf, f) <= 0)
482                                 break;
483                         disabled = true;
484                 }
485                 else if(!strncmp(buf, "-----END RSA", 12)) {    
486                         buf[ 9] = 'O';
487                         buf[10] = 'L';
488                         buf[11] = 'D';
489                         if(fseek(f, pos, SEEK_SET))
490                                 break;
491                         if(fputs(buf, f) <= 0)
492                                 break;
493                         disabled = true;
494                 }
495                 pos = ftell(f);
496                 if(pos < 0)
497                         break;
498         }
499
500         return disabled;
501 }