Attribution for Julien Muchembled.
[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 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(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(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 = {0};
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 = strlen(prefix);
343
344         for(node = cmdline_conf->tail; node; node = next) {
345                 config_t *cfg = (config_t *)node->data;
346                 next = node->prev;
347
348                 if(!prefix && strchr(cfg->variable, '.'))
349                         continue;
350
351                 if(prefix && (strncmp(prefix, cfg->variable, prefix_len) || cfg->variable[prefix_len] != '.'))
352                         continue;
353
354                 config_add(config_tree, cfg);
355                 node->data = NULL;
356                 list_unlink_node(cmdline_conf, node);
357         }
358 }
359
360 bool read_server_config() {
361         list_node_t *node, *next;
362         char *fname;
363         bool x;
364
365         read_config_options(config_tree, NULL);
366
367         xasprintf(&fname, "%s/tinc.conf", confbase);
368         x = read_config_file(config_tree, fname);
369
370         if(!x) {                                /* System error: complain */
371                 logger(LOG_ERR, "Failed to read `%s': %s", fname, strerror(errno));
372         }
373
374         free(fname);
375
376         return x;
377 }
378
379 bool read_connection_config(connection_t *c) {
380         list_node_t *node, *next;
381         size_t name_len = strlen(c->name);
382         char *fname;
383         bool x;
384
385         read_config_options(c->config_tree, c->name);
386
387         xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
388         x = read_config_file(c->config_tree, fname);
389         free(fname);
390
391         return x;
392 }
393
394 FILE *ask_and_open(const char *filename, const char *what) {
395         FILE *r;
396         char *directory;
397         char line[PATH_MAX];
398         const char *fn;
399
400         /* Check stdin and stdout */
401         if(!isatty(0) || !isatty(1)) {
402                 /* Argh, they are running us from a script or something.  Write
403                    the files to the current directory and let them burn in hell
404                    for ever. */
405                 fn = filename;
406         } else {
407                 /* Ask for a file and/or directory name. */
408                 fprintf(stdout, "Please enter a file to save %s to [%s]: ",
409                                 what, filename);
410                 fflush(stdout);
411
412                 fn = readline(stdin, line, sizeof line);
413
414                 if(!fn) {
415                         fprintf(stderr, "Error while reading stdin: %s\n",
416                                         strerror(errno));
417                         return NULL;
418                 }
419
420                 if(!strlen(fn))
421                         /* User just pressed enter. */
422                         fn = filename;
423         }
424
425 #ifdef HAVE_MINGW
426         if(fn[0] != '\\' && fn[0] != '/' && !strchr(fn, ':')) {
427 #else
428         if(fn[0] != '/') {
429 #endif
430                 /* The directory is a relative path or a filename. */
431                 char *p;
432
433                 directory = get_current_dir_name();
434                 xasprintf(&p, "%s/%s", directory, fn);
435                 free(directory);
436                 fn = p;
437         }
438
439         umask(0077);                            /* Disallow everything for group and other */
440
441         /* Open it first to keep the inode busy */
442
443         r = fopen(fn, "r+") ?: fopen(fn, "w+");
444
445         if(!r) {
446                 fprintf(stderr, "Error opening file `%s': %s\n",
447                                 fn, strerror(errno));
448                 return NULL;
449         }
450
451         return r;
452 }
453
454 bool disable_old_keys(FILE *f) {
455         char buf[100];
456         long pos;
457         bool disabled = false;
458
459         rewind(f);
460         pos = ftell(f);
461
462         while(fgets(buf, sizeof buf, f)) {
463                 if(!strncmp(buf, "-----BEGIN RSA", 14)) {       
464                         buf[11] = 'O';
465                         buf[12] = 'L';
466                         buf[13] = 'D';
467                         fseek(f, pos, SEEK_SET);
468                         fputs(buf, f);
469                         disabled = true;
470                 }
471                 else if(!strncmp(buf, "-----END RSA", 12)) {    
472                         buf[ 9] = 'O';
473                         buf[10] = 'L';
474                         buf[11] = 'D';
475                         fseek(f, pos, SEEK_SET);
476                         fputs(buf, f);
477                         disabled = true;
478                 }
479                 pos = ftell(f);
480         }
481
482         return disabled;
483 }