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