b895b7f6fc022e53796707ac64ec8cc672333178
[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 "logger.h"
30 #include "netutl.h"                             /* for str2address */
31 #include "protocol.h"
32 #include "utils.h"                              /* for cp */
33 #include "xalloc.h"
34
35 avl_tree_t *config_tree;
36
37 int pinginterval = 0;                   /* seconds between pings */
38 int pingtimeout = 0;                    /* seconds to wait for response */
39 char *confbase = NULL;                  /* directory in which all config files are */
40 char *netname = NULL;                   /* name of the vpn network */
41 list_t *cmdline_conf = NULL;    /* global/host configuration values given at the command line */
42
43
44 static int config_compare(const config_t *a, const config_t *b) {
45         int result;
46
47         result = strcasecmp(a->variable, b->variable);
48
49         if(result)
50                 return result;
51
52         /* give priority to command line options */
53         result = !b->file - !a->file;
54         if (result)
55                 return result;
56
57         result = a->line - b->line;
58
59         if(result)
60                 return result;
61         else
62                 return a->file ? strcmp(a->file, b->file) : 0;
63 }
64
65 void init_configuration(avl_tree_t ** config_tree) {
66         *config_tree = avl_alloc_tree((avl_compare_t) config_compare, (avl_action_t) free_config);
67 }
68
69 void exit_configuration(avl_tree_t ** config_tree) {
70         avl_delete_tree(*config_tree);
71         *config_tree = NULL;
72 }
73
74 config_t *new_config(void) {
75         return xmalloc_and_zero(sizeof(config_t));
76 }
77
78 void free_config(config_t *cfg) {
79         if(cfg->variable)
80                 free(cfg->variable);
81
82         if(cfg->value)
83                 free(cfg->value);
84
85         if(cfg->file)
86                 free(cfg->file);
87
88         free(cfg);
89 }
90
91 void config_add(avl_tree_t *config_tree, config_t *cfg) {
92         avl_insert(config_tree, cfg);
93 }
94
95 config_t *lookup_config(const avl_tree_t *config_tree, char *variable) {
96         config_t cfg, *found;
97
98         cfg.variable = variable;
99         cfg.file = NULL;
100         cfg.line = 0;
101
102         found = avl_search_closest_greater(config_tree, &cfg);
103
104         if(!found)
105                 return NULL;
106
107         if(strcasecmp(found->variable, variable))
108                 return NULL;
109
110         return found;
111 }
112
113 config_t *lookup_config_next(const avl_tree_t *config_tree, const config_t *cfg) {
114         avl_node_t *node;
115         config_t *found;
116
117         node = avl_search_node(config_tree, cfg);
118
119         if(node) {
120                 if(node->next) {
121                         found = node->next->data;
122
123                         if(!strcasecmp(found->variable, cfg->variable))
124                                 return found;
125                 }
126         }
127
128         return NULL;
129 }
130
131 bool get_config_bool(const config_t *cfg, bool *result) {
132         if(!cfg)
133                 return false;
134
135         if(!strcasecmp(cfg->value, "yes")) {
136                 *result = true;
137                 return true;
138         } else if(!strcasecmp(cfg->value, "no")) {
139                 *result = false;
140                 return true;
141         }
142
143         logger(LOG_ERR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
144                    cfg->variable, cfg->file, cfg->line);
145
146         return false;
147 }
148
149 bool get_config_int(const config_t *cfg, int *result) {
150         if(!cfg)
151                 return false;
152
153         if(sscanf(cfg->value, "%d", result) == 1)
154                 return true;
155
156         logger(LOG_ERR, "Integer expected for configuration variable %s in %s line %d",
157                    cfg->variable, cfg->file, cfg->line);
158
159         return false;
160 }
161
162 bool get_config_string(const config_t *cfg, char **result) {
163         if(!cfg)
164                 return false;
165
166         *result = xstrdup(cfg->value);
167
168         return true;
169 }
170
171 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
172         struct addrinfo *ai;
173
174         if(!cfg)
175                 return false;
176
177         ai = str2addrinfo(cfg->value, NULL, 0);
178
179         if(ai) {
180                 *result = ai;
181                 return true;
182         }
183
184         logger(LOG_ERR, "Hostname or IP address expected for configuration variable %s in %s line %d",
185                    cfg->variable, cfg->file, cfg->line);
186
187         return false;
188 }
189
190 bool get_config_subnet(const config_t *cfg, subnet_t ** result) {
191         subnet_t subnet = {NULL};
192
193         if(!cfg)
194                 return false;
195
196         if(!str2net(&subnet, cfg->value)) {
197                 logger(LOG_ERR, "Subnet expected for configuration variable %s in %s line %d",
198                            cfg->variable, cfg->file, cfg->line);
199                 return false;
200         }
201
202         /* Teach newbies what subnets are... */
203
204         if(((subnet.type == SUBNET_IPV4)
205                 && !maskcheck(&subnet.net.ipv4.address, subnet.net.ipv4.prefixlength, sizeof(ipv4_t)))
206                 || ((subnet.type == SUBNET_IPV6)
207                 && !maskcheck(&subnet.net.ipv6.address, subnet.net.ipv6.prefixlength, sizeof(ipv6_t)))) {
208                 logger(LOG_ERR, "Network address and prefix length do not match for configuration variable %s in %s line %d",
209                            cfg->variable, cfg->file, cfg->line);
210                 return false;
211         }
212
213         *(*result = new_subnet()) = subnet;
214
215         return true;
216 }
217
218 /*
219   Read exactly one line and strip the trailing newline if any.
220 */
221 static char *readline(FILE * fp, char *buf, size_t buflen) {
222         char *newline = NULL;
223         char *p;
224
225         if(feof(fp))
226                 return NULL;
227
228         p = fgets(buf, buflen, fp);
229
230         if(!p)
231                 return NULL;
232
233         newline = strchr(p, '\n');
234
235         if(!newline)
236                 return buf;
237
238         *newline = '\0';        /* kill newline */
239         if(newline > p && newline[-1] == '\r')  /* and carriage return if necessary */
240                 newline[-1] = '\0';
241
242         return buf;
243 }
244
245 config_t *parse_config_line(char *line, const char *fname, int lineno) {
246         config_t *cfg;
247         int len;
248         char *variable, *value, *eol;
249         variable = value = line;
250
251         eol = line + strlen(line);
252         while(strchr("\t ", *--eol))
253                 *eol = '\0';
254
255         len = strcspn(value, "\t =");
256         value += len;
257         value += strspn(value, "\t ");
258         if(*value == '=') {
259                 value++;
260                 value += strspn(value, "\t ");
261         }
262         variable[len] = '\0';
263
264         if(!*value) {
265                 const char err[] = "No value for variable";
266                 if (fname)
267                         logger(LOG_ERR, "%s `%s' on line %d while reading config file %s",
268                                 err, variable, lineno, fname);
269                 else
270                         logger(LOG_ERR, "%s `%s' in command line option %d",
271                                 err, variable, lineno);
272                 return NULL;
273         }
274
275         cfg = new_config();
276         cfg->variable = xstrdup(variable);
277         cfg->value = xstrdup(value);
278         cfg->file = fname ? xstrdup(fname) : NULL;
279         cfg->line = lineno;
280
281         return cfg;
282 }
283
284 /*
285   Parse a configuration file and put the results in the configuration tree
286   starting at *base.
287 */
288 bool read_config_file(avl_tree_t *config_tree, const char *fname) {
289         FILE *fp;
290         char buffer[MAX_STRING_SIZE];
291         char *line;
292         int lineno = 0;
293         bool ignore = false;
294         config_t *cfg;
295         bool result = false;
296
297         fp = fopen(fname, "r");
298
299         if(!fp) {
300                 logger(LOG_ERR, "Cannot open config file %s: %s", fname, strerror(errno));
301                 return false;
302         }
303
304         for(;;) {
305                 line = readline(fp, buffer, sizeof buffer);
306
307                 if(!line) {
308                         if(feof(fp))
309                                 result = true;
310                         break;
311                 }
312
313                 lineno++;
314
315                 if(!*line || *line == '#')
316                         continue;
317
318                 if(ignore) {
319                         if(!strncmp(line, "-----END", 8))
320                                 ignore = false;
321                         continue;
322                 }
323                 
324                 if(!strncmp(line, "-----BEGIN", 10)) {
325                         ignore = true;
326                         continue;
327                 }
328
329                 cfg = parse_config_line(line, fname, lineno);
330                 if (!cfg)
331                         break;
332                 config_add(config_tree, cfg);
333         }
334
335         fclose(fp);
336
337         return result;
338 }
339
340 void read_config_options(avl_tree_t *config_tree, const char *prefix) {
341         list_node_t *node, *next;
342         size_t prefix_len = prefix ? strlen(prefix) : 0;
343
344         for(node = cmdline_conf->tail; node; node = next) {
345                 config_t *orig_cfg, *cfg = (config_t *)node->data;
346                 next = node->prev;
347
348                 if(!prefix) {
349                         if(strchr(cfg->variable, '.'))
350                                 continue;
351                         node->data = NULL;
352                         list_unlink_node(cmdline_conf, node);
353                 } else {
354                         if(strncmp(prefix, cfg->variable, prefix_len) ||
355                            cfg->variable[prefix_len] != '.')
356                                 continue;
357                         /* Because host configuration is parsed again when
358                            reconnecting, nodes must not be freed when a prefix
359                            is given. */
360                         orig_cfg = cfg;
361                         cfg = new_config();
362                         cfg->variable = xstrdup(orig_cfg->variable + prefix_len + 1);
363                         cfg->value = xstrdup(orig_cfg->value);
364                         cfg->file = NULL;
365                         cfg->line = orig_cfg->line;
366                 }
367                 config_add(config_tree, cfg);
368         }
369 }
370
371 bool read_server_config(void) {
372         char *fname;
373         bool x;
374
375         read_config_options(config_tree, NULL);
376
377         xasprintf(&fname, "%s/tinc.conf", confbase);
378         x = read_config_file(config_tree, fname);
379
380         if(!x) {                                /* System error: complain */
381                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
382         }
383
384         free(fname);
385
386         return x;
387 }
388
389 bool read_connection_config(connection_t *c) {
390         char *fname;
391         bool x;
392
393         read_config_options(c->config_tree, c->name);
394
395         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
396         x = read_config_file(c->config_tree, fname);
397         free(fname);
398
399         return x;
400 }
401
402 FILE *ask_and_open(const char *filename, const char *what) {
403         FILE *r;
404         char *directory;
405         char line[PATH_MAX];
406         const char *fn;
407
408         /* Check stdin and stdout */
409         if(!isatty(0) || !isatty(1)) {
410                 /* Argh, they are running us from a script or something.  Write
411                    the files to the current directory and let them burn in hell
412                    for ever. */
413                 fn = filename;
414         } else {
415                 /* Ask for a file and/or directory name. */
416                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
417                                 what, filename);
418                 fflush(stdout);
419
420                 fn = readline(stdin, line, sizeof line);
421
422                 if(!fn) {
423                         fprintf(stderr, "Error while reading stdin: %s\n",
424                                         strerror(errno));
425                         return NULL;
426                 }
427
428                 if(!strlen(fn))
429                         /* User just pressed enter. */
430                         fn = filename;
431         }
432
433 #ifdef HAVE_MINGW
434         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
435 #else
436         if(fn[0] != '/') {
437 #endif
438                 /* The directory is a relative path or a filename. */
439                 char *p;
440
441                 directory = get_current_dir_name();
442                 xasprintf(&p, "%s/%s", directory, fn);
443                 free(directory);
444                 fn = p;
445         }
446
447         umask(0077);                            /* Disallow everything for group and other */
448
449         /* Open it first to keep the inode busy */
450
451         r = fopen(fn, "r+") ?: fopen(fn, "w+");
452
453         if(!r) {
454                 fprintf(stderr, "Error opening file `%s': %s\n",
455                                 fn, strerror(errno));
456                 return NULL;
457         }
458
459         return r;
460 }
461
462 bool disable_old_keys(FILE *f) {
463         char buf[100];
464         long pos;
465         bool disabled = false;
466
467         rewind(f);
468         pos = ftell(f);
469
470         if(pos < 0)
471                 return false;
472
473         while(fgets(buf, sizeof buf, f)) {
474                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {       
475                         buf[11] = 'O';
476                         buf[12] = 'L';
477                         buf[13] = 'D';
478                         if(fseek(f, pos, SEEK_SET))
479                                 break;
480                         if(fputs(buf, f) <= 0)
481                                 break;
482                         disabled = true;
483                 }
484                 else if(!strncmp(buf, "-----END RSA", 12)) {    
485                         buf[ 9] = 'O';
486                         buf[10] = 'L';
487                         buf[11] = 'D';
488                         if(fseek(f, pos, SEEK_SET))
489                                 break;
490                         if(fputs(buf, f) <= 0)
491                                 break;
492                         disabled = true;
493                 }
494                 pos = ftell(f);
495                 if(pos < 0)
496                         break;
497         }
498
499         return disabled;
500 }