]> git.meshlink.io Git - meshlink/blob - src/conf.c
Avoid allocating packet buffers unnecessarily.
[meshlink] / src / conf.c
1 /*
2     econf.c -- configuration code
3     Copyright (C) 2018 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 #include <sys/types.h>
23 #include <utime.h>
24
25 #include "conf.h"
26 #include "crypto.h"
27 #include "logger.h"
28 #include "meshlink_internal.h"
29 #include "xalloc.h"
30 #include "packmsg.h"
31
32 /// Generate a path to the main configuration file.
33 static void make_main_path(meshlink_handle_t *mesh, const char *conf_subdir, char *path, size_t len) {
34         assert(conf_subdir);
35         assert(path);
36         assert(len);
37
38         snprintf(path, len, "%s" SLASH "%s" SLASH "meshlink.conf", mesh->confbase, conf_subdir);
39 }
40
41 /// Generate a path to a host configuration file.
42 static void make_host_path(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, char *path, size_t len) {
43         assert(conf_subdir);
44         assert(name);
45         assert(path);
46         assert(len);
47
48         snprintf(path, len, "%s" SLASH "%s" SLASH "hosts" SLASH "%s", mesh->confbase, conf_subdir, name);
49 }
50
51 /// Generate a path to an unused invitation file.
52 static void make_invitation_path(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, char *path, size_t len) {
53         assert(conf_subdir);
54         assert(name);
55         assert(path);
56         assert(len);
57
58         snprintf(path, len, "%s" SLASH "%s" SLASH "invitations" SLASH "%s", mesh->confbase, conf_subdir, name);
59 }
60
61 /// Generate a path to a used invitation file.
62 static void make_used_invitation_path(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, char *path, size_t len) {
63         assert(conf_subdir);
64         assert(name);
65         assert(path);
66         assert(len);
67
68         snprintf(path, len, "%s" SLASH "%s" SLASH "invitations" SLASH "%s.used", mesh->confbase, conf_subdir, name);
69 }
70
71 /// Remove a directory recursively
72 static bool deltree(const char *dirname) {
73         assert(dirname);
74
75         DIR *d = opendir(dirname);
76
77         if(d) {
78                 struct dirent *ent;
79
80                 while((ent = readdir(d))) {
81                         if(ent->d_name[0] == '.') {
82                                 continue;
83                         }
84
85                         char filename[PATH_MAX];
86                         snprintf(filename, sizeof(filename), "%s" SLASH "%s", dirname, ent->d_name);
87
88                         if(unlink(filename)) {
89                                 if(!deltree(filename)) {
90                                         return false;
91                                 }
92                         }
93                 }
94
95                 closedir(d);
96         } else {
97                 return errno == ENOENT;
98         }
99
100         return rmdir(dirname) == 0;
101 }
102
103 bool sync_path(const char *pathname) {
104         assert(pathname);
105
106         int fd = open(pathname, O_RDONLY);
107
108         if(fd < 0) {
109                 logger(NULL, MESHLINK_ERROR, "Failed to open %s: %s\n", pathname, strerror(errno));
110                 meshlink_errno = MESHLINK_ESTORAGE;
111                 return false;
112         }
113
114         if(fsync(fd)) {
115                 logger(NULL, MESHLINK_ERROR, "Failed to sync %s: %s\n", pathname, strerror(errno));
116                 close(fd);
117                 meshlink_errno = MESHLINK_ESTORAGE;
118                 return false;
119         }
120
121         if(close(fd)) {
122                 logger(NULL, MESHLINK_ERROR, "Failed to close %s: %s\n", pathname, strerror(errno));
123                 close(fd);
124                 meshlink_errno = MESHLINK_ESTORAGE;
125                 return false;
126         }
127
128         return true;
129 }
130
131 /// Try decrypting the main configuration file from the given sub-directory.
132 static bool main_config_decrypt(meshlink_handle_t *mesh, const char *conf_subdir) {
133         assert(mesh->config_key);
134         assert(mesh->confbase);
135         assert(conf_subdir);
136
137         config_t config;
138
139         if(!main_config_read(mesh, conf_subdir, &config, mesh->config_key)) {
140                 logger(mesh, MESHLINK_ERROR, "Could not read main configuration file");
141                 return false;
142         }
143
144         packmsg_input_t in = {config.buf, config.len};
145
146         uint32_t version = packmsg_get_uint32(&in);
147         config_free(&config);
148
149         return version == MESHLINK_CONFIG_VERSION;
150 }
151
152 /// Create a fresh configuration directory
153 bool config_init(meshlink_handle_t *mesh, const char *conf_subdir) {
154         assert(conf_subdir);
155
156         if(!mesh->confbase) {
157                 return true;
158         }
159
160         char path[PATH_MAX];
161
162         // Create "current" sub-directory in the confbase
163         snprintf(path, sizeof(path), "%s" SLASH "%s", mesh->confbase, conf_subdir);
164
165         if(!deltree(path)) {
166                 logger(mesh, MESHLINK_DEBUG, "Could not delete directory %s: %s\n", path, strerror(errno));
167                 return false;
168         }
169
170         if(mkdir(path, 0700)) {
171                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", path, strerror(errno));
172                 return false;
173         }
174
175         make_host_path(mesh, conf_subdir, "", path, sizeof(path));
176
177         if(mkdir(path, 0700)) {
178                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", path, strerror(errno));
179                 return false;
180         }
181
182         make_invitation_path(mesh, conf_subdir, "", path, sizeof(path));
183
184         if(mkdir(path, 0700)) {
185                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", path, strerror(errno));
186                 return false;
187         }
188
189         return true;
190 }
191
192 /// Wipe an existing configuration directory
193 bool config_destroy(const char *confbase, const char *conf_subdir) {
194         assert(conf_subdir);
195
196         if(!confbase) {
197                 return true;
198         }
199
200         struct stat st;
201
202         char path[PATH_MAX];
203
204         // Check the presence of configuration base sub directory.
205         snprintf(path, sizeof(path), "%s" SLASH "%s", confbase, conf_subdir);
206
207         if(stat(path, &st)) {
208                 if(errno == ENOENT) {
209                         return true;
210                 } else {
211                         logger(NULL, MESHLINK_ERROR, "Cannot stat %s: %s\n", path, strerror(errno));
212                         meshlink_errno = MESHLINK_ESTORAGE;
213                         return false;
214                 }
215         }
216
217         // Remove meshlink.conf
218         snprintf(path, sizeof(path), "%s" SLASH "%s" SLASH "meshlink.conf", confbase, conf_subdir);
219
220         if(unlink(path)) {
221                 if(errno != ENOENT) {
222                         logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", path, strerror(errno));
223                         meshlink_errno = MESHLINK_ESTORAGE;
224                         return false;
225                 }
226         }
227
228         snprintf(path, sizeof(path), "%s" SLASH "%s", confbase, conf_subdir);
229
230         if(!deltree(path)) {
231                 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", path, strerror(errno));
232                 meshlink_errno = MESHLINK_ESTORAGE;
233                 return false;
234         }
235
236         return sync_path(confbase);
237 }
238
239 static bool copytree(const char *src_dir_name, const void *src_key, const char *dst_dir_name, const void *dst_key) {
240         assert(src_dir_name);
241         assert(dst_dir_name);
242
243         char src_filename[PATH_MAX];
244         char dst_filename[PATH_MAX];
245         struct dirent *ent;
246
247         DIR *src_dir = opendir(src_dir_name);
248
249         if(!src_dir) {
250                 logger(NULL, MESHLINK_ERROR, "Could not open directory file %s\n", src_dir_name);
251                 meshlink_errno = MESHLINK_ESTORAGE;
252                 return false;
253         }
254
255         // Delete if already exists and create a new destination directory
256         if(!deltree(dst_dir_name)) {
257                 logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", dst_dir_name, strerror(errno));
258                 meshlink_errno = MESHLINK_ESTORAGE;
259                 return false;
260         }
261
262         if(mkdir(dst_dir_name, 0700)) {
263                 logger(NULL, MESHLINK_ERROR, "Could not create directory %s\n", dst_filename);
264                 meshlink_errno = MESHLINK_ESTORAGE;
265                 return false;
266         }
267
268         while((ent = readdir(src_dir))) {
269                 if(ent->d_name[0] == '.') {
270                         continue;
271                 }
272
273                 snprintf(dst_filename, sizeof(dst_filename), "%s" SLASH "%s", dst_dir_name, ent->d_name);
274                 snprintf(src_filename, sizeof(src_filename), "%s" SLASH "%s", src_dir_name, ent->d_name);
275
276                 if(ent->d_type == DT_DIR) {
277                         if(!copytree(src_filename, src_key, dst_filename, dst_key)) {
278                                 logger(NULL, MESHLINK_ERROR, "Copying %s to %s failed\n", src_filename, dst_filename);
279                                 meshlink_errno = MESHLINK_ESTORAGE;
280                                 return false;
281                         }
282
283                         if(!sync_path(dst_filename)) {
284                                 return false;
285                         }
286                 } else if(ent->d_type == DT_REG) {
287                         struct stat st;
288                         config_t config;
289
290                         if(stat(src_filename, &st)) {
291                                 logger(NULL, MESHLINK_ERROR, "Could not stat file `%s': %s\n", src_filename, strerror(errno));
292                                 meshlink_errno = MESHLINK_ESTORAGE;
293                                 return false;
294                         }
295
296                         FILE *f = fopen(src_filename, "r");
297
298                         if(!f) {
299                                 logger(NULL, MESHLINK_ERROR, "Failed to open `%s': %s\n", src_filename, strerror(errno));
300                                 meshlink_errno = MESHLINK_ESTORAGE;
301                                 return false;
302                         }
303
304                         if(!config_read_file(NULL, f, &config, src_key)) {
305                                 logger(NULL, MESHLINK_ERROR, "Failed to read `%s': %s\n", src_filename, strerror(errno));
306                                 fclose(f);
307                                 meshlink_errno = MESHLINK_ESTORAGE;
308                                 return false;
309                         }
310
311                         if(fclose(f)) {
312                                 logger(NULL, MESHLINK_ERROR, "Failed to close `%s': %s\n", src_filename, strerror(errno));
313                                 config_free(&config);
314                                 meshlink_errno = MESHLINK_ESTORAGE;
315                                 return false;
316                         }
317
318                         f = fopen(dst_filename, "w");
319
320                         if(!f) {
321                                 logger(NULL, MESHLINK_ERROR, "Failed to open `%s': %s", dst_filename, strerror(errno));
322                                 config_free(&config);
323                                 meshlink_errno = MESHLINK_ESTORAGE;
324                                 return false;
325                         }
326
327                         if(!config_write_file(NULL, f, &config, dst_key)) {
328                                 logger(NULL, MESHLINK_ERROR, "Failed to write `%s': %s", dst_filename, strerror(errno));
329                                 config_free(&config);
330                                 fclose(f);
331                                 meshlink_errno = MESHLINK_ESTORAGE;
332                                 return false;
333                         }
334
335                         if(fclose(f)) {
336                                 logger(NULL, MESHLINK_ERROR, "Failed to close `%s': %s", dst_filename, strerror(errno));
337                                 config_free(&config);
338                                 meshlink_errno = MESHLINK_ESTORAGE;
339                                 return false;
340                         }
341
342                         config_free(&config);
343
344                         struct utimbuf times;
345                         times.modtime = st.st_mtime;
346                         times.actime = st.st_atime;
347
348                         if(utime(dst_filename, &times)) {
349                                 logger(NULL, MESHLINK_ERROR, "Failed to utime `%s': %s", dst_filename, strerror(errno));
350                                 meshlink_errno = MESHLINK_ESTORAGE;
351                                 return false;
352                         }
353                 }
354         }
355
356         closedir(src_dir);
357         return true;
358 }
359
360 bool config_copy(meshlink_handle_t *mesh, const char *src_dir_name, const void *src_key, const char *dst_dir_name, const void *dst_key) {
361         assert(src_dir_name);
362         assert(dst_dir_name);
363
364         char src_filename[PATH_MAX];
365         char dst_filename[PATH_MAX];
366
367         snprintf(dst_filename, sizeof(dst_filename), "%s" SLASH "%s", mesh->confbase, dst_dir_name);
368         snprintf(src_filename, sizeof(src_filename), "%s" SLASH "%s", mesh->confbase, src_dir_name);
369
370         return copytree(src_filename, src_key, dst_filename, dst_key);
371 }
372
373 /// Check the presence of the main configuration file.
374 bool main_config_exists(meshlink_handle_t *mesh, const char *conf_subdir) {
375         assert(conf_subdir);
376
377         if(!mesh->confbase) {
378                 return false;
379         }
380
381         char path[PATH_MAX];
382         make_main_path(mesh, conf_subdir, path, sizeof(path));
383         return access(path, F_OK) == 0;
384 }
385
386 bool config_rename(meshlink_handle_t *mesh, const char *old_conf_subdir, const char *new_conf_subdir) {
387         assert(old_conf_subdir);
388         assert(new_conf_subdir);
389
390         if(!mesh->confbase) {
391                 return false;
392         }
393
394         char old_path[PATH_MAX];
395         char new_path[PATH_MAX];
396
397         snprintf(old_path, sizeof(old_path), "%s" SLASH "%s", mesh->confbase, old_conf_subdir);
398         snprintf(new_path, sizeof(new_path), "%s" SLASH "%s", mesh->confbase, new_conf_subdir);
399
400         return rename(old_path, new_path) == 0 && sync_path(mesh->confbase);
401 }
402
403 bool config_sync(meshlink_handle_t *mesh, const char *conf_subdir) {
404         assert(conf_subdir);
405
406         if(!mesh->confbase) {
407                 return true;
408         }
409
410         char path[PATH_MAX];
411         snprintf(path, sizeof(path), "%s" SLASH "%s" SLASH "hosts", mesh->confbase, conf_subdir);
412
413         if(!sync_path(path)) {
414                 return false;
415         }
416
417         snprintf(path, sizeof(path), "%s" SLASH "%s", mesh->confbase, conf_subdir);
418
419         if(!sync_path(path)) {
420                 return false;
421         }
422
423         return true;
424 }
425
426 bool meshlink_confbase_exists(meshlink_handle_t *mesh) {
427         if(!mesh->confbase) {
428                 return false;
429         }
430
431         bool confbase_exists = false;
432         bool confbase_decryptable = false;
433
434         if(main_config_exists(mesh, "current")) {
435                 confbase_exists = true;
436
437                 if(mesh->config_key && main_config_decrypt(mesh, "current")) {
438                         confbase_decryptable = true;
439                 }
440         }
441
442         if(mesh->config_key && !confbase_decryptable && main_config_exists(mesh, "new")) {
443                 confbase_exists = true;
444
445                 if(main_config_decrypt(mesh, "new")) {
446                         if(!config_destroy(mesh->confbase, "current")) {
447                                 return false;
448                         }
449
450                         if(!config_rename(mesh, "new", "current")) {
451                                 return false;
452                         }
453
454                         confbase_decryptable = true;
455                 }
456         }
457
458         if(mesh->config_key && !confbase_decryptable && main_config_exists(mesh, "old")) {
459                 confbase_exists = true;
460
461                 if(main_config_decrypt(mesh, "old")) {
462                         if(!config_destroy(mesh->confbase, "current")) {
463                                 return false;
464                         }
465
466                         if(!config_rename(mesh, "old", "current")) {
467                                 return false;
468                         }
469
470                         confbase_decryptable = true;
471                 }
472         }
473
474         // Cleanup if current is existing with old and new
475         if(confbase_exists && confbase_decryptable) {
476                 if(!config_destroy(mesh->confbase, "old") || !config_destroy(mesh->confbase, "new")) {
477                         return false;
478                 }
479         }
480
481         return confbase_exists;
482 }
483
484 /// Lock the main configuration file. Creates confbase if necessary.
485 bool main_config_lock(meshlink_handle_t *mesh) {
486         if(!mesh->confbase) {
487                 return true;
488         }
489
490         if(mkdir(mesh->confbase, 0700) && errno != EEXIST) {
491                 logger(NULL, MESHLINK_ERROR, "Cannot create configuration directory %s: %s", mesh->confbase, strerror(errno));
492                 meshlink_close(mesh);
493                 meshlink_errno = MESHLINK_ESTORAGE;
494                 return NULL;
495         }
496
497         char path[PATH_MAX];
498         snprintf(path, sizeof(path), "%s" SLASH "meshlink.lock", mesh->confbase);
499
500         mesh->lockfile = fopen(path, "w+");
501
502         if(!mesh->lockfile) {
503                 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", path, strerror(errno));
504                 meshlink_errno = MESHLINK_ESTORAGE;
505                 return false;
506         }
507
508 #ifdef FD_CLOEXEC
509         fcntl(fileno(mesh->lockfile), F_SETFD, FD_CLOEXEC);
510 #endif
511
512 #ifdef HAVE_MINGW
513         // TODO: use _locking()?
514 #else
515
516         if(flock(fileno(mesh->lockfile), LOCK_EX | LOCK_NB) != 0) {
517                 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", path, strerror(errno));
518                 fclose(mesh->lockfile);
519                 mesh->lockfile = NULL;
520                 meshlink_errno = MESHLINK_EBUSY;
521                 return false;
522         }
523
524 #endif
525
526         return true;
527 }
528
529 /// Unlock the main configuration file.
530 void main_config_unlock(meshlink_handle_t *mesh) {
531         if(mesh->lockfile) {
532                 fclose(mesh->lockfile);
533                 mesh->lockfile = NULL;
534         }
535 }
536
537 /// Read a configuration file from a FILE handle.
538 bool config_read_file(meshlink_handle_t *mesh, FILE *f, config_t *config, const void *key) {
539         assert(f);
540
541         long len;
542
543         if(fseek(f, 0, SEEK_END) || !(len = ftell(f)) || fseek(f, 0, SEEK_SET)) {
544                 logger(mesh, MESHLINK_ERROR, "Cannot get config file size: %s\n", strerror(errno));
545                 meshlink_errno = MESHLINK_ESTORAGE;
546                 return false;
547         }
548
549         uint8_t *buf = xmalloc(len);
550
551         if(fread(buf, len, 1, f) != 1) {
552                 logger(mesh, MESHLINK_ERROR, "Cannot read config file: %s\n", strerror(errno));
553                 meshlink_errno = MESHLINK_ESTORAGE;
554                 return false;
555         }
556
557         if(key) {
558                 uint8_t *decrypted = xmalloc(len);
559                 size_t decrypted_len = len;
560                 chacha_poly1305_ctx_t *ctx = chacha_poly1305_init();
561                 chacha_poly1305_set_key(ctx, key);
562
563                 if(len > 12 && chacha_poly1305_decrypt_iv96(ctx, buf, buf + 12, len - 12, decrypted, &decrypted_len)) {
564                         chacha_poly1305_exit(ctx);
565                         free(buf);
566                         config->buf = decrypted;
567                         config->len = decrypted_len;
568                         return true;
569                 } else {
570                         logger(mesh, MESHLINK_ERROR, "Cannot decrypt config file\n");
571                         meshlink_errno = MESHLINK_ESTORAGE;
572                         chacha_poly1305_exit(ctx);
573                         free(decrypted);
574                         free(buf);
575                         return false;
576                 }
577         }
578
579         config->buf = buf;
580         config->len = len;
581
582         return true;
583 }
584
585 /// Write a configuration file to a FILE handle.
586 bool config_write_file(meshlink_handle_t *mesh, FILE *f, const config_t *config, const void *key) {
587         assert(f);
588
589         if(key) {
590                 uint8_t buf[config->len + 16];
591                 size_t len = sizeof(buf);
592                 uint8_t seqbuf[12];
593                 randomize(&seqbuf, sizeof(seqbuf));
594                 chacha_poly1305_ctx_t *ctx = chacha_poly1305_init();
595                 chacha_poly1305_set_key(ctx, key);
596                 bool success = false;
597
598                 if(chacha_poly1305_encrypt_iv96(ctx, seqbuf, config->buf, config->len, buf, &len)) {
599                         success = fwrite(seqbuf, sizeof(seqbuf), 1, f) == 1 && fwrite(buf, len, 1, f) == 1;
600
601                         if(!success) {
602                                 logger(mesh, MESHLINK_ERROR, "Cannot write config file: %s", strerror(errno));
603                         }
604
605                         meshlink_errno = MESHLINK_ESTORAGE;
606                 } else {
607                         logger(mesh, MESHLINK_ERROR, "Cannot encrypt config file\n");
608                         meshlink_errno = MESHLINK_ESTORAGE;
609                 }
610
611                 chacha_poly1305_exit(ctx);
612                 return success;
613         }
614
615         if(fwrite(config->buf, config->len, 1, f) != 1) {
616                 logger(mesh, MESHLINK_ERROR, "Cannot write config file: %s", strerror(errno));
617                 meshlink_errno = MESHLINK_ESTORAGE;
618                 return false;
619         }
620
621         if(fflush(f)) {
622                 logger(mesh, MESHLINK_ERROR, "Failed to flush file: %s", strerror(errno));
623                 meshlink_errno = MESHLINK_ESTORAGE;
624                 return false;
625         }
626
627         if(fsync(fileno(f))) {
628                 logger(mesh, MESHLINK_ERROR, "Failed to sync file: %s\n", strerror(errno));
629                 meshlink_errno = MESHLINK_ESTORAGE;
630                 return false;
631         }
632
633         return true;
634 }
635
636 /// Free resources of a loaded configuration file.
637 void config_free(config_t *config) {
638         assert(!config->len || config->buf);
639
640         free((uint8_t *)config->buf);
641         config->buf = NULL;
642         config->len = 0;
643 }
644
645 /// Check the presence of a host configuration file.
646 bool config_exists(meshlink_handle_t *mesh, const char *conf_subdir, const char *name) {
647         assert(conf_subdir);
648
649         if(!mesh->confbase) {
650                 return false;
651         }
652
653         char path[PATH_MAX];
654         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
655
656         return access(path, F_OK) == 0;
657 }
658
659 /// Read a host configuration file.
660 bool config_read(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, config_t *config, void *key) {
661         assert(conf_subdir);
662
663         if(!mesh->confbase) {
664                 return false;
665         }
666
667         char path[PATH_MAX];
668         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
669
670         FILE *f = fopen(path, "r");
671
672         if(!f) {
673                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
674                 return false;
675         }
676
677         if(!config_read_file(mesh, f, config, key)) {
678                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", path, strerror(errno));
679                 fclose(f);
680                 return false;
681         }
682
683         fclose(f);
684
685         return true;
686 }
687
688 bool config_scan_all(meshlink_handle_t *mesh, const char *conf_subdir, const char *conf_type, config_scan_action_t action, void *arg) {
689         assert(conf_subdir);
690         assert(conf_type);
691
692         if(!mesh->confbase) {
693                 return true;
694         }
695
696         DIR *dir;
697         struct dirent *ent;
698         char dname[PATH_MAX];
699         snprintf(dname, sizeof(dname), "%s" SLASH "%s" SLASH "%s", mesh->confbase, conf_subdir, conf_type);
700
701         dir = opendir(dname);
702
703         if(!dir) {
704                 logger(mesh, MESHLINK_ERROR, "Could not open %s: %s", dname, strerror(errno));
705                 meshlink_errno = MESHLINK_ESTORAGE;
706                 return false;
707         }
708
709         while((ent = readdir(dir))) {
710                 if(ent->d_name[0] == '.') {
711                         continue;
712                 }
713
714                 if(!action(mesh, ent->d_name, arg)) {
715                         closedir(dir);
716                         return false;
717                 }
718         }
719
720         closedir(dir);
721         return true;
722 }
723
724 /// Write a host configuration file.
725 bool config_write(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, const config_t *config, void *key) {
726         assert(conf_subdir);
727         assert(name);
728         assert(config);
729
730         if(!mesh->confbase) {
731                 return true;
732         }
733
734         char path[PATH_MAX];
735         char tmp_path[PATH_MAX + 4];
736         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
737         snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path);
738
739         FILE *f = fopen(tmp_path, "w");
740
741         if(!f) {
742                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", tmp_path, strerror(errno));
743                 meshlink_errno = MESHLINK_ESTORAGE;
744                 return false;
745         }
746
747         if(!config_write_file(mesh, f, config, key)) {
748                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmp_path, strerror(errno));
749                 fclose(f);
750                 return false;
751         }
752
753         if(fclose(f)) {
754                 logger(mesh, MESHLINK_ERROR, "Failed to close `%s': %s", tmp_path, strerror(errno));
755                 meshlink_errno = MESHLINK_ESTORAGE;
756                 return false;
757         }
758
759         if(rename(tmp_path, path)) {
760                 logger(mesh, MESHLINK_ERROR, "Failed to rename `%s' to `%s': %s", tmp_path, path, strerror(errno));
761                 meshlink_errno = MESHLINK_ESTORAGE;
762                 return false;
763         }
764
765         return true;
766 }
767
768 /// Delete a host configuration file.
769 bool config_delete(meshlink_handle_t *mesh, const char *conf_subdir, const char *name) {
770         assert(conf_subdir);
771         assert(name);
772
773         if(!mesh->confbase) {
774                 return true;
775         }
776
777         char path[PATH_MAX];
778         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
779
780         if(unlink(path) && errno != ENOENT) {
781                 logger(mesh, MESHLINK_ERROR, "Failed to unlink `%s': %s", path, strerror(errno));
782                 meshlink_errno = MESHLINK_ESTORAGE;
783                 return false;
784         }
785
786         return true;
787 }
788
789 /// Read the main configuration file.
790 bool main_config_read(meshlink_handle_t *mesh, const char *conf_subdir, config_t *config, void *key) {
791         assert(conf_subdir);
792         assert(config);
793
794         if(!mesh->confbase) {
795                 return false;
796         }
797
798         char path[PATH_MAX];
799         make_main_path(mesh, conf_subdir, path, sizeof(path));
800
801         FILE *f = fopen(path, "r");
802
803         if(!f) {
804                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
805                 return false;
806         }
807
808         if(!config_read_file(mesh, f, config, key)) {
809                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", path, strerror(errno));
810                 fclose(f);
811                 return false;
812         }
813
814         fclose(f);
815
816         return true;
817 }
818
819 /// Write the main configuration file.
820 bool main_config_write(meshlink_handle_t *mesh, const char *conf_subdir, const config_t *config, void *key) {
821         assert(conf_subdir);
822         assert(config);
823
824         if(!mesh->confbase) {
825                 return true;
826         }
827
828         char path[PATH_MAX];
829         char tmp_path[PATH_MAX + 4];
830         make_main_path(mesh, conf_subdir, path, sizeof(path));
831         snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path);
832
833         FILE *f = fopen(tmp_path, "w");
834
835         if(!f) {
836                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", tmp_path, strerror(errno));
837                 meshlink_errno = MESHLINK_ESTORAGE;
838                 return false;
839         }
840
841         if(!config_write_file(mesh, f, config, key)) {
842                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmp_path, strerror(errno));
843                 fclose(f);
844                 return false;
845         }
846
847         if(rename(tmp_path, path)) {
848                 logger(mesh, MESHLINK_ERROR, "Failed to rename `%s' to `%s': %s", tmp_path, path, strerror(errno));
849                 meshlink_errno = MESHLINK_ESTORAGE;
850                 fclose(f);
851                 return false;
852         }
853
854         if(fclose(f)) {
855                 logger(mesh, MESHLINK_ERROR, "Failed to close `%s': %s", tmp_path, strerror(errno));
856                 meshlink_errno = MESHLINK_ESTORAGE;
857                 return false;
858         }
859
860         return true;
861 }
862
863 /// Read an invitation file from the confbase sub-directory, and immediately delete it.
864 bool invitation_read(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, config_t *config, void *key) {
865         assert(conf_subdir);
866         assert(name);
867         assert(config);
868
869         if(!mesh->confbase) {
870                 return false;
871         }
872
873         char path[PATH_MAX];
874         char used_path[PATH_MAX];
875         make_invitation_path(mesh, conf_subdir, name, path, sizeof(path));
876         make_used_invitation_path(mesh, conf_subdir, name, used_path, sizeof(used_path));
877
878         // Atomically rename the invitation file
879         if(rename(path, used_path)) {
880                 if(errno == ENOENT) {
881                         logger(mesh, MESHLINK_ERROR, "Peer tried to use non-existing invitation %s\n", name);
882                 } else {
883                         logger(mesh, MESHLINK_ERROR, "Error trying to rename invitation %s\n", name);
884                 }
885
886                 return false;
887         }
888
889         FILE *f = fopen(used_path, "r");
890
891         if(!f) {
892                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
893                 return false;
894         }
895
896         // Check the timestamp
897         struct stat st;
898
899         if(fstat(fileno(f), &st)) {
900                 logger(mesh, MESHLINK_ERROR, "Could not stat invitation file %s\n", name);
901                 fclose(f);
902                 unlink(used_path);
903                 return false;
904         }
905
906         if(time(NULL) >= st.st_mtime + mesh->invitation_timeout) {
907                 logger(mesh, MESHLINK_ERROR, "Peer tried to use an outdated invitation file %s\n", name);
908                 fclose(f);
909                 unlink(used_path);
910                 return false;
911         }
912
913         if(!config_read_file(mesh, f, config, key)) {
914                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", path, strerror(errno));
915                 fclose(f);
916                 unlink(used_path);
917                 return false;
918         }
919
920         fclose(f);
921
922         if(unlink(used_path)) {
923                 logger(mesh, MESHLINK_ERROR, "Failed to unlink `%s': %s", path, strerror(errno));
924                 return false;
925         }
926
927         snprintf(path, sizeof(path), "%s" SLASH "%s" SLASH "invitations", mesh->confbase, conf_subdir);
928
929         if(!sync_path(path)) {
930                 logger(mesh, MESHLINK_ERROR, "Failed to sync `%s': %s", path, strerror(errno));
931                 meshlink_errno = MESHLINK_ESTORAGE;
932                 return false;
933         }
934
935         return true;
936 }
937
938 /// Write an invitation file.
939 bool invitation_write(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, const config_t *config, void *key) {
940         assert(conf_subdir);
941         assert(name);
942         assert(config);
943
944         if(!mesh->confbase) {
945                 return false;
946         }
947
948         char path[PATH_MAX];
949         make_invitation_path(mesh, conf_subdir, name, path, sizeof(path));
950
951         FILE *f = fopen(path, "w");
952
953         if(!f) {
954                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
955                 meshlink_errno = MESHLINK_ESTORAGE;
956                 return false;
957         }
958
959         if(!config_write_file(mesh, f, config, key)) {
960                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", path, strerror(errno));
961                 fclose(f);
962                 return false;
963         }
964
965         if(fclose(f)) {
966                 logger(mesh, MESHLINK_ERROR, "Failed to close `%s': %s", path, strerror(errno));
967                 meshlink_errno = MESHLINK_ESTORAGE;
968                 return false;
969         }
970
971         snprintf(path, sizeof(path), "%s" SLASH "%s" SLASH "invitations", mesh->confbase, conf_subdir);
972
973         if(!sync_path(path)) {
974                 logger(mesh, MESHLINK_ERROR, "Failed to sync `%s': %s", path, strerror(errno));
975                 meshlink_errno = MESHLINK_ESTORAGE;
976                 return false;
977         }
978
979         return true;
980 }
981
982 /// Purge old invitation files
983 size_t invitation_purge_old(meshlink_handle_t *mesh, time_t deadline) {
984         if(!mesh->confbase) {
985                 return true;
986         }
987
988         char path[PATH_MAX];
989         make_invitation_path(mesh, "current", "", path, sizeof(path));
990
991         DIR *dir = opendir(path);
992
993         if(!dir) {
994                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", path, strerror(errno));
995                 meshlink_errno = MESHLINK_ESTORAGE;
996                 return 0;
997         }
998
999         errno = 0;
1000         size_t count = 0;
1001         struct dirent *ent;
1002
1003         while((ent = readdir(dir))) {
1004                 if(strlen(ent->d_name) != 24) {
1005                         continue;
1006                 }
1007
1008                 char invname[PATH_MAX];
1009                 struct stat st;
1010
1011                 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", path, ent->d_name) >= PATH_MAX) {
1012                         logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", path, ent->d_name);
1013                         continue;
1014                 }
1015
1016                 if(!stat(invname, &st)) {
1017                         if(mesh->invitation_key && deadline < st.st_mtime) {
1018                                 count++;
1019                         } else {
1020                                 unlink(invname);
1021                         }
1022                 } else {
1023                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1024                         errno = 0;
1025                 }
1026         }
1027
1028         if(errno) {
1029                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", path, strerror(errno));
1030                 closedir(dir);
1031                 meshlink_errno = MESHLINK_ESTORAGE;
1032                 return 0;
1033         }
1034
1035         closedir(dir);
1036
1037         return count;
1038 }