]> git.meshlink.io Git - meshlink-tiny/blob - src/meshlink.c
Remove all support for channels.
[meshlink-tiny] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014-2021 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 <pthread.h>
22
23 #include "crypto.h"
24 #include "ecdsagen.h"
25 #include "logger.h"
26 #include "meshlink_internal.h"
27 #include "net.h"
28 #include "netutl.h"
29 #include "node.h"
30 #include "packmsg.h"
31 #include "prf.h"
32 #include "protocol.h"
33 #include "sockaddr.h"
34 #include "utils.h"
35 #include "xalloc.h"
36 #include "ed25519/sha512.h"
37 #include "devtools.h"
38
39 #ifndef MSG_NOSIGNAL
40 #define MSG_NOSIGNAL 0
41 #endif
42 __thread meshlink_errno_t meshlink_errno;
43 meshlink_log_cb_t global_log_cb;
44 meshlink_log_level_t global_log_level;
45
46 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
47
48 static int rstrip(char *value) {
49         int len = strlen(value);
50
51         while(len && strchr("\t\r\n ", value[len - 1])) {
52                 value[--len] = 0;
53         }
54
55         return len;
56 }
57
58 static bool is_valid_hostname(const char *hostname) {
59         if(!*hostname) {
60                 return false;
61         }
62
63         for(const char *p = hostname; *p; p++) {
64                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
65                         return false;
66                 }
67         }
68
69         return true;
70 }
71
72 static bool is_valid_port(const char *port) {
73         if(!*port) {
74                 return false;
75         }
76
77         if(isdigit(*port)) {
78                 char *end;
79                 unsigned long int result = strtoul(port, &end, 10);
80                 return result && result < 65536 && !*end;
81         }
82
83         for(const char *p = port; *p; p++) {
84                 if(!(isalnum(*p) || *p == '-')) {
85                         return false;
86                 }
87         }
88
89         return true;
90 }
91
92 static void set_timeout(int sock, int timeout) {
93 #ifdef _WIN32
94         DWORD tv = timeout;
95 #else
96         struct timeval tv;
97         tv.tv_sec = timeout / 1000;
98         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
99 #endif
100         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
101         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
102 }
103
104 struct socket_in_netns_params {
105         int domain;
106         int type;
107         int protocol;
108         int netns;
109         int fd;
110 };
111
112 #ifdef HAVE_SETNS
113 static void *socket_in_netns_thread(void *arg) {
114         struct socket_in_netns_params *params = arg;
115
116         if(setns(params->netns, CLONE_NEWNET) == -1) {
117                 meshlink_errno = MESHLINK_EINVAL;
118                 return NULL;
119         }
120
121         params->fd = socket(params->domain, params->type, params->protocol);
122
123         return NULL;
124 }
125 #endif // HAVE_SETNS
126
127 static int socket_in_netns(int domain, int type, int protocol, int netns) {
128         if(netns == -1) {
129                 return socket(domain, type, protocol);
130         }
131
132 #ifdef HAVE_SETNS
133         struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
134
135         pthread_t thr;
136
137         if(pthread_create(&thr, NULL, socket_in_netns_thread, &params) == 0) {
138                 if(pthread_join(thr, NULL) != 0) {
139                         abort();
140                 }
141         }
142
143         return params.fd;
144 #else
145         return -1;
146 #endif // HAVE_SETNS
147
148 }
149
150 static bool write_main_config_files(meshlink_handle_t *mesh) {
151         if(!mesh->confbase) {
152                 return true;
153         }
154
155         uint8_t buf[4096];
156
157         /* Write the main config file */
158         packmsg_output_t out = {buf, sizeof buf};
159
160         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
161         packmsg_add_str(&out, mesh->name);
162         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
163         packmsg_add_nil(&out); // Invitation keys are not supported
164         packmsg_add_uint16(&out, atoi(mesh->myport));
165
166         if(!packmsg_output_ok(&out)) {
167                 return false;
168         }
169
170         config_t config = {buf, packmsg_output_size(&out, buf)};
171
172         if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
173                 return false;
174         }
175
176         /* Write our own host config file */
177         if(!node_write_config(mesh, mesh->self, true)) {
178                 return false;
179         }
180
181         return true;
182 }
183
184 typedef struct {
185         meshlink_handle_t *mesh;
186         int sock;
187         char cookie[18 + 32];
188         char hash[18];
189         bool success;
190         sptps_t sptps;
191         char *data;
192         size_t thedatalen;
193         size_t blen;
194         char line[4096];
195         char buffer[4096];
196 } join_state_t;
197
198 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
199         meshlink_handle_t *mesh = state->mesh;
200         packmsg_input_t in = {buf, len};
201         uint32_t version = packmsg_get_uint32(&in);
202
203         if(version != MESHLINK_INVITATION_VERSION) {
204                 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
205                 return false;
206         }
207
208         char *name = packmsg_get_str_dup(&in);
209         packmsg_skip_element(&in); // submesh_name
210         dev_class_t devclass = packmsg_get_int32(&in);
211         uint32_t count = packmsg_get_array(&in);
212
213         if(!name || !check_id(name)) {
214                 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
215                 free(name);
216                 return false;
217         }
218
219         if(!count) {
220                 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
221                 free(name);
222                 return false;
223         }
224
225         free(mesh->name);
226         free(mesh->self->name);
227         mesh->name = name;
228         mesh->self->name = xstrdup(name);
229         mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
230
231         // Initialize configuration directory
232         if(!config_init(mesh, "current")) {
233                 return false;
234         }
235
236         if(!write_main_config_files(mesh)) {
237                 return false;
238         }
239
240         // Write host config files
241         for(uint32_t i = 0; i < count; i++) {
242                 const void *data;
243                 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
244
245                 if(!data_len) {
246                         logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
247                         return false;
248                 }
249
250                 packmsg_input_t in2 = {data, data_len};
251                 uint32_t version2 = packmsg_get_uint32(&in2);
252                 char *name2 = packmsg_get_str_dup(&in2);
253
254                 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
255                         free(name2);
256                         packmsg_input_invalidate(&in);
257                         break;
258                 }
259
260                 if(!check_id(name2)) {
261                         free(name2);
262                         break;
263                 }
264
265                 if(!strcmp(name2, mesh->name)) {
266                         logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
267                         free(name2);
268                         meshlink_errno = MESHLINK_EPEER;
269                         return false;
270                 }
271
272                 node_t *n = new_node();
273                 n->name = name2;
274
275                 config_t config = {data, data_len};
276
277                 if(!node_read_from_config(mesh, n, &config)) {
278                         free_node(n);
279                         logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
280                         meshlink_errno = MESHLINK_EPEER;
281                         return false;
282                 }
283
284                 if(i == 0) {
285                         /* The first host config file is of the inviter itself;
286                          * remember the address we are currently using for the invitation connection.
287                          */
288                         sockaddr_t sa;
289                         socklen_t salen = sizeof(sa);
290
291                         if(getpeername(state->sock, &sa.sa, &salen) == 0) {
292                                 node_add_recent_address(mesh, n, &sa);
293                         }
294                 }
295
296                 if(!node_write_config(mesh, n, true)) {
297                         free_node(n);
298                         return false;
299                 }
300
301                 node_add(mesh, n);
302         }
303
304         /* Ensure the configuration directory metadata is on disk */
305         if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
306                 return false;
307         }
308
309         if(!mesh->inviter_commits_first) {
310                 devtool_set_inviter_commits_first(false);
311         }
312
313         sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
314
315         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
316
317         return true;
318 }
319
320 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
321         (void)type;
322         join_state_t *state = handle;
323         const char *ptr = data;
324
325         while(len) {
326                 int result = send(state->sock, ptr, len, 0);
327
328                 if(result == -1 && errno == EINTR) {
329                         continue;
330                 } else if(result <= 0) {
331                         return false;
332                 }
333
334                 ptr += result;
335                 len -= result;
336         }
337
338         return true;
339 }
340
341 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
342         join_state_t *state = handle;
343         meshlink_handle_t *mesh = state->mesh;
344
345         if(mesh->inviter_commits_first) {
346                 switch(type) {
347                 case SPTPS_HANDSHAKE:
348                         return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
349
350                 case 1:
351                         break;
352
353                 case 0:
354                         if(!finalize_join(state, msg, len)) {
355                                 return false;
356                         }
357
358                         logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
359                         shutdown(state->sock, SHUT_RDWR);
360                         state->success = true;
361                         break;
362
363                 default:
364                         return false;
365                 }
366         } else {
367                 switch(type) {
368                 case SPTPS_HANDSHAKE:
369                         return sptps_send_record(&state->sptps, 0, state->cookie, 18);
370
371                 case 0:
372                         return finalize_join(state, msg, len);
373
374                 case 1:
375                         logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
376                         shutdown(state->sock, SHUT_RDWR);
377                         state->success = true;
378                         break;
379
380                 default:
381                         return false;
382                 }
383         }
384
385         return true;
386 }
387
388 static bool recvline(join_state_t *state) {
389         char *newline = NULL;
390
391         while(!(newline = memchr(state->buffer, '\n', state->blen))) {
392                 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
393
394                 if(result == -1 && errno == EINTR) {
395                         continue;
396                 } else if(result <= 0) {
397                         return false;
398                 }
399
400                 state->blen += result;
401         }
402
403         if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
404                 return false;
405         }
406
407         size_t len = newline - state->buffer;
408
409         memcpy(state->line, state->buffer, len);
410         state->line[len] = 0;
411         memmove(state->buffer, newline + 1, state->blen - len - 1);
412         state->blen -= len + 1;
413
414         return true;
415 }
416
417 static bool sendline(int fd, const char *format, ...) {
418         char buffer[4096];
419         char *p = buffer;
420         int blen = 0;
421         va_list ap;
422
423         va_start(ap, format);
424         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
425         va_end(ap);
426
427         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
428                 return false;
429         }
430
431         buffer[blen] = '\n';
432         blen++;
433
434         while(blen) {
435                 int result = send(fd, p, blen, MSG_NOSIGNAL);
436
437                 if(result == -1 && errno == EINTR) {
438                         continue;
439                 } else if(result <= 0) {
440                         return false;
441                 }
442
443                 p += result;
444                 blen -= result;
445         }
446
447         return true;
448 }
449
450 static const char *errstr[] = {
451         [MESHLINK_OK] = "No error",
452         [MESHLINK_EINVAL] = "Invalid argument",
453         [MESHLINK_ENOMEM] = "Out of memory",
454         [MESHLINK_ENOENT] = "No such node",
455         [MESHLINK_EEXIST] = "Node already exists",
456         [MESHLINK_EINTERNAL] = "Internal error",
457         [MESHLINK_ERESOLV] = "Could not resolve hostname",
458         [MESHLINK_ESTORAGE] = "Storage error",
459         [MESHLINK_ENETWORK] = "Network error",
460         [MESHLINK_EPEER] = "Error communicating with peer",
461         [MESHLINK_ENOTSUP] = "Operation not supported",
462         [MESHLINK_EBUSY] = "MeshLink instance already in use",
463         [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
464 };
465
466 const char *meshlink_strerror(meshlink_errno_t err) {
467         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
468                 return "Invalid error code";
469         }
470
471         return errstr[err];
472 }
473
474 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
475         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
476
477         mesh->private_key = ecdsa_generate();
478
479         if(!mesh->private_key) {
480                 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
481                 meshlink_errno = MESHLINK_EINTERNAL;
482                 return false;
483         }
484
485         logger(mesh, MESHLINK_DEBUG, "Done.\n");
486
487         return true;
488 }
489
490 static struct timespec idle(event_loop_t *loop, void *data) {
491         (void)loop;
492         (void)data;
493
494         return (struct timespec) {
495                 3600, 0
496         };
497 }
498
499 static bool meshlink_setup(meshlink_handle_t *mesh) {
500         if(!config_destroy(mesh->confbase, "new")) {
501                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
502                 meshlink_errno = MESHLINK_ESTORAGE;
503                 return false;
504         }
505
506         if(!config_destroy(mesh->confbase, "old")) {
507                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
508                 meshlink_errno = MESHLINK_ESTORAGE;
509                 return false;
510         }
511
512         if(!config_init(mesh, "current")) {
513                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
514                 meshlink_errno = MESHLINK_ESTORAGE;
515                 return false;
516         }
517
518         if(!ecdsa_keygen(mesh)) {
519                 meshlink_errno = MESHLINK_EINTERNAL;
520                 return false;
521         }
522
523         mesh->myport = xstrdup("0");
524
525         /* Create a node for ourself */
526
527         mesh->self = new_node();
528         mesh->self->name = xstrdup(mesh->name);
529         mesh->self->devclass = mesh->devclass;
530         mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
531         mesh->self->session_id = mesh->session_id;
532
533         if(!write_main_config_files(mesh)) {
534                 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
535                 meshlink_errno = MESHLINK_ESTORAGE;
536                 return false;
537         }
538
539         /* Ensure the configuration directory metadata is on disk */
540         if(!config_sync(mesh, "current")) {
541                 return false;
542         }
543
544         return true;
545 }
546
547 static bool meshlink_read_config(meshlink_handle_t *mesh) {
548         config_t config;
549
550         if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
551                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
552                 return false;
553         }
554
555         packmsg_input_t in = {config.buf, config.len};
556         const void *private_key;
557
558         uint32_t version = packmsg_get_uint32(&in);
559         char *name = packmsg_get_str_dup(&in);
560         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
561         packmsg_skip_element(&in); // Invitation key is not supported
562         uint16_t myport = packmsg_get_uint16(&in);
563
564         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
565                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
566                 free(name);
567                 config_free(&config);
568                 return false;
569         }
570
571         if(mesh->name && strcmp(mesh->name, name)) {
572                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
573                 meshlink_errno = MESHLINK_ESTORAGE;
574                 free(name);
575                 config_free(&config);
576                 return false;
577         }
578
579         free(mesh->name);
580         mesh->name = name;
581         xasprintf(&mesh->myport, "%u", myport);
582         mesh->private_key = ecdsa_set_private_key(private_key);
583         config_free(&config);
584
585         /* Create a node for ourself and read our host configuration file */
586
587         mesh->self = new_node();
588         mesh->self->name = xstrdup(name);
589         mesh->self->devclass = mesh->devclass;
590         mesh->self->session_id = mesh->session_id;
591
592         if(!node_read_public_key(mesh, mesh->self)) {
593                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
594                 meshlink_errno = MESHLINK_ESTORAGE;
595                 free_node(mesh->self);
596                 mesh->self = NULL;
597                 return false;
598         }
599
600         return true;
601 }
602
603 #ifdef HAVE_SETNS
604 static void *setup_network_in_netns_thread(void *arg) {
605         meshlink_handle_t *mesh = arg;
606
607         if(setns(mesh->netns, CLONE_NEWNET) != 0) {
608                 return NULL;
609         }
610
611         bool success = setup_network(mesh);
612         return success ? arg : NULL;
613 }
614 #endif // HAVE_SETNS
615
616 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
617         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
618
619         if(!confbase || !*confbase) {
620                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
621                 meshlink_errno = MESHLINK_EINVAL;
622                 return NULL;
623         }
624
625         if(!appname || !*appname) {
626                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
627                 meshlink_errno = MESHLINK_EINVAL;
628                 return NULL;
629         }
630
631         if(strchr(appname, ' ')) {
632                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
633                 meshlink_errno = MESHLINK_EINVAL;
634                 return NULL;
635         }
636
637         if(name && !check_id(name)) {
638                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
639                 meshlink_errno = MESHLINK_EINVAL;
640                 return NULL;
641         }
642
643         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
644                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
645                 meshlink_errno = MESHLINK_EINVAL;
646                 return NULL;
647         }
648
649         meshlink_open_params_t *params = xzalloc(sizeof * params);
650
651         params->confbase = xstrdup(confbase);
652         params->name = name ? xstrdup(name) : NULL;
653         params->appname = xstrdup(appname);
654         params->devclass = devclass;
655         params->netns = -1;
656
657         xasprintf(&params->lock_filename, "%s" SLASH "meshlink.lock", confbase);
658
659         return params;
660 }
661
662 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
663         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
664
665         if(!params) {
666                 meshlink_errno = MESHLINK_EINVAL;
667                 return false;
668         }
669
670         params->netns = netns;
671
672         return true;
673 }
674
675 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
676         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
677
678         if(!params) {
679                 meshlink_errno = MESHLINK_EINVAL;
680                 return false;
681         }
682
683         if((!key && keylen) || (key && !keylen)) {
684                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
685                 meshlink_errno = MESHLINK_EINVAL;
686                 return false;
687         }
688
689         params->key = key;
690         params->keylen = keylen;
691
692         return true;
693 }
694
695 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
696         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
697
698         if(!params) {
699                 meshlink_errno = MESHLINK_EINVAL;
700                 return false;
701         }
702
703         params->storage_policy = policy;
704
705         return true;
706 }
707
708 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
709         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
710
711         if(!params || !filename) {
712                 meshlink_errno = MESHLINK_EINVAL;
713                 return false;
714         }
715
716         free(params->lock_filename);
717         params->lock_filename = xstrdup(filename);
718
719         return true;
720 }
721
722 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
723         logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
724
725         if(!mesh || !new_key || !new_keylen) {
726                 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
727                 meshlink_errno = MESHLINK_EINVAL;
728                 return false;
729         }
730
731         if(pthread_mutex_lock(&mesh->mutex) != 0) {
732                 abort();
733         }
734
735         // Create hash for the new key
736         void *new_config_key;
737         new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
738
739         if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
740                 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
741                 meshlink_errno = MESHLINK_EINTERNAL;
742                 pthread_mutex_unlock(&mesh->mutex);
743                 return false;
744         }
745
746         // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
747
748         if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
749                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
750                 meshlink_errno = MESHLINK_ESTORAGE;
751                 pthread_mutex_unlock(&mesh->mutex);
752                 return false;
753         }
754
755         devtool_keyrotate_probe(1);
756
757         // Rename confbase/current/ to confbase/old
758
759         if(!config_rename(mesh, "current", "old")) {
760                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
761                 meshlink_errno = MESHLINK_ESTORAGE;
762                 pthread_mutex_unlock(&mesh->mutex);
763                 return false;
764         }
765
766         devtool_keyrotate_probe(2);
767
768         // Rename confbase/new/ to confbase/current
769
770         if(!config_rename(mesh, "new", "current")) {
771                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
772                 meshlink_errno = MESHLINK_ESTORAGE;
773                 pthread_mutex_unlock(&mesh->mutex);
774                 return false;
775         }
776
777         devtool_keyrotate_probe(3);
778
779         // Cleanup the "old" confbase sub-directory
780
781         if(!config_destroy(mesh->confbase, "old")) {
782                 pthread_mutex_unlock(&mesh->mutex);
783                 return false;
784         }
785
786         // Change the mesh handle key with new key
787
788         free(mesh->config_key);
789         mesh->config_key = new_config_key;
790
791         pthread_mutex_unlock(&mesh->mutex);
792
793         return true;
794 }
795
796 void meshlink_open_params_free(meshlink_open_params_t *params) {
797         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
798
799         if(!params) {
800                 meshlink_errno = MESHLINK_EINVAL;
801                 return;
802         }
803
804         free(params->confbase);
805         free(params->name);
806         free(params->appname);
807         free(params->lock_filename);
808
809         free(params);
810 }
811
812 /// Device class traits
813 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
814         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
815         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
816         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 },     // DEV_CLASS_PORTABLE
817         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 },     // DEV_CLASS_UNKNOWN
818 };
819
820 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
821         logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
822
823         if(!confbase || !*confbase) {
824                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
825                 meshlink_errno = MESHLINK_EINVAL;
826                 return NULL;
827         }
828
829         char lock_filename[PATH_MAX];
830         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
831
832         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
833         meshlink_open_params_t params = {
834                 .confbase = (char *)confbase,
835                 .lock_filename = lock_filename,
836                 .name = (char *)name,
837                 .appname = (char *)appname,
838                 .devclass = devclass,
839                 .netns = -1,
840         };
841
842         return meshlink_open_ex(&params);
843 }
844
845 meshlink_handle_t *meshlink_open_encrypted(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
846         logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
847
848         if(!confbase || !*confbase) {
849                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
850                 meshlink_errno = MESHLINK_EINVAL;
851                 return NULL;
852         }
853
854         char lock_filename[PATH_MAX];
855         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
856
857         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
858         meshlink_open_params_t params = {
859                 .confbase = (char *)confbase,
860                 .lock_filename = lock_filename,
861                 .name = (char *)name,
862                 .appname = (char *)appname,
863                 .devclass = devclass,
864                 .netns = -1,
865         };
866
867         if(!meshlink_open_params_set_storage_key(&params, key, keylen)) {
868                 return false;
869         }
870
871         return meshlink_open_ex(&params);
872 }
873
874 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
875         logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
876
877         if(!name) {
878                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
879                 meshlink_errno = MESHLINK_EINVAL;
880                 return NULL;
881         }
882
883         if(!check_id(name)) {
884                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
885                 meshlink_errno = MESHLINK_EINVAL;
886                 return NULL;
887         }
888
889         if(!appname || !*appname) {
890                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
891                 meshlink_errno = MESHLINK_EINVAL;
892                 return NULL;
893         }
894
895         if(strchr(appname, ' ')) {
896                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
897                 meshlink_errno = MESHLINK_EINVAL;
898                 return NULL;
899         }
900
901         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
902                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
903                 meshlink_errno = MESHLINK_EINVAL;
904                 return NULL;
905         }
906
907         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
908         meshlink_open_params_t params = {
909                 .name = (char *)name,
910                 .appname = (char *)appname,
911                 .devclass = devclass,
912                 .netns = -1,
913         };
914
915         return meshlink_open_ex(&params);
916 }
917
918 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
919         logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
920
921         // Validate arguments provided by the application
922         if(!params->appname || !*params->appname) {
923                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
924                 meshlink_errno = MESHLINK_EINVAL;
925                 return NULL;
926         }
927
928         if(strchr(params->appname, ' ')) {
929                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
930                 meshlink_errno = MESHLINK_EINVAL;
931                 return NULL;
932         }
933
934         if(params->name && !check_id(params->name)) {
935                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
936                 meshlink_errno = MESHLINK_EINVAL;
937                 return NULL;
938         }
939
940         if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
941                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
942                 meshlink_errno = MESHLINK_EINVAL;
943                 return NULL;
944         }
945
946         if((params->key && !params->keylen) || (!params->key && params->keylen)) {
947                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
948                 meshlink_errno = MESHLINK_EINVAL;
949                 return NULL;
950         }
951
952         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
953
954         if(params->confbase) {
955                 mesh->confbase = xstrdup(params->confbase);
956         }
957
958         mesh->appname = xstrdup(params->appname);
959         mesh->devclass = params->devclass;
960         mesh->netns = params->netns;
961         mesh->log_cb = global_log_cb;
962         mesh->log_level = global_log_level;
963         mesh->packet = xmalloc(sizeof(vpn_packet_t));
964
965         randomize(&mesh->prng_state, sizeof(mesh->prng_state));
966
967         do {
968                 randomize(&mesh->session_id, sizeof(mesh->session_id));
969         } while(mesh->session_id == 0);
970
971         memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
972
973         mesh->name = params->name ? xstrdup(params->name) : NULL;
974
975         // Hash the key
976         if(params->key) {
977                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
978
979                 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
980                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
981                         meshlink_close(mesh);
982                         meshlink_errno = MESHLINK_EINTERNAL;
983                         return NULL;
984                 }
985         }
986
987         // initialize mutexes and conds
988         pthread_mutexattr_t attr;
989         pthread_mutexattr_init(&attr);
990
991         if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
992                 abort();
993         }
994
995         pthread_mutex_init(&mesh->mutex, &attr);
996         pthread_cond_init(&mesh->cond, NULL);
997
998         mesh->threadstarted = false;
999         event_loop_init(&mesh->loop);
1000         mesh->loop.data = mesh;
1001
1002         meshlink_queue_init(&mesh->outpacketqueue);
1003
1004         // Atomically lock the configuration directory.
1005         if(!main_config_lock(mesh, params->lock_filename)) {
1006                 meshlink_close(mesh);
1007                 return NULL;
1008         }
1009
1010         // If no configuration exists yet, create it.
1011
1012         bool new_configuration = false;
1013
1014         if(!meshlink_confbase_exists(mesh)) {
1015                 if(!mesh->name) {
1016                         logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1017                         meshlink_close(mesh);
1018                         meshlink_errno = MESHLINK_ESTORAGE;
1019                         return NULL;
1020                 }
1021
1022                 if(!meshlink_setup(mesh)) {
1023                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1024                         meshlink_close(mesh);
1025                         return NULL;
1026                 }
1027
1028                 new_configuration = true;
1029         } else {
1030                 if(!meshlink_read_config(mesh)) {
1031                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1032                         meshlink_close(mesh);
1033                         return NULL;
1034                 }
1035         }
1036
1037         mesh->storage_policy = params->storage_policy;
1038
1039 #ifdef HAVE_MINGW
1040         struct WSAData wsa_state;
1041         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1042 #endif
1043
1044         // Setup up everything
1045         // TODO: we should not open listening sockets yet
1046
1047         bool success = false;
1048
1049         if(mesh->netns != -1) {
1050 #ifdef HAVE_SETNS
1051                 pthread_t thr;
1052
1053                 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1054                         void *retval = NULL;
1055                         success = pthread_join(thr, &retval) == 0 && retval;
1056                 }
1057
1058 #else
1059                 meshlink_errno = MESHLINK_EINTERNAL;
1060                 return NULL;
1061
1062 #endif // HAVE_SETNS
1063         } else {
1064                 success = setup_network(mesh);
1065         }
1066
1067         if(!success) {
1068                 meshlink_close(mesh);
1069                 meshlink_errno = MESHLINK_ENETWORK;
1070                 return NULL;
1071         }
1072
1073         if(!node_write_config(mesh, mesh->self, new_configuration)) {
1074                 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1075                 return NULL;
1076         }
1077
1078         idle_set(&mesh->loop, idle, mesh);
1079
1080         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1081         return mesh;
1082 }
1083
1084 static void *meshlink_main_loop(void *arg) {
1085         meshlink_handle_t *mesh = arg;
1086
1087         if(mesh->netns != -1) {
1088 #ifdef HAVE_SETNS
1089
1090                 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1091                         pthread_cond_signal(&mesh->cond);
1092                         return NULL;
1093                 }
1094
1095 #else
1096                 pthread_cond_signal(&mesh->cond);
1097                 return NULL;
1098 #endif // HAVE_SETNS
1099         }
1100
1101         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1102                 abort();
1103         }
1104
1105         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1106         pthread_cond_broadcast(&mesh->cond);
1107         main_loop(mesh);
1108         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1109
1110         pthread_mutex_unlock(&mesh->mutex);
1111
1112         return NULL;
1113 }
1114
1115 bool meshlink_start(meshlink_handle_t *mesh) {
1116         if(!mesh) {
1117                 meshlink_errno = MESHLINK_EINVAL;
1118                 return false;
1119         }
1120
1121         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1122
1123         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1124                 abort();
1125         }
1126
1127         assert(mesh->self);
1128         assert(mesh->private_key);
1129         assert(mesh->self->ecdsa);
1130         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1131
1132         if(mesh->threadstarted) {
1133                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1134                 pthread_mutex_unlock(&mesh->mutex);
1135                 return true;
1136         }
1137
1138         // Reset node connection timers
1139         if(mesh->peer) {
1140                 mesh->peer->last_connect_try = 0;
1141         }
1142
1143         //Check that a valid name is set
1144         if(!mesh->name) {
1145                 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1146                 meshlink_errno = MESHLINK_EINVAL;
1147                 pthread_mutex_unlock(&mesh->mutex);
1148                 return false;
1149         }
1150
1151         init_outgoings(mesh);
1152
1153         // Start the main thread
1154
1155         event_loop_start(&mesh->loop);
1156
1157         // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1158         pthread_attr_t attr;
1159         pthread_attr_init(&attr);
1160         pthread_attr_setstacksize(&attr, 1024 * 1024);
1161
1162         if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1163                 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1164                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1165                 meshlink_errno = MESHLINK_EINTERNAL;
1166                 event_loop_stop(&mesh->loop);
1167                 pthread_mutex_unlock(&mesh->mutex);
1168                 return false;
1169         }
1170
1171         pthread_cond_wait(&mesh->cond, &mesh->mutex);
1172         mesh->threadstarted = true;
1173
1174         pthread_mutex_unlock(&mesh->mutex);
1175         return true;
1176 }
1177
1178 void meshlink_stop(meshlink_handle_t *mesh) {
1179         logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1180
1181         if(!mesh) {
1182                 meshlink_errno = MESHLINK_EINVAL;
1183                 return;
1184         }
1185
1186         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1187                 abort();
1188         }
1189
1190         // Shut down the main thread
1191         event_loop_stop(&mesh->loop);
1192
1193         // TODO: send something to a local socket to kick the event loop
1194
1195         if(mesh->threadstarted) {
1196                 // Wait for the main thread to finish
1197                 pthread_mutex_unlock(&mesh->mutex);
1198
1199                 if(pthread_join(mesh->thread, NULL) != 0) {
1200                         abort();
1201                 }
1202
1203                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1204                         abort();
1205                 }
1206
1207                 mesh->threadstarted = false;
1208         }
1209
1210         // Close all metaconnections
1211         if(mesh->connection) {
1212                 mesh->connection->outgoing = NULL;
1213                 terminate_connection(mesh, mesh->connection, false);
1214         }
1215
1216         exit_outgoings(mesh);
1217
1218         // Try to write out any changed node config files, ignore errors at this point.
1219         if(mesh->peer && mesh->peer->status.dirty) {
1220                 if(!node_write_config(mesh, mesh->peer, false)) {
1221                         // ignore
1222                 }
1223         }
1224
1225         pthread_mutex_unlock(&mesh->mutex);
1226 }
1227
1228 void meshlink_close(meshlink_handle_t *mesh) {
1229         logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1230
1231         if(!mesh) {
1232                 meshlink_errno = MESHLINK_EINVAL;
1233                 return;
1234         }
1235
1236         // stop can be called even if mesh has not been started
1237         meshlink_stop(mesh);
1238
1239         // lock is not released after this
1240         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1241                 abort();
1242         }
1243
1244         // Close and free all resources used.
1245
1246         close_network_connections(mesh);
1247
1248         logger(mesh, MESHLINK_INFO, "Terminating");
1249
1250         event_loop_exit(&mesh->loop);
1251
1252 #ifdef HAVE_MINGW
1253
1254         if(mesh->confbase) {
1255                 WSACleanup();
1256         }
1257
1258 #endif
1259
1260         if(mesh->netns != -1) {
1261                 close(mesh->netns);
1262         }
1263
1264         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1265                 free(packet);
1266         }
1267
1268         meshlink_queue_exit(&mesh->outpacketqueue);
1269
1270         free(mesh->name);
1271         free(mesh->appname);
1272         free(mesh->confbase);
1273         free(mesh->config_key);
1274         free(mesh->external_address_url);
1275         free(mesh->packet);
1276         ecdsa_free(mesh->private_key);
1277
1278         main_config_unlock(mesh);
1279
1280         pthread_mutex_unlock(&mesh->mutex);
1281         pthread_mutex_destroy(&mesh->mutex);
1282
1283         memset(mesh, 0, sizeof(*mesh));
1284
1285         free(mesh);
1286 }
1287
1288 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1289         logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1290
1291         if(!params) {
1292                 meshlink_errno = MESHLINK_EINVAL;
1293                 return false;
1294         }
1295
1296         if(!params->confbase) {
1297                 /* Ephemeral instances */
1298                 return true;
1299         }
1300
1301         /* Exit early if the confbase directory itself doesn't exist */
1302         if(access(params->confbase, F_OK) && errno == ENOENT) {
1303                 return true;
1304         }
1305
1306         /* Take the lock the same way meshlink_open() would. */
1307         FILE *lockfile = fopen(params->lock_filename, "w+");
1308
1309         if(!lockfile) {
1310                 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1311                 meshlink_errno = MESHLINK_ESTORAGE;
1312                 return false;
1313         }
1314
1315 #ifdef FD_CLOEXEC
1316         fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1317 #endif
1318
1319 #ifdef HAVE_MINGW
1320         // TODO: use _locking()?
1321 #else
1322
1323         if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1324                 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1325                 fclose(lockfile);
1326                 meshlink_errno = MESHLINK_EBUSY;
1327                 return false;
1328         }
1329
1330 #endif
1331
1332         if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1333                 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1334                 return false;
1335         }
1336
1337         if(unlink(params->lock_filename)) {
1338                 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1339                 fclose(lockfile);
1340                 meshlink_errno = MESHLINK_ESTORAGE;
1341                 return false;
1342         }
1343
1344         fclose(lockfile);
1345
1346         if(!sync_path(params->confbase)) {
1347                 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1348                 meshlink_errno = MESHLINK_ESTORAGE;
1349                 return false;
1350         }
1351
1352         return true;
1353 }
1354
1355 bool meshlink_destroy(const char *confbase) {
1356         logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1357
1358         char lock_filename[PATH_MAX];
1359         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1360
1361         meshlink_open_params_t params = {
1362                 .confbase = (char *)confbase,
1363                 .lock_filename = lock_filename,
1364         };
1365
1366         return meshlink_destroy_ex(&params);
1367 }
1368
1369 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1370         logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1371
1372         if(!mesh) {
1373                 meshlink_errno = MESHLINK_EINVAL;
1374                 return;
1375         }
1376
1377         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1378                 abort();
1379         }
1380
1381         mesh->receive_cb = cb;
1382         pthread_mutex_unlock(&mesh->mutex);
1383 }
1384
1385 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1386         logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1387
1388         if(!mesh) {
1389                 meshlink_errno = MESHLINK_EINVAL;
1390                 return;
1391         }
1392
1393         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1394                 abort();
1395         }
1396
1397         mesh->connection_try_cb = cb;
1398         pthread_mutex_unlock(&mesh->mutex);
1399 }
1400
1401 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1402         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1403
1404         if(!mesh) {
1405                 meshlink_errno = MESHLINK_EINVAL;
1406                 return;
1407         }
1408
1409         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1410                 abort();
1411         }
1412
1413         mesh->node_status_cb = cb;
1414         pthread_mutex_unlock(&mesh->mutex);
1415 }
1416
1417 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1418         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1419
1420         if(!mesh) {
1421                 meshlink_errno = MESHLINK_EINVAL;
1422                 return;
1423         }
1424
1425         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1426                 abort();
1427         }
1428
1429         mesh->node_duplicate_cb = cb;
1430         pthread_mutex_unlock(&mesh->mutex);
1431 }
1432
1433 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1434         logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1435
1436         if(mesh) {
1437                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1438                         abort();
1439                 }
1440
1441                 mesh->log_cb = cb;
1442                 mesh->log_level = cb ? level : 0;
1443                 pthread_mutex_unlock(&mesh->mutex);
1444         } else {
1445                 global_log_cb = cb;
1446                 global_log_level = cb ? level : 0;
1447         }
1448 }
1449
1450 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1451         logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1452
1453         if(!mesh) {
1454                 meshlink_errno = MESHLINK_EINVAL;
1455                 return;
1456         }
1457
1458         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1459                 abort();
1460         }
1461
1462         mesh->error_cb = cb;
1463         pthread_mutex_unlock(&mesh->mutex);
1464 }
1465
1466 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1467         logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1468
1469         // Validate arguments
1470         if(!mesh || !destination) {
1471                 meshlink_errno = MESHLINK_EINVAL;
1472                 return false;
1473         }
1474
1475         if(!len) {
1476                 return true;
1477         }
1478
1479         if(!data || len > MTU) {
1480                 meshlink_errno = MESHLINK_EINVAL;
1481                 return false;
1482         }
1483
1484         // Prepare the packet
1485         vpn_packet_t *packet = malloc(sizeof(*packet));
1486
1487         if(!packet) {
1488                 meshlink_errno = MESHLINK_ENOMEM;
1489                 return false;
1490         }
1491
1492         packet->len = len;
1493         memcpy(packet->data, data, len);
1494
1495         // Queue it
1496         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1497                 free(packet);
1498                 meshlink_errno = MESHLINK_ENOMEM;
1499                 return false;
1500         }
1501
1502         logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1503
1504         // Notify event loop
1505         signal_trigger(&mesh->loop, &mesh->datafromapp);
1506
1507         return true;
1508 }
1509
1510 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1511         (void)loop;
1512         meshlink_handle_t *mesh = data;
1513
1514         logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1515
1516         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1517                 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1518                 send_raw_packet(mesh, mesh->peer->connection, packet);
1519                 free(packet);
1520         }
1521 }
1522
1523 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1524         if(!mesh || !node) {
1525                 meshlink_errno = MESHLINK_EINVAL;
1526                 return NULL;
1527         }
1528
1529         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1530                 abort();
1531         }
1532
1533         node_t *n = (node_t *)node;
1534
1535         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1536                 meshlink_errno = MESHLINK_EINTERNAL;
1537                 pthread_mutex_unlock(&mesh->mutex);
1538                 return false;
1539         }
1540
1541         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1542
1543         if(!fingerprint) {
1544                 meshlink_errno = MESHLINK_EINTERNAL;
1545         }
1546
1547         pthread_mutex_unlock(&mesh->mutex);
1548         return fingerprint;
1549 }
1550
1551 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1552         if(!mesh) {
1553                 meshlink_errno = MESHLINK_EINVAL;
1554                 return NULL;
1555         }
1556
1557         return (meshlink_node_t *)mesh->self;
1558 }
1559
1560 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1561         if(!mesh || !name) {
1562                 meshlink_errno = MESHLINK_EINVAL;
1563                 return NULL;
1564         }
1565
1566         node_t *n = NULL;
1567
1568         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1569                 abort();
1570         }
1571
1572         n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1573         pthread_mutex_unlock(&mesh->mutex);
1574
1575         if(!n) {
1576                 meshlink_errno = MESHLINK_ENOENT;
1577         }
1578
1579         return (meshlink_node_t *)n;
1580 }
1581
1582 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1583         logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1584
1585         if(!mesh || !data || !len || !signature || !siglen) {
1586                 meshlink_errno = MESHLINK_EINVAL;
1587                 return false;
1588         }
1589
1590         if(*siglen < MESHLINK_SIGLEN) {
1591                 meshlink_errno = MESHLINK_EINVAL;
1592                 return false;
1593         }
1594
1595         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1596                 abort();
1597         }
1598
1599         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1600                 meshlink_errno = MESHLINK_EINTERNAL;
1601                 pthread_mutex_unlock(&mesh->mutex);
1602                 return false;
1603         }
1604
1605         *siglen = MESHLINK_SIGLEN;
1606         pthread_mutex_unlock(&mesh->mutex);
1607         return true;
1608 }
1609
1610 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1611         logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1612
1613         if(!mesh || !source || !data || !len || !signature) {
1614                 meshlink_errno = MESHLINK_EINVAL;
1615                 return false;
1616         }
1617
1618         if(siglen != MESHLINK_SIGLEN) {
1619                 meshlink_errno = MESHLINK_EINVAL;
1620                 return false;
1621         }
1622
1623         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1624                 abort();
1625         }
1626
1627         bool rval = false;
1628
1629         struct node_t *n = (struct node_t *)source;
1630
1631         if(!node_read_public_key(mesh, n)) {
1632                 meshlink_errno = MESHLINK_EINTERNAL;
1633                 rval = false;
1634         } else {
1635                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1636         }
1637
1638         pthread_mutex_unlock(&mesh->mutex);
1639         return rval;
1640 }
1641
1642 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1643         logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1644
1645         if(!mesh || !node || !address) {
1646                 meshlink_errno = MESHLINK_EINVAL;
1647                 return false;
1648         }
1649
1650         if(!is_valid_hostname(address)) {
1651                 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1652                 meshlink_errno = MESHLINK_EINVAL;
1653                 return false;
1654         }
1655
1656         if((node_t *)node != mesh->self && !port) {
1657                 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1658                 meshlink_errno = MESHLINK_EINVAL;
1659                 return false;
1660
1661         }
1662
1663         if(port && !is_valid_port(port)) {
1664                 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1665                 meshlink_errno = MESHLINK_EINVAL;
1666                 return false;
1667         }
1668
1669         char *canonical_address;
1670
1671         xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1672
1673         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1674                 abort();
1675         }
1676
1677         node_t *n = (node_t *)node;
1678         free(n->canonical_address);
1679         n->canonical_address = canonical_address;
1680
1681         if(!node_write_config(mesh, n, false)) {
1682                 pthread_mutex_unlock(&mesh->mutex);
1683                 return false;
1684         }
1685
1686         pthread_mutex_unlock(&mesh->mutex);
1687
1688         return config_sync(mesh, "current");
1689 }
1690
1691 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1692         logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1693
1694         if(!mesh || !node) {
1695                 meshlink_errno = MESHLINK_EINVAL;
1696                 return false;
1697         }
1698
1699         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1700                 abort();
1701         }
1702
1703         node_t *n = (node_t *)node;
1704         free(n->canonical_address);
1705         n->canonical_address = NULL;
1706
1707         if(!node_write_config(mesh, n, false)) {
1708                 pthread_mutex_unlock(&mesh->mutex);
1709                 return false;
1710         }
1711
1712         pthread_mutex_unlock(&mesh->mutex);
1713
1714         return config_sync(mesh, "current");
1715 }
1716
1717 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1718         logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1719
1720         if(!mesh || !invitation) {
1721                 meshlink_errno = MESHLINK_EINVAL;
1722                 return false;
1723         }
1724
1725         if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1726                 meshlink_errno = MESHLINK_EINVAL;
1727                 return false;
1728         }
1729
1730         join_state_t state = {
1731                 .mesh = mesh,
1732                 .sock = -1,
1733         };
1734
1735         ecdsa_t *key = NULL;
1736         ecdsa_t *hiskey = NULL;
1737
1738         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1739         char copy[strlen(invitation) + 1];
1740
1741         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1742                 abort();
1743         }
1744
1745         //Before doing meshlink_join make sure we are not connected to another mesh
1746         if(mesh->threadstarted) {
1747                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1748                 meshlink_errno = MESHLINK_EINVAL;
1749                 goto exit;
1750         }
1751
1752         // Refuse to join a mesh if we are already part of one. We are part of one if we know at least one other node.
1753         if(mesh->peer) {
1754                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1755                 meshlink_errno = MESHLINK_EINVAL;
1756                 goto exit;
1757         }
1758
1759         strcpy(copy, invitation);
1760
1761         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1762
1763         char *slash = strchr(copy, '/');
1764
1765         if(!slash) {
1766                 goto invalid;
1767         }
1768
1769         *slash++ = 0;
1770
1771         if(strlen(slash) != 48) {
1772                 goto invalid;
1773         }
1774
1775         char *address = copy;
1776         char *port = NULL;
1777
1778         if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
1779                 goto invalid;
1780         }
1781
1782         if(mesh->inviter_commits_first) {
1783                 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1784         }
1785
1786         // Generate a throw-away key for the invitation.
1787         key = ecdsa_generate();
1788
1789         if(!key) {
1790                 meshlink_errno = MESHLINK_EINTERNAL;
1791                 goto exit;
1792         }
1793
1794         char *b64key = ecdsa_get_base64_public_key(key);
1795         char *comma;
1796
1797         while(address && *address) {
1798                 // We allow commas in the address part to support multiple addresses in one invitation URL.
1799                 comma = strchr(address, ',');
1800
1801                 if(comma) {
1802                         *comma++ = 0;
1803                 }
1804
1805                 // Split of the port
1806                 port = strrchr(address, ':');
1807
1808                 if(!port) {
1809                         goto invalid;
1810                 }
1811
1812                 *port++ = 0;
1813
1814                 // IPv6 address are enclosed in brackets, per RFC 3986
1815                 if(*address == '[') {
1816                         address++;
1817                         char *bracket = strchr(address, ']');
1818
1819                         if(!bracket) {
1820                                 goto invalid;
1821                         }
1822
1823                         *bracket++ = 0;
1824
1825                         if(*bracket) {
1826                                 goto invalid;
1827                         }
1828                 }
1829
1830                 // Connect to the meshlink daemon mentioned in the URL.
1831                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1832
1833                 if(ai) {
1834                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1835                                 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1836
1837                                 if(state.sock == -1) {
1838                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1839                                         meshlink_errno = MESHLINK_ENETWORK;
1840                                         continue;
1841                                 }
1842
1843 #ifdef SO_NOSIGPIPE
1844                                 int nosigpipe = 1;
1845                                 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1846 #endif
1847
1848                                 set_timeout(state.sock, 5000);
1849
1850                                 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
1851                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1852                                         meshlink_errno = MESHLINK_ENETWORK;
1853                                         closesocket(state.sock);
1854                                         state.sock = -1;
1855                                         continue;
1856                                 }
1857
1858                                 break;
1859                         }
1860
1861                         freeaddrinfo(ai);
1862                 } else {
1863                         meshlink_errno = MESHLINK_ERESOLV;
1864                 }
1865
1866                 if(state.sock != -1 || !comma) {
1867                         break;
1868                 }
1869
1870                 address = comma;
1871         }
1872
1873         if(state.sock == -1) {
1874                 goto exit;
1875         }
1876
1877         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1878
1879         // Tell him we have an invitation, and give him our throw-away key.
1880
1881         state.blen = 0;
1882
1883         if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1884                 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1885                 meshlink_errno = MESHLINK_ENETWORK;
1886                 goto exit;
1887         }
1888
1889         free(b64key);
1890
1891         char hisname[4096] = "";
1892         int code, hismajor, hisminor = 0;
1893
1894         if(!recvline(&state) || sscanf(state.line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(&state) || !rstrip(state.line) || sscanf(state.line, "%d ", &code) != 1 || code != ACK || strlen(state.line) < 3) {
1895                 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1896                 meshlink_errno = MESHLINK_ENETWORK;
1897                 goto exit;
1898         }
1899
1900         // Check if the hash of the key he gave us matches the hash in the URL.
1901         char *fingerprint = state.line + 2;
1902         char hishash[64];
1903
1904         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1905                 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
1906                 meshlink_errno = MESHLINK_EINTERNAL;
1907                 goto exit;
1908         }
1909
1910         if(memcmp(hishash, state.hash, 18)) {
1911                 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
1912                 meshlink_errno = MESHLINK_EPEER;
1913                 goto exit;
1914         }
1915
1916         hiskey = ecdsa_set_base64_public_key(fingerprint);
1917
1918         if(!hiskey) {
1919                 meshlink_errno = MESHLINK_EINTERNAL;
1920                 goto exit;
1921         }
1922
1923         // Start an SPTPS session
1924         if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1925                 meshlink_errno = MESHLINK_EINTERNAL;
1926                 goto exit;
1927         }
1928
1929         // Feed rest of input buffer to SPTPS
1930         if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
1931                 meshlink_errno = MESHLINK_EPEER;
1932                 goto exit;
1933         }
1934
1935         ssize_t len;
1936         logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
1937
1938         while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
1939                 if(len < 0) {
1940                         if(errno == EINTR) {
1941                                 continue;
1942                         }
1943
1944                         logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1945                         meshlink_errno = MESHLINK_ENETWORK;
1946                         goto exit;
1947                 }
1948
1949                 if(!sptps_receive_data(&state.sptps, state.line, len)) {
1950                         meshlink_errno = MESHLINK_EPEER;
1951                         goto exit;
1952                 }
1953         }
1954
1955         if(!state.success) {
1956                 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
1957                 meshlink_errno = MESHLINK_EPEER;
1958                 goto exit;
1959         }
1960
1961         sptps_stop(&state.sptps);
1962         ecdsa_free(hiskey);
1963         ecdsa_free(key);
1964         closesocket(state.sock);
1965
1966         pthread_mutex_unlock(&mesh->mutex);
1967         return true;
1968
1969 invalid:
1970         logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
1971         meshlink_errno = MESHLINK_EINVAL;
1972 exit:
1973         sptps_stop(&state.sptps);
1974         ecdsa_free(hiskey);
1975         ecdsa_free(key);
1976
1977         if(state.sock != -1) {
1978                 closesocket(state.sock);
1979         }
1980
1981         pthread_mutex_unlock(&mesh->mutex);
1982         return false;
1983 }
1984
1985 char *meshlink_export(meshlink_handle_t *mesh) {
1986         if(!mesh) {
1987                 meshlink_errno = MESHLINK_EINVAL;
1988                 return NULL;
1989         }
1990
1991         // Create a config file on the fly.
1992
1993         uint8_t buf[4096];
1994         packmsg_output_t out = {buf, sizeof(buf)};
1995         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
1996         packmsg_add_str(&out, mesh->name);
1997         packmsg_add_str(&out, CORE_MESH);
1998
1999         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2000                 abort();
2001         }
2002
2003         packmsg_add_int32(&out, mesh->self->devclass);
2004         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2005         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2006
2007         if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2008                 char *canonical_address = NULL;
2009                 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2010                 packmsg_add_str(&out, canonical_address);
2011                 free(canonical_address);
2012         } else {
2013                 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2014         }
2015
2016         uint32_t count = 0;
2017
2018         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2019                 if(mesh->self->recent[i].sa.sa_family) {
2020                         count++;
2021                 } else {
2022                         break;
2023                 }
2024         }
2025
2026         packmsg_add_array(&out, count);
2027
2028         for(uint32_t i = 0; i < count; i++) {
2029                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2030         }
2031
2032         packmsg_add_int64(&out, 0);
2033         packmsg_add_int64(&out, 0);
2034
2035         pthread_mutex_unlock(&mesh->mutex);
2036
2037         if(!packmsg_output_ok(&out)) {
2038                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2039                 meshlink_errno = MESHLINK_EINTERNAL;
2040                 return NULL;
2041         }
2042
2043         // Prepare a base64-encoded packmsg array containing our config file
2044
2045         uint32_t len = packmsg_output_size(&out, buf);
2046         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2047         uint8_t *buf2 = xmalloc(len2);
2048         packmsg_output_t out2 = {buf2, len2};
2049         packmsg_add_array(&out2, 1);
2050         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2051
2052         if(!packmsg_output_ok(&out2)) {
2053                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2054                 meshlink_errno = MESHLINK_EINTERNAL;
2055                 free(buf2);
2056                 return NULL;
2057         }
2058
2059         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2060
2061         return (char *)buf2;
2062 }
2063
2064 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2065         logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2066
2067         if(!mesh || !data) {
2068                 meshlink_errno = MESHLINK_EINVAL;
2069                 return false;
2070         }
2071
2072         size_t datalen = strlen(data);
2073         uint8_t *buf = xmalloc(datalen);
2074         int buflen = b64decode(data, buf, datalen);
2075
2076         if(!buflen) {
2077                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2078                 free(buf);
2079                 meshlink_errno = MESHLINK_EPEER;
2080                 return false;
2081         }
2082
2083         packmsg_input_t in = {buf, buflen};
2084         uint32_t count = packmsg_get_array(&in);
2085
2086         if(!count) {
2087                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2088                 free(buf);
2089                 meshlink_errno = MESHLINK_EPEER;
2090                 return false;
2091         }
2092
2093         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2094                 abort();
2095         }
2096
2097         while(count--) {
2098                 const void *data2;
2099                 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2100
2101                 if(!len2) {
2102                         break;
2103                 }
2104
2105                 packmsg_input_t in2 = {data2, len2};
2106                 uint32_t version = packmsg_get_uint32(&in2);
2107                 char *name = packmsg_get_str_dup(&in2);
2108
2109                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2110                         free(name);
2111                         packmsg_input_invalidate(&in);
2112                         break;
2113                 }
2114
2115                 if(!check_id(name)) {
2116                         free(name);
2117                         break;
2118                 }
2119
2120                 node_t *n = lookup_node(mesh, name);
2121
2122                 if(n) {
2123                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2124                         free(name);
2125                         continue;
2126                 }
2127
2128                 n = new_node();
2129                 n->name = name;
2130
2131                 config_t config = {data2, len2};
2132
2133                 if(!node_read_from_config(mesh, n, &config)) {
2134                         free_node(n);
2135                         packmsg_input_invalidate(&in);
2136                         break;
2137                 }
2138
2139                 if(!node_write_config(mesh, n, true)) {
2140                         free_node(n);
2141                         free(buf);
2142                         return false;
2143                 }
2144
2145                 node_add(mesh, n);
2146         }
2147
2148         pthread_mutex_unlock(&mesh->mutex);
2149
2150         free(buf);
2151
2152         if(!packmsg_done(&in)) {
2153                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2154                 meshlink_errno = MESHLINK_EPEER;
2155                 return false;
2156         }
2157
2158         if(!config_sync(mesh, "current")) {
2159                 return false;
2160         }
2161
2162         return true;
2163 }
2164
2165 /* Hint that a hostname may be found at an address
2166  * See header file for detailed comment.
2167  */
2168 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2169         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2170
2171         if(!mesh || !node || !addr) {
2172                 meshlink_errno = EINVAL;
2173                 return;
2174         }
2175
2176         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2177                 abort();
2178         }
2179
2180         node_t *n = (node_t *)node;
2181
2182         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2183                 if(!node_write_config(mesh, n, false)) {
2184                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2185                 }
2186         }
2187
2188         pthread_mutex_unlock(&mesh->mutex);
2189         // @TODO do we want to fire off a connection attempt right away?
2190 }
2191
2192 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2193         if(mesh->node_status_cb) {
2194                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2195         }
2196 }
2197
2198 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2199         if(!mesh->node_duplicate_cb || n->status.duplicate) {
2200                 return;
2201         }
2202
2203         n->status.duplicate = true;
2204         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2205 }
2206
2207 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
2208         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
2209
2210         if(!mesh) {
2211                 meshlink_errno = MESHLINK_EINVAL;
2212                 return;
2213         }
2214
2215         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2216                 abort();
2217         }
2218
2219         pthread_mutex_unlock(&mesh->mutex);
2220 }
2221
2222 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
2223         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
2224
2225         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2226                 meshlink_errno = EINVAL;
2227                 return;
2228         }
2229
2230         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
2231                 meshlink_errno = EINVAL;
2232                 return;
2233         }
2234
2235         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2236                 abort();
2237         }
2238
2239         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
2240         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
2241         pthread_mutex_unlock(&mesh->mutex);
2242 }
2243
2244 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
2245         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
2246
2247         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2248                 meshlink_errno = EINVAL;
2249                 return;
2250         }
2251
2252         if(fast_retry_period < 0) {
2253                 meshlink_errno = EINVAL;
2254                 return;
2255         }
2256
2257         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2258                 abort();
2259         }
2260
2261         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
2262         pthread_mutex_unlock(&mesh->mutex);
2263 }
2264
2265 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
2266         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
2267
2268         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
2269                 meshlink_errno = EINVAL;
2270                 return;
2271         }
2272
2273         if(maxtimeout < 0) {
2274                 meshlink_errno = EINVAL;
2275                 return;
2276         }
2277
2278         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2279                 abort();
2280         }
2281
2282         mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
2283         pthread_mutex_unlock(&mesh->mutex);
2284 }
2285
2286 void meshlink_reset_timers(struct meshlink_handle *mesh) {
2287         logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
2288
2289         if(!mesh) {
2290                 return;
2291         }
2292
2293         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2294                 abort();
2295         }
2296
2297         handle_network_change(mesh, true);
2298
2299         pthread_mutex_unlock(&mesh->mutex);
2300 }
2301
2302 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
2303         logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
2304
2305         if(!mesh) {
2306                 meshlink_errno = EINVAL;
2307                 return;
2308         }
2309
2310         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2311                 abort();
2312         }
2313
2314         mesh->inviter_commits_first = inviter_commits_first;
2315         pthread_mutex_unlock(&mesh->mutex);
2316 }
2317
2318 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
2319         logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
2320
2321         if(!mesh) {
2322                 meshlink_errno = EINVAL;
2323                 return;
2324         }
2325
2326         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2327                 abort();
2328         }
2329
2330         mesh->storage_policy = policy;
2331         pthread_mutex_unlock(&mesh->mutex);
2332 }
2333
2334 void handle_network_change(meshlink_handle_t *mesh, bool online) {
2335         (void)online;
2336
2337         if(!mesh->loop.running) {
2338                 return;
2339         }
2340
2341         retry(mesh);
2342         signal_trigger(&mesh->loop, &mesh->datafromapp);
2343 }
2344
2345 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
2346         // We should only call the callback function if we are in the background thread.
2347         if(!mesh->error_cb) {
2348                 return;
2349         }
2350
2351         if(!mesh->threadstarted) {
2352                 return;
2353         }
2354
2355         if(mesh->thread == pthread_self()) {
2356                 mesh->error_cb(mesh, cb_errno);
2357         }
2358 }
2359
2360 static void __attribute__((constructor)) meshlink_init(void) {
2361         crypto_init();
2362 }
2363
2364 static void __attribute__((destructor)) meshlink_exit(void) {
2365         crypto_exit();
2366 }