]> git.meshlink.io Git - meshlink/blob - src/conf.c
Add a function to change a configuration file on disk.
[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                         logger(NULL, MESHLINK_ERROR, "Cannot write to config file %s: %s", fname, strerror(errno));
338                         return false;
339                 }
340
341                 if(fwrite(" = ", sizeof(char), 3, fp) < 3) {
342                         logger(NULL, MESHLINK_ERROR, "Cannot write to config file %s: %s", fname, strerror(errno));
343                         return false;
344                 }
345
346                 if(fwrite(cnf->value, sizeof(char), strlen(cnf->value), fp) < strlen(cnf->value)) {
347                         logger(NULL, MESHLINK_ERROR, "Cannot write to config file %s: %s", fname, strerror(errno));
348                         return false;
349                 }
350
351                 if(fwrite("\n", sizeof(char), 1, fp) < 1) {
352                         logger(NULL, MESHLINK_ERROR, "Cannot write to config file %s: %s", fname, strerror(errno));
353                         return false;
354                 }
355         }
356
357         fclose(fp);
358
359         return true;
360 }
361
362 bool read_server_config(meshlink_handle_t *mesh) {
363         char filename[PATH_MAX];
364         bool x;
365
366         snprintf(filename, PATH_MAX,"%s" SLASH "meshlink.conf", mesh->confbase);
367         errno = 0;
368         x = read_config_file(mesh->config, filename);
369
370         if(!x && errno)
371                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", filename, strerror(errno));
372
373         return x;
374 }
375
376 bool read_host_config(meshlink_handle_t *mesh, splay_tree_t *config_tree, const char *name) {
377         char filename[PATH_MAX];
378         bool x;
379
380         snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
381         x = read_config_file(config_tree, filename);
382
383         return x;
384 }
385
386 bool write_host_config(struct meshlink_handle *mesh, const struct splay_tree_t *config_tree, const char *name)
387 {
388         char filename[PATH_MAX];
389
390         snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
391         return write_config_file(config_tree, filename);
392 }
393
394 bool change_config_file(meshlink_handle_t *mesh, const char *name, const char *key, const char *value) {
395         char filename[PATH_MAX];
396         char tmpname[PATH_MAX];
397         char buf[MAX_STRING_SIZE];
398         const int keylen = strlen(key);
399
400         snprintf(filename, PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
401         snprintf(tmpname, PATH_MAX, "%s.tmp", filename);
402
403         FILE *in = fopen(filename, "r");
404         if(!in) {
405                 // Hm, maybe the file does not exist? Try appending.
406                 return append_config_file(mesh, name, key, value);
407         }
408
409         FILE *out = fopen(tmpname, "w");
410         if(!out) {
411                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmpname, strerror(errno));
412                 fclose(in);
413                 return false;
414         }
415
416         bool ignore = false;
417
418         while(readline(in, buf, sizeof buf)) {
419                 if(ignore) {
420                         if(!strncmp(buf, "-----END", 8))
421                                 ignore = false;
422                 } else {
423                         if(!strncmp(buf, "-----BEGIN", 10))
424                                 ignore = true;
425                 }
426
427                 if(!ignore && !strncmp(buf, key, keylen)) {
428                         if(strchr("\t =", buf[keylen])) {
429                                 continue;
430                         }
431                 }
432
433                 fputs(buf, out);
434                 fputc('\n', out);
435         }       
436
437         if(ferror(in)) {
438                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", filename, strerror(errno));
439                 fclose(in);
440                 fclose(out);
441                 return false;
442         }
443
444         fclose(in);
445
446         fprintf(out, "%s = %s\n", key, value);
447
448         if(ferror(out)) {
449                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmpname, strerror(errno));
450                 fclose(out);
451                 return false;
452         }
453
454         fclose(out);
455
456 #ifdef HAVE_MINGW
457         // We cannot atomically replace files on Windows.
458         char bakname[PATH_MAX];
459         snprintf(bakname, PATH_MAX, "%s.bak", filename);
460         if(rename(tmpname, bakfile) || rename(bakfile, filename)) {
461                 rename(bakfile, filename);
462 #else
463         if(rename(tmpname, filename)) {
464 #endif
465                 logger(mesh, MESHLINK_ERROR, "Failed to update `%s': %s", filename, strerror(errno));
466                 return false;
467         }
468
469         return true;
470 }
471
472 bool append_config_file(meshlink_handle_t *mesh, const char *name, const char *key, const char *value) {
473         char filename[PATH_MAX];
474         snprintf(filename,PATH_MAX, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
475
476         FILE *fp = fopen(filename, "a");
477
478         if(!fp) {
479                 logger(mesh, MESHLINK_ERROR, "Cannot open config file %s: %s", filename, strerror(errno));
480         } else {
481                 fprintf(fp, "%s = %s\n", key, value);
482                 fclose(fp);
483         }
484
485         return fp != NULL;
486 }