]> git.meshlink.io Git - meshlink/blob - src/conf.c
Fix deleting configuration directories with hidden files.
[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) {
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) {
488         if(!mesh->confbase) {
489                 return true;
490         }
491
492         if(mkdir(mesh->confbase, 0700) && errno != EEXIST) {
493                 logger(NULL, MESHLINK_ERROR, "Cannot create configuration directory %s: %s", mesh->confbase, strerror(errno));
494                 meshlink_close(mesh);
495                 meshlink_errno = MESHLINK_ESTORAGE;
496                 return NULL;
497         }
498
499         char path[PATH_MAX];
500         snprintf(path, sizeof(path), "%s" SLASH "meshlink.lock", mesh->confbase);
501
502         mesh->lockfile = fopen(path, "w+");
503
504         if(!mesh->lockfile) {
505                 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", path, strerror(errno));
506                 meshlink_errno = MESHLINK_ESTORAGE;
507                 return false;
508         }
509
510 #ifdef FD_CLOEXEC
511         fcntl(fileno(mesh->lockfile), F_SETFD, FD_CLOEXEC);
512 #endif
513
514 #ifdef HAVE_MINGW
515         // TODO: use _locking()?
516 #else
517
518         if(flock(fileno(mesh->lockfile), LOCK_EX | LOCK_NB) != 0) {
519                 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", path, strerror(errno));
520                 fclose(mesh->lockfile);
521                 mesh->lockfile = NULL;
522                 meshlink_errno = MESHLINK_EBUSY;
523                 return false;
524         }
525
526 #endif
527
528         return true;
529 }
530
531 /// Unlock the main configuration file.
532 void main_config_unlock(meshlink_handle_t *mesh) {
533         if(mesh->lockfile) {
534                 fclose(mesh->lockfile);
535                 mesh->lockfile = NULL;
536         }
537 }
538
539 /// Read a configuration file from a FILE handle.
540 bool config_read_file(meshlink_handle_t *mesh, FILE *f, config_t *config, const void *key) {
541         assert(f);
542
543         long len;
544
545         if(fseek(f, 0, SEEK_END) || !(len = ftell(f)) || fseek(f, 0, SEEK_SET)) {
546                 logger(mesh, MESHLINK_ERROR, "Cannot get config file size: %s\n", strerror(errno));
547                 meshlink_errno = MESHLINK_ESTORAGE;
548                 return false;
549         }
550
551         uint8_t *buf = xmalloc(len);
552
553         if(fread(buf, len, 1, f) != 1) {
554                 logger(mesh, MESHLINK_ERROR, "Cannot read config file: %s\n", strerror(errno));
555                 meshlink_errno = MESHLINK_ESTORAGE;
556                 return false;
557         }
558
559         if(key) {
560                 uint8_t *decrypted = xmalloc(len);
561                 size_t decrypted_len = len;
562                 chacha_poly1305_ctx_t *ctx = chacha_poly1305_init();
563                 chacha_poly1305_set_key(ctx, key);
564
565                 if(len > 12 && chacha_poly1305_decrypt_iv96(ctx, buf, buf + 12, len - 12, decrypted, &decrypted_len)) {
566                         chacha_poly1305_exit(ctx);
567                         free(buf);
568                         config->buf = decrypted;
569                         config->len = decrypted_len;
570                         return true;
571                 } else {
572                         logger(mesh, MESHLINK_ERROR, "Cannot decrypt config file\n");
573                         meshlink_errno = MESHLINK_ESTORAGE;
574                         chacha_poly1305_exit(ctx);
575                         free(decrypted);
576                         free(buf);
577                         return false;
578                 }
579         }
580
581         config->buf = buf;
582         config->len = len;
583
584         return true;
585 }
586
587 /// Write a configuration file to a FILE handle.
588 bool config_write_file(meshlink_handle_t *mesh, FILE *f, const config_t *config, const void *key) {
589         assert(f);
590
591         if(key) {
592                 uint8_t buf[config->len + 16];
593                 size_t len = sizeof(buf);
594                 uint8_t seqbuf[12];
595                 randomize(&seqbuf, sizeof(seqbuf));
596                 chacha_poly1305_ctx_t *ctx = chacha_poly1305_init();
597                 chacha_poly1305_set_key(ctx, key);
598                 bool success = false;
599
600                 if(chacha_poly1305_encrypt_iv96(ctx, seqbuf, config->buf, config->len, buf, &len)) {
601                         success = fwrite(seqbuf, sizeof(seqbuf), 1, f) == 1 && fwrite(buf, len, 1, f) == 1;
602
603                         if(!success) {
604                                 logger(mesh, MESHLINK_ERROR, "Cannot write config file: %s", strerror(errno));
605                         }
606
607                         meshlink_errno = MESHLINK_ESTORAGE;
608                 } else {
609                         logger(mesh, MESHLINK_ERROR, "Cannot encrypt config file\n");
610                         meshlink_errno = MESHLINK_ESTORAGE;
611                 }
612
613                 chacha_poly1305_exit(ctx);
614                 return success;
615         }
616
617         if(fwrite(config->buf, config->len, 1, f) != 1) {
618                 logger(mesh, MESHLINK_ERROR, "Cannot write config file: %s", strerror(errno));
619                 meshlink_errno = MESHLINK_ESTORAGE;
620                 return false;
621         }
622
623         if(fflush(f)) {
624                 logger(mesh, MESHLINK_ERROR, "Failed to flush file: %s", strerror(errno));
625                 meshlink_errno = MESHLINK_ESTORAGE;
626                 return false;
627         }
628
629         if(fsync(fileno(f))) {
630                 logger(mesh, MESHLINK_ERROR, "Failed to sync file: %s\n", strerror(errno));
631                 meshlink_errno = MESHLINK_ESTORAGE;
632                 return false;
633         }
634
635         return true;
636 }
637
638 /// Free resources of a loaded configuration file.
639 void config_free(config_t *config) {
640         assert(!config->len || config->buf);
641
642         free((uint8_t *)config->buf);
643         config->buf = NULL;
644         config->len = 0;
645 }
646
647 /// Check the presence of a host configuration file.
648 bool config_exists(meshlink_handle_t *mesh, const char *conf_subdir, const char *name) {
649         assert(conf_subdir);
650
651         if(!mesh->confbase) {
652                 return false;
653         }
654
655         char path[PATH_MAX];
656         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
657
658         return access(path, F_OK) == 0;
659 }
660
661 /// Read a host configuration file.
662 bool config_read(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, config_t *config, void *key) {
663         assert(conf_subdir);
664
665         if(!mesh->confbase) {
666                 return false;
667         }
668
669         char path[PATH_MAX];
670         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
671
672         FILE *f = fopen(path, "r");
673
674         if(!f) {
675                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
676                 return false;
677         }
678
679         if(!config_read_file(mesh, f, config, key)) {
680                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", path, strerror(errno));
681                 fclose(f);
682                 return false;
683         }
684
685         fclose(f);
686
687         return true;
688 }
689
690 bool config_scan_all(meshlink_handle_t *mesh, const char *conf_subdir, const char *conf_type, config_scan_action_t action, void *arg) {
691         assert(conf_subdir);
692         assert(conf_type);
693
694         if(!mesh->confbase) {
695                 return true;
696         }
697
698         DIR *dir;
699         struct dirent *ent;
700         char dname[PATH_MAX];
701         snprintf(dname, sizeof(dname), "%s" SLASH "%s" SLASH "%s", mesh->confbase, conf_subdir, conf_type);
702
703         dir = opendir(dname);
704
705         if(!dir) {
706                 logger(mesh, MESHLINK_ERROR, "Could not open %s: %s", dname, strerror(errno));
707                 meshlink_errno = MESHLINK_ESTORAGE;
708                 return false;
709         }
710
711         while((ent = readdir(dir))) {
712                 if(ent->d_name[0] == '.') {
713                         continue;
714                 }
715
716                 if(!action(mesh, ent->d_name, arg)) {
717                         closedir(dir);
718                         return false;
719                 }
720         }
721
722         closedir(dir);
723         return true;
724 }
725
726 /// Write a host configuration file.
727 bool config_write(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, const config_t *config, void *key) {
728         assert(conf_subdir);
729         assert(name);
730         assert(config);
731
732         if(!mesh->confbase) {
733                 return true;
734         }
735
736         char path[PATH_MAX];
737         char tmp_path[PATH_MAX + 4];
738         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
739         snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path);
740
741         FILE *f = fopen(tmp_path, "w");
742
743         if(!f) {
744                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", tmp_path, strerror(errno));
745                 meshlink_errno = MESHLINK_ESTORAGE;
746                 return false;
747         }
748
749         if(!config_write_file(mesh, f, config, key)) {
750                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmp_path, strerror(errno));
751                 fclose(f);
752                 return false;
753         }
754
755         if(fclose(f)) {
756                 logger(mesh, MESHLINK_ERROR, "Failed to close `%s': %s", tmp_path, strerror(errno));
757                 meshlink_errno = MESHLINK_ESTORAGE;
758                 return false;
759         }
760
761         if(rename(tmp_path, path)) {
762                 logger(mesh, MESHLINK_ERROR, "Failed to rename `%s' to `%s': %s", tmp_path, path, strerror(errno));
763                 meshlink_errno = MESHLINK_ESTORAGE;
764                 return false;
765         }
766
767         return true;
768 }
769
770 /// Delete a host configuration file.
771 bool config_delete(meshlink_handle_t *mesh, const char *conf_subdir, const char *name) {
772         assert(conf_subdir);
773         assert(name);
774
775         if(!mesh->confbase) {
776                 return true;
777         }
778
779         char path[PATH_MAX];
780         make_host_path(mesh, conf_subdir, name, path, sizeof(path));
781
782         if(unlink(path) && errno != ENOENT) {
783                 logger(mesh, MESHLINK_ERROR, "Failed to unlink `%s': %s", path, strerror(errno));
784                 meshlink_errno = MESHLINK_ESTORAGE;
785                 return false;
786         }
787
788         return true;
789 }
790
791 /// Read the main configuration file.
792 bool main_config_read(meshlink_handle_t *mesh, const char *conf_subdir, config_t *config, void *key) {
793         assert(conf_subdir);
794         assert(config);
795
796         if(!mesh->confbase) {
797                 return false;
798         }
799
800         char path[PATH_MAX];
801         make_main_path(mesh, conf_subdir, path, sizeof(path));
802
803         FILE *f = fopen(path, "r");
804
805         if(!f) {
806                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
807                 return false;
808         }
809
810         if(!config_read_file(mesh, f, config, key)) {
811                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", path, strerror(errno));
812                 fclose(f);
813                 return false;
814         }
815
816         fclose(f);
817
818         return true;
819 }
820
821 /// Write the main configuration file.
822 bool main_config_write(meshlink_handle_t *mesh, const char *conf_subdir, const config_t *config, void *key) {
823         assert(conf_subdir);
824         assert(config);
825
826         if(!mesh->confbase) {
827                 return true;
828         }
829
830         char path[PATH_MAX];
831         char tmp_path[PATH_MAX + 4];
832         make_main_path(mesh, conf_subdir, path, sizeof(path));
833         snprintf(tmp_path, sizeof(tmp_path), "%s.tmp", path);
834
835         FILE *f = fopen(tmp_path, "w");
836
837         if(!f) {
838                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", tmp_path, strerror(errno));
839                 meshlink_errno = MESHLINK_ESTORAGE;
840                 return false;
841         }
842
843         if(!config_write_file(mesh, f, config, key)) {
844                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", tmp_path, strerror(errno));
845                 fclose(f);
846                 return false;
847         }
848
849         if(rename(tmp_path, path)) {
850                 logger(mesh, MESHLINK_ERROR, "Failed to rename `%s' to `%s': %s", tmp_path, path, strerror(errno));
851                 meshlink_errno = MESHLINK_ESTORAGE;
852                 fclose(f);
853                 return false;
854         }
855
856         if(fclose(f)) {
857                 logger(mesh, MESHLINK_ERROR, "Failed to close `%s': %s", tmp_path, strerror(errno));
858                 meshlink_errno = MESHLINK_ESTORAGE;
859                 return false;
860         }
861
862         return true;
863 }
864
865 /// Read an invitation file from the confbase sub-directory, and immediately delete it.
866 bool invitation_read(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, config_t *config, void *key) {
867         assert(conf_subdir);
868         assert(name);
869         assert(config);
870
871         if(!mesh->confbase) {
872                 return false;
873         }
874
875         char path[PATH_MAX];
876         char used_path[PATH_MAX];
877         make_invitation_path(mesh, conf_subdir, name, path, sizeof(path));
878         make_used_invitation_path(mesh, conf_subdir, name, used_path, sizeof(used_path));
879
880         // Atomically rename the invitation file
881         if(rename(path, used_path)) {
882                 if(errno == ENOENT) {
883                         logger(mesh, MESHLINK_ERROR, "Peer tried to use non-existing invitation %s\n", name);
884                 } else {
885                         logger(mesh, MESHLINK_ERROR, "Error trying to rename invitation %s\n", name);
886                 }
887
888                 return false;
889         }
890
891         FILE *f = fopen(used_path, "r");
892
893         if(!f) {
894                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
895                 return false;
896         }
897
898         // Check the timestamp
899         struct stat st;
900
901         if(fstat(fileno(f), &st)) {
902                 logger(mesh, MESHLINK_ERROR, "Could not stat invitation file %s\n", name);
903                 fclose(f);
904                 unlink(used_path);
905                 return false;
906         }
907
908         if(time(NULL) >= st.st_mtime + mesh->invitation_timeout) {
909                 logger(mesh, MESHLINK_ERROR, "Peer tried to use an outdated invitation file %s\n", name);
910                 fclose(f);
911                 unlink(used_path);
912                 return false;
913         }
914
915         if(!config_read_file(mesh, f, config, key)) {
916                 logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", path, strerror(errno));
917                 fclose(f);
918                 unlink(used_path);
919                 return false;
920         }
921
922         fclose(f);
923
924         if(unlink(used_path)) {
925                 logger(mesh, MESHLINK_ERROR, "Failed to unlink `%s': %s", path, strerror(errno));
926                 return false;
927         }
928
929         snprintf(path, sizeof(path), "%s" SLASH "%s" SLASH "invitations", mesh->confbase, conf_subdir);
930
931         if(!sync_path(path)) {
932                 logger(mesh, MESHLINK_ERROR, "Failed to sync `%s': %s", path, strerror(errno));
933                 meshlink_errno = MESHLINK_ESTORAGE;
934                 return false;
935         }
936
937         return true;
938 }
939
940 /// Write an invitation file.
941 bool invitation_write(meshlink_handle_t *mesh, const char *conf_subdir, const char *name, const config_t *config, void *key) {
942         assert(conf_subdir);
943         assert(name);
944         assert(config);
945
946         if(!mesh->confbase) {
947                 return false;
948         }
949
950         char path[PATH_MAX];
951         make_invitation_path(mesh, conf_subdir, name, path, sizeof(path));
952
953         FILE *f = fopen(path, "w");
954
955         if(!f) {
956                 logger(mesh, MESHLINK_ERROR, "Failed to open `%s': %s", path, strerror(errno));
957                 meshlink_errno = MESHLINK_ESTORAGE;
958                 return false;
959         }
960
961         if(!config_write_file(mesh, f, config, key)) {
962                 logger(mesh, MESHLINK_ERROR, "Failed to write `%s': %s", path, strerror(errno));
963                 fclose(f);
964                 return false;
965         }
966
967         if(fclose(f)) {
968                 logger(mesh, MESHLINK_ERROR, "Failed to close `%s': %s", path, strerror(errno));
969                 meshlink_errno = MESHLINK_ESTORAGE;
970                 return false;
971         }
972
973         snprintf(path, sizeof(path), "%s" SLASH "%s" SLASH "invitations", mesh->confbase, conf_subdir);
974
975         if(!sync_path(path)) {
976                 logger(mesh, MESHLINK_ERROR, "Failed to sync `%s': %s", path, strerror(errno));
977                 meshlink_errno = MESHLINK_ESTORAGE;
978                 return false;
979         }
980
981         return true;
982 }
983
984 /// Purge old invitation files
985 size_t invitation_purge_old(meshlink_handle_t *mesh, time_t deadline) {
986         if(!mesh->confbase) {
987                 return true;
988         }
989
990         char path[PATH_MAX];
991         make_invitation_path(mesh, "current", "", path, sizeof(path));
992
993         DIR *dir = opendir(path);
994
995         if(!dir) {
996                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", path, strerror(errno));
997                 meshlink_errno = MESHLINK_ESTORAGE;
998                 return 0;
999         }
1000
1001         errno = 0;
1002         size_t count = 0;
1003         struct dirent *ent;
1004
1005         while((ent = readdir(dir))) {
1006                 if(strlen(ent->d_name) != 24) {
1007                         continue;
1008                 }
1009
1010                 char invname[PATH_MAX];
1011                 struct stat st;
1012
1013                 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", path, ent->d_name) >= PATH_MAX) {
1014                         logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", path, ent->d_name);
1015                         continue;
1016                 }
1017
1018                 if(!stat(invname, &st)) {
1019                         if(mesh->invitation_key && deadline < st.st_mtime) {
1020                                 count++;
1021                         } else {
1022                                 unlink(invname);
1023                         }
1024                 } else {
1025                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1026                         errno = 0;
1027                 }
1028         }
1029
1030         if(errno) {
1031                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", path, strerror(errno));
1032                 closedir(dir);
1033                 meshlink_errno = MESHLINK_ESTORAGE;
1034                 return 0;
1035         }
1036
1037         closedir(dir);
1038
1039         return count;
1040 }
1041
1042 /// Purge invitations for the given node
1043 size_t invitation_purge_node(meshlink_handle_t *mesh, const char *node_name) {
1044         if(!mesh->confbase) {
1045                 return true;
1046         }
1047
1048         char path[PATH_MAX];
1049         make_invitation_path(mesh, "current", "", path, sizeof(path));
1050
1051         DIR *dir = opendir(path);
1052
1053         if(!dir) {
1054                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", path, strerror(errno));
1055                 meshlink_errno = MESHLINK_ESTORAGE;
1056                 return 0;
1057         }
1058
1059         errno = 0;
1060         size_t count = 0;
1061         struct dirent *ent;
1062
1063         while((ent = readdir(dir))) {
1064                 if(strlen(ent->d_name) != 24) {
1065                         continue;
1066                 }
1067
1068                 char invname[PATH_MAX];
1069
1070                 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", path, ent->d_name) >= PATH_MAX) {
1071                         logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", path, ent->d_name);
1072                         continue;
1073                 }
1074
1075                 FILE *f = fopen(invname, "r");
1076
1077                 if(!f) {
1078                         errno = 0;
1079                         continue;
1080                 }
1081
1082                 config_t config;
1083
1084                 if(!config_read_file(mesh, f, &config, mesh->config_key)) {
1085                         logger(mesh, MESHLINK_ERROR, "Failed to read `%s': %s", invname, strerror(errno));
1086                         config_free(&config);
1087                         fclose(f);
1088                         errno = 0;
1089                         continue;
1090                 }
1091
1092                 packmsg_input_t in = {config.buf, config.len};
1093                 packmsg_get_uint32(&in); // skip version
1094                 char *name = packmsg_get_str_dup(&in);
1095
1096                 if(name && !strcmp(name, node_name)) {
1097                         logger(mesh, MESHLINK_DEBUG, "Removing invitation for %s", node_name);
1098                         unlink(invname);
1099                 }
1100
1101                 free(name);
1102                 config_free(&config);
1103                 fclose(f);
1104         }
1105
1106         if(errno) {
1107                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", path, strerror(errno));
1108                 closedir(dir);
1109                 meshlink_errno = MESHLINK_ESTORAGE;
1110                 return 0;
1111         }
1112
1113         closedir(dir);
1114
1115         return count;
1116 }