]> git.meshlink.io Git - meshlink/blob - src/conf.c
ef595efca958f8cdb22ad240f41fb4f09864f0d1
[meshlink] / src / conf.c
1 /*
2     conf.c -- configuration code
3     Copyright (C) 2014 Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "splay_tree.h"
23 #include "connection.h"
24 #include "conf.h"
25 #include "list.h"
26 #include "logger.h"
27 #include "meshlink_internal.h"
28 #include "netutl.h"             /* for str2address */
29 #include "protocol.h"
30 #include "utils.h"              /* for cp */
31 #include "xalloc.h"
32
33 static int config_compare(const config_t *a, const config_t *b) {
34         int result;
35
36         result = strcasecmp(a->variable, b->variable);
37
38         if(result)
39                 return result;
40
41         result = a->line - b->line;
42
43         if(result)
44                 return result;
45         else
46                 return a->file ? strcmp(a->file, b->file) : 0;
47 }
48
49 void init_configuration(splay_tree_t **config_tree) {
50         *config_tree = splay_alloc_tree((splay_compare_t) config_compare, (splay_action_t) free_config);
51 }
52
53 void exit_configuration(splay_tree_t **config_tree) {
54         if(*config_tree)
55                 splay_delete_tree(*config_tree);
56         *config_tree = NULL;
57 }
58
59 config_t *new_config(void) {
60         return xzalloc(sizeof(config_t));
61 }
62
63 void free_config(config_t *cfg) {
64         if(cfg->variable)
65                 free(cfg->variable);
66
67         if(cfg->value)
68                 free(cfg->value);
69
70         if(cfg->file)
71                 free(cfg->file);
72
73         free(cfg);
74 }
75
76 void config_add(splay_tree_t *config_tree, config_t *cfg) {
77         splay_insert(config_tree, cfg);
78 }
79
80 config_t *lookup_config(splay_tree_t *config_tree, char *variable) {
81         config_t cfg, *found;
82
83         cfg.variable = variable;
84         cfg.file = NULL;
85         cfg.line = 0;
86
87         found = splay_search_closest_greater(config_tree, &cfg);
88
89         if(!found)
90                 return NULL;
91
92         if(strcasecmp(found->variable, variable))
93                 return NULL;
94
95         return found;
96 }
97
98 config_t *lookup_config_next(splay_tree_t *config_tree, const config_t *cfg) {
99         splay_node_t *node;
100         config_t *found;
101
102         node = splay_search_node(config_tree, cfg);
103
104         if(node) {
105                 if(node->next) {
106                         found = node->next->data;
107
108                         if(!strcasecmp(found->variable, cfg->variable))
109                                 return found;
110                 }
111         }
112
113         return NULL;
114 }
115
116 bool get_config_bool(const config_t *cfg, bool *result) {
117         if(!cfg)
118                 return false;
119
120         if(!strcasecmp(cfg->value, "yes")) {
121                 *result = true;
122                 return true;
123         } else if(!strcasecmp(cfg->value, "no")) {
124                 *result = false;
125                 return true;
126         }
127
128         logger(NULL, MESHLINK_ERROR, "\"yes\" or \"no\" expected for configuration variable %s in %s line %d",
129                    cfg->variable, cfg->file, cfg->line);
130
131         return false;
132 }
133
134 bool get_config_int(const config_t *cfg, int *result) {
135         if(!cfg)
136                 return false;
137
138         if(sscanf(cfg->value, "%d", result) == 1)
139                 return true;
140
141         logger(NULL, MESHLINK_ERROR, "Integer expected for configuration variable %s in %s line %d",
142                    cfg->variable, cfg->file, cfg->line);
143
144         return false;
145 }
146
147 bool set_config_int(config_t *cfg, int val)
148 {
149         if(!cfg)
150                 return false;
151
152         char val_str[1024];
153         snprintf(val_str, sizeof(val_str), "%d", val);
154
155         if(cfg->value)
156                 free(cfg->value);
157
158         cfg->value = xstrdup(val_str);
159
160         return true;
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 set_config_string(config_t *cfg, const char* val)
173 {
174         if(!cfg)
175                 return false;
176
177         if(cfg->value)
178                 free(cfg->value);
179
180         cfg->value = xstrdup(val);
181
182         return true;
183 }
184
185 bool get_config_address(const config_t *cfg, struct addrinfo **result) {
186         struct addrinfo *ai;
187
188         if(!cfg)
189                 return false;
190
191         ai = str2addrinfo(cfg->value, NULL, 0);
192
193         if(ai) {
194                 *result = ai;
195                 return true;
196         }
197
198         logger(NULL, MESHLINK_ERROR, "Hostname or IP address expected for configuration variable %s in %s line %d",
199                    cfg->variable, cfg->file, cfg->line);
200
201         return false;
202 }
203
204 /*
205   Read exactly one line and strip the trailing newline if any.
206 */
207 static char *readline(FILE * fp, char *buf, size_t buflen) {
208         char *newline = NULL;
209         char *p;
210
211         if(feof(fp))
212                 return NULL;
213
214         p = fgets(buf, buflen, fp);
215
216         if(!p)
217                 return NULL;
218
219         newline = strchr(p, '\n');
220
221         if(!newline)
222                 return buf;
223
224         /* kill newline and carriage return if necessary */
225         *newline = '\0';
226         if(newline > p && newline[-1] == '\r')
227                 newline[-1] = '\0';
228
229         return buf;
230 }
231
232 config_t *parse_config_line(char *line, const char *fname, int lineno) {
233         config_t *cfg;
234         int len;
235         char *variable, *value, *eol;
236         variable = value = line;
237
238         eol = line + strlen(line);
239         while(strchr("\t ", *--eol))
240                 *eol = '\0';
241
242         len = strcspn(value, "\t =");
243         value += len;
244         value += strspn(value, "\t ");
245         if(*value == '=') {
246                 value++;
247                 value += strspn(value, "\t ");
248         }
249         variable[len] = '\0';
250
251         if(!*value) {
252                 const char err[] = "No value for variable";
253                 logger(NULL, MESHLINK_ERROR, "%s `%s' on line %d while reading config file %s",
254                         err, variable, lineno, fname);
255                 return NULL;
256         }
257
258         cfg = new_config();
259         cfg->variable = xstrdup(variable);
260         cfg->value = xstrdup(value);
261         cfg->file = xstrdup(fname);
262         cfg->line = lineno;
263
264         return cfg;
265 }
266
267 /*
268   Parse a configuration file and put the results in the configuration tree
269   starting at *base.
270 */
271 bool read_config_file(splay_tree_t *config_tree, const char *fname) {
272         FILE *fp;
273         char buffer[MAX_STRING_SIZE];
274         char *line;
275         int lineno = 0;
276         bool ignore = false;
277         config_t *cfg;
278         bool result = false;
279
280         fp = fopen(fname, "r");
281
282         if(!fp) {
283                 logger(NULL, MESHLINK_ERROR, "Cannot open config file %s: %s", fname, strerror(errno));
284                 return false;
285         }
286
287         for(;;) {
288                 line = readline(fp, buffer, sizeof buffer);
289
290                 if(!line) {
291                         if(feof(fp))
292                                 result = true;
293                         break;
294                 }
295
296                 lineno++;
297
298                 if(!*line || *line == '#')
299                         continue;
300
301                 if(ignore) {
302                         if(!strncmp(line, "-----END", 8))
303                                 ignore = false;
304                         continue;
305                 }
306
307                 if(!strncmp(line, "-----BEGIN", 10)) {
308                         ignore = true;
309                         continue;
310                 }
311
312                 cfg = parse_config_line(line, fname, lineno);
313                 if (!cfg)
314                         break;
315                 config_add(config_tree, cfg);
316         }
317
318         fclose(fp);
319
320         return result;
321 }
322
323 bool write_config_file(const struct splay_tree_t *config_tree, const char *fname)
324 {
325         FILE *fp;
326
327         fp = fopen(fname, "w+");
328
329         if(!fp) {
330                 logger(NULL, MESHLINK_ERROR, "Cannot open config file %s: %s", fname, strerror(errno));
331                 return false;
332         }
333
334         for splay_each(config_t, cnf, config_tree)
335         {
336                 if(fwrite(cnf->variable, sizeof(char), strlen(cnf->variable), fp) < strlen(cnf->variable))
337                         goto error;
338
339                 if(fwrite(" = ", sizeof(char), 3, fp) < 3)
340                         goto error;
341
342                 if(fwrite(cnf->value, sizeof(char), strlen(cnf->value), fp) < strlen(cnf->value))
343                         goto error;
344
345                 if(fwrite("\n", sizeof(char), 1, fp) < 1)
346                         goto error;
347         }
348
349         fclose(fp);
350         return true;
351
352 error:
353         logger(NULL, MESHLINK_ERROR, "Cannot write to config file %s: %s", fname, strerror(errno));
354         fclose(fp);
355         return false;
356 }
357
358 bool read_server_config(meshlink_handle_t *mesh) {
359         char filename[PATH_MAX];
360         bool x;
361
362         snprintf(filename, PATH_MAX,"%s" SLASH "meshlink.conf", mesh->confbase);
363         errno = 0;
364         x = read_config_file(mesh->config, filename);
365
366         if(!x && errno)
367                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", filename, strerror(errno));
368
369         return x;
370 }
371
372 bool read_host_config(meshlink_handle_t *mesh, splay_tree_t *config_tree, const char *name) {
373         char filename[PATH_MAX];
374         bool x;
375
376         snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
377         x = read_config_file(config_tree, filename);
378
379         return x;
380 }
381
382 bool write_host_config(struct meshlink_handle *mesh, const struct splay_tree_t *config_tree, const char *name)
383 {
384         char filename[PATH_MAX];
385
386         snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
387         return write_config_file(config_tree, filename);
388 }
389
390 bool change_config_file(meshlink_handle_t *mesh, const char *name, const char *key, const char *value) {
391         char filename[PATH_MAX];
392         char tmpname[PATH_MAX];
393         char buf[MAX_STRING_SIZE];
394         const int keylen = strlen(key);
395
396         snprintf(filename, PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
397         snprintf(tmpname, PATH_MAX, "%s.tmp", filename);
398
399         FILE *in = fopen(filename, "r");
400         if(!in) {
401                 // Hm, maybe the file does not exist? Try appending.
402                 return append_config_file(mesh, name, key, value);
403         }
404
405         FILE *out = fopen(tmpname, "w");
406         if(!out) {
407                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmpname, strerror(errno));
408                 fclose(in);
409                 return false;
410         }
411
412         bool ignore = false;
413
414         while(readline(in, buf, sizeof buf)) {
415                 if(ignore) {
416                         if(!strncmp(buf, "-----END", 8))
417                                 ignore = false;
418                 } else {
419                         if(!strncmp(buf, "-----BEGIN", 10))
420                                 ignore = true;
421                 }
422
423                 if(!ignore && !strncmp(buf, key, keylen)) {
424                         if(strchr("\t =", buf[keylen])) {
425                                 continue;
426                         }
427                 }
428
429                 fputs(buf, out);
430                 fputc('\n', out);
431         }       
432
433         if(ferror(in)) {
434                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", filename, strerror(errno));
435                 fclose(in);
436                 fclose(out);
437                 return false;
438         }
439
440         fclose(in);
441
442         fprintf(out, "%s = %s\n", key, value);
443
444         if(ferror(out)) {
445                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmpname, strerror(errno));
446                 fclose(out);
447                 return false;
448         }
449
450         fclose(out);
451
452 #ifdef HAVE_MINGW
453         // We cannot atomically replace files on Windows.
454         char bakname[PATH_MAX];
455         snprintf(bakname, PATH_MAX, "%s.bak", filename);
456         if(rename(tmpname, bakfile) || rename(bakfile, filename)) {
457                 rename(bakfile, filename);
458 #else
459         if(rename(tmpname, filename)) {
460 #endif
461                 logger(mesh, MESHLINK_ERROR, "Failed to update `%s': %s", filename, strerror(errno));
462                 return false;
463         }
464
465         return true;
466 }
467
468 bool append_config_file(meshlink_handle_t *mesh, const char *name, const char *key, const char *value) {
469         char filename[PATH_MAX];
470         snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
471
472         FILE *fp = fopen(filename, "a");
473
474         if(!fp) {
475                 logger(mesh, MESHLINK_ERROR, "Cannot open config file %s: %s", filename, strerror(errno));
476                 return false;
477         }
478
479         // Check if we don't add a duplicate entry
480
481         char entry[MAX_STRING_SIZE];
482         snprintf(entry, sizeof entry, "%s = %s", key, value);
483
484         char buffer[MAX_STRING_SIZE];
485         bool found = false;
486
487         while(readline(fp, buffer, sizeof buffer)) {
488                 if(!strcmp(buffer, entry)) {
489                         found = true;
490                         break;
491                 }
492         }
493
494         // If not, append the new entry
495
496         if(!found)
497                 fprintf(fp, "%s\n", entry);
498
499         fclose(fp);
500         return true;
501 }