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