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