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