]> git.meshlink.io Git - meshlink-tiny/blob - src/meshlink.c
Remove support for multiple connections.
[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 "route.h"
34 #include "sockaddr.h"
35 #include "utils.h"
36 #include "xalloc.h"
37 #include "ed25519/sha512.h"
38 #include "devtools.h"
39
40 #ifndef MSG_NOSIGNAL
41 #define MSG_NOSIGNAL 0
42 #endif
43 __thread meshlink_errno_t meshlink_errno;
44 meshlink_log_cb_t global_log_cb;
45 meshlink_log_level_t global_log_level;
46
47 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
48
49 static int rstrip(char *value) {
50         int len = strlen(value);
51
52         while(len && strchr("\t\r\n ", value[len - 1])) {
53                 value[--len] = 0;
54         }
55
56         return len;
57 }
58
59 static bool is_valid_hostname(const char *hostname) {
60         if(!*hostname) {
61                 return false;
62         }
63
64         for(const char *p = hostname; *p; p++) {
65                 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
66                         return false;
67                 }
68         }
69
70         return true;
71 }
72
73 static bool is_valid_port(const char *port) {
74         if(!*port) {
75                 return false;
76         }
77
78         if(isdigit(*port)) {
79                 char *end;
80                 unsigned long int result = strtoul(port, &end, 10);
81                 return result && result < 65536 && !*end;
82         }
83
84         for(const char *p = port; *p; p++) {
85                 if(!(isalnum(*p) || *p == '-')) {
86                         return false;
87                 }
88         }
89
90         return true;
91 }
92
93 static void set_timeout(int sock, int timeout) {
94 #ifdef _WIN32
95         DWORD tv = timeout;
96 #else
97         struct timeval tv;
98         tv.tv_sec = timeout / 1000;
99         tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
100 #endif
101         setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
102         setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
103 }
104
105 struct socket_in_netns_params {
106         int domain;
107         int type;
108         int protocol;
109         int netns;
110         int fd;
111 };
112
113 #ifdef HAVE_SETNS
114 static void *socket_in_netns_thread(void *arg) {
115         struct socket_in_netns_params *params = arg;
116
117         if(setns(params->netns, CLONE_NEWNET) == -1) {
118                 meshlink_errno = MESHLINK_EINVAL;
119                 return NULL;
120         }
121
122         params->fd = socket(params->domain, params->type, params->protocol);
123
124         return NULL;
125 }
126 #endif // HAVE_SETNS
127
128 static int socket_in_netns(int domain, int type, int protocol, int netns) {
129         if(netns == -1) {
130                 return socket(domain, type, protocol);
131         }
132
133 #ifdef HAVE_SETNS
134         struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
135
136         pthread_t thr;
137
138         if(pthread_create(&thr, NULL, socket_in_netns_thread, &params) == 0) {
139                 if(pthread_join(thr, NULL) != 0) {
140                         abort();
141                 }
142         }
143
144         return params.fd;
145 #else
146         return -1;
147 #endif // HAVE_SETNS
148
149 }
150
151 static bool write_main_config_files(meshlink_handle_t *mesh) {
152         if(!mesh->confbase) {
153                 return true;
154         }
155
156         uint8_t buf[4096];
157
158         /* Write the main config file */
159         packmsg_output_t out = {buf, sizeof buf};
160
161         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
162         packmsg_add_str(&out, mesh->name);
163         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
164         packmsg_add_nil(&out); // Invitation keys are not supported
165         packmsg_add_uint16(&out, atoi(mesh->myport));
166
167         if(!packmsg_output_ok(&out)) {
168                 return false;
169         }
170
171         config_t config = {buf, packmsg_output_size(&out, buf)};
172
173         if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
174                 return false;
175         }
176
177         /* Write our own host config file */
178         if(!node_write_config(mesh, mesh->self, true)) {
179                 return false;
180         }
181
182         return true;
183 }
184
185 typedef struct {
186         meshlink_handle_t *mesh;
187         int sock;
188         char cookie[18 + 32];
189         char hash[18];
190         bool success;
191         sptps_t sptps;
192         char *data;
193         size_t thedatalen;
194         size_t blen;
195         char line[4096];
196         char buffer[4096];
197 } join_state_t;
198
199 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
200         meshlink_handle_t *mesh = state->mesh;
201         packmsg_input_t in = {buf, len};
202         uint32_t version = packmsg_get_uint32(&in);
203
204         if(version != MESHLINK_INVITATION_VERSION) {
205                 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
206                 return false;
207         }
208
209         char *name = packmsg_get_str_dup(&in);
210         packmsg_skip_element(&in); // submesh_name
211         dev_class_t devclass = packmsg_get_int32(&in);
212         uint32_t count = packmsg_get_array(&in);
213
214         if(!name || !check_id(name)) {
215                 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
216                 free(name);
217                 return false;
218         }
219
220         if(!count) {
221                 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
222                 free(name);
223                 return false;
224         }
225
226         free(mesh->name);
227         free(mesh->self->name);
228         mesh->name = name;
229         mesh->self->name = xstrdup(name);
230         mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
231
232         // Initialize configuration directory
233         if(!config_init(mesh, "current")) {
234                 return false;
235         }
236
237         if(!write_main_config_files(mesh)) {
238                 return false;
239         }
240
241         // Write host config files
242         for(uint32_t i = 0; i < count; i++) {
243                 const void *data;
244                 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
245
246                 if(!data_len) {
247                         logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
248                         return false;
249                 }
250
251                 packmsg_input_t in2 = {data, data_len};
252                 uint32_t version2 = packmsg_get_uint32(&in2);
253                 char *name2 = packmsg_get_str_dup(&in2);
254
255                 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
256                         free(name2);
257                         packmsg_input_invalidate(&in);
258                         break;
259                 }
260
261                 if(!check_id(name2)) {
262                         free(name2);
263                         break;
264                 }
265
266                 if(!strcmp(name2, mesh->name)) {
267                         logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
268                         free(name2);
269                         meshlink_errno = MESHLINK_EPEER;
270                         return false;
271                 }
272
273                 node_t *n = new_node();
274                 n->name = name2;
275
276                 config_t config = {data, data_len};
277
278                 if(!node_read_from_config(mesh, n, &config)) {
279                         free_node(n);
280                         logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
281                         meshlink_errno = MESHLINK_EPEER;
282                         return false;
283                 }
284
285                 if(i == 0) {
286                         /* The first host config file is of the inviter itself;
287                          * remember the address we are currently using for the invitation connection.
288                          */
289                         sockaddr_t sa;
290                         socklen_t salen = sizeof(sa);
291
292                         if(getpeername(state->sock, &sa.sa, &salen) == 0) {
293                                 node_add_recent_address(mesh, n, &sa);
294                         }
295                 }
296
297                 if(!node_write_config(mesh, n, true)) {
298                         free_node(n);
299                         return false;
300                 }
301
302                 node_add(mesh, n);
303         }
304
305         /* Ensure the configuration directory metadata is on disk */
306         if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
307                 return false;
308         }
309
310         if(!mesh->inviter_commits_first) {
311                 devtool_set_inviter_commits_first(false);
312         }
313
314         sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
315
316         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
317
318         return true;
319 }
320
321 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
322         (void)type;
323         join_state_t *state = handle;
324         const char *ptr = data;
325
326         while(len) {
327                 int result = send(state->sock, ptr, len, 0);
328
329                 if(result == -1 && errno == EINTR) {
330                         continue;
331                 } else if(result <= 0) {
332                         return false;
333                 }
334
335                 ptr += result;
336                 len -= result;
337         }
338
339         return true;
340 }
341
342 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
343         join_state_t *state = handle;
344         meshlink_handle_t *mesh = state->mesh;
345
346         if(mesh->inviter_commits_first) {
347                 switch(type) {
348                 case SPTPS_HANDSHAKE:
349                         return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
350
351                 case 1:
352                         break;
353
354                 case 0:
355                         if(!finalize_join(state, msg, len)) {
356                                 return false;
357                         }
358
359                         logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
360                         shutdown(state->sock, SHUT_RDWR);
361                         state->success = true;
362                         break;
363
364                 default:
365                         return false;
366                 }
367         } else {
368                 switch(type) {
369                 case SPTPS_HANDSHAKE:
370                         return sptps_send_record(&state->sptps, 0, state->cookie, 18);
371
372                 case 0:
373                         return finalize_join(state, msg, len);
374
375                 case 1:
376                         logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
377                         shutdown(state->sock, SHUT_RDWR);
378                         state->success = true;
379                         break;
380
381                 default:
382                         return false;
383                 }
384         }
385
386         return true;
387 }
388
389 static bool recvline(join_state_t *state) {
390         char *newline = NULL;
391
392         while(!(newline = memchr(state->buffer, '\n', state->blen))) {
393                 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
394
395                 if(result == -1 && errno == EINTR) {
396                         continue;
397                 } else if(result <= 0) {
398                         return false;
399                 }
400
401                 state->blen += result;
402         }
403
404         if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
405                 return false;
406         }
407
408         size_t len = newline - state->buffer;
409
410         memcpy(state->line, state->buffer, len);
411         state->line[len] = 0;
412         memmove(state->buffer, newline + 1, state->blen - len - 1);
413         state->blen -= len + 1;
414
415         return true;
416 }
417
418 static bool sendline(int fd, const char *format, ...) {
419         char buffer[4096];
420         char *p = buffer;
421         int blen = 0;
422         va_list ap;
423
424         va_start(ap, format);
425         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
426         va_end(ap);
427
428         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
429                 return false;
430         }
431
432         buffer[blen] = '\n';
433         blen++;
434
435         while(blen) {
436                 int result = send(fd, p, blen, MSG_NOSIGNAL);
437
438                 if(result == -1 && errno == EINTR) {
439                         continue;
440                 } else if(result <= 0) {
441                         return false;
442                 }
443
444                 p += result;
445                 blen -= result;
446         }
447
448         return true;
449 }
450
451 static const char *errstr[] = {
452         [MESHLINK_OK] = "No error",
453         [MESHLINK_EINVAL] = "Invalid argument",
454         [MESHLINK_ENOMEM] = "Out of memory",
455         [MESHLINK_ENOENT] = "No such node",
456         [MESHLINK_EEXIST] = "Node already exists",
457         [MESHLINK_EINTERNAL] = "Internal error",
458         [MESHLINK_ERESOLV] = "Could not resolve hostname",
459         [MESHLINK_ESTORAGE] = "Storage error",
460         [MESHLINK_ENETWORK] = "Network error",
461         [MESHLINK_EPEER] = "Error communicating with peer",
462         [MESHLINK_ENOTSUP] = "Operation not supported",
463         [MESHLINK_EBUSY] = "MeshLink instance already in use",
464         [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
465 };
466
467 const char *meshlink_strerror(meshlink_errno_t err) {
468         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
469                 return "Invalid error code";
470         }
471
472         return errstr[err];
473 }
474
475 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
476         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
477
478         mesh->private_key = ecdsa_generate();
479
480         if(!mesh->private_key) {
481                 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
482                 meshlink_errno = MESHLINK_EINTERNAL;
483                 return false;
484         }
485
486         logger(mesh, MESHLINK_DEBUG, "Done.\n");
487
488         return true;
489 }
490
491 static struct timespec idle(event_loop_t *loop, void *data) {
492         (void)loop;
493         meshlink_handle_t *mesh = data;
494
495         if(mesh->peer && mesh->peer->utcp) {
496                 return utcp_timeout(mesh->peer->utcp);
497         } else {
498                 return (struct timespec) {
499                         3600, 0
500                 };
501         }
502 }
503
504 static bool meshlink_setup(meshlink_handle_t *mesh) {
505         if(!config_destroy(mesh->confbase, "new")) {
506                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
507                 meshlink_errno = MESHLINK_ESTORAGE;
508                 return false;
509         }
510
511         if(!config_destroy(mesh->confbase, "old")) {
512                 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
513                 meshlink_errno = MESHLINK_ESTORAGE;
514                 return false;
515         }
516
517         if(!config_init(mesh, "current")) {
518                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
519                 meshlink_errno = MESHLINK_ESTORAGE;
520                 return false;
521         }
522
523         if(!ecdsa_keygen(mesh)) {
524                 meshlink_errno = MESHLINK_EINTERNAL;
525                 return false;
526         }
527
528         mesh->myport = xstrdup("0");
529
530         /* Create a node for ourself */
531
532         mesh->self = new_node();
533         mesh->self->name = xstrdup(mesh->name);
534         mesh->self->devclass = mesh->devclass;
535         mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
536         mesh->self->session_id = mesh->session_id;
537
538         if(!write_main_config_files(mesh)) {
539                 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
540                 meshlink_errno = MESHLINK_ESTORAGE;
541                 return false;
542         }
543
544         /* Ensure the configuration directory metadata is on disk */
545         if(!config_sync(mesh, "current")) {
546                 return false;
547         }
548
549         return true;
550 }
551
552 static bool meshlink_read_config(meshlink_handle_t *mesh) {
553         config_t config;
554
555         if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
556                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
557                 return false;
558         }
559
560         packmsg_input_t in = {config.buf, config.len};
561         const void *private_key;
562
563         uint32_t version = packmsg_get_uint32(&in);
564         char *name = packmsg_get_str_dup(&in);
565         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
566         packmsg_skip_element(&in); // Invitation key is not supported
567         uint16_t myport = packmsg_get_uint16(&in);
568
569         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
570                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
571                 free(name);
572                 config_free(&config);
573                 return false;
574         }
575
576         if(mesh->name && strcmp(mesh->name, name)) {
577                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
578                 meshlink_errno = MESHLINK_ESTORAGE;
579                 free(name);
580                 config_free(&config);
581                 return false;
582         }
583
584         free(mesh->name);
585         mesh->name = name;
586         xasprintf(&mesh->myport, "%u", myport);
587         mesh->private_key = ecdsa_set_private_key(private_key);
588         config_free(&config);
589
590         /* Create a node for ourself and read our host configuration file */
591
592         mesh->self = new_node();
593         mesh->self->name = xstrdup(name);
594         mesh->self->devclass = mesh->devclass;
595         mesh->self->session_id = mesh->session_id;
596
597         if(!node_read_public_key(mesh, mesh->self)) {
598                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
599                 meshlink_errno = MESHLINK_ESTORAGE;
600                 free_node(mesh->self);
601                 mesh->self = NULL;
602                 return false;
603         }
604
605         return true;
606 }
607
608 #ifdef HAVE_SETNS
609 static void *setup_network_in_netns_thread(void *arg) {
610         meshlink_handle_t *mesh = arg;
611
612         if(setns(mesh->netns, CLONE_NEWNET) != 0) {
613                 return NULL;
614         }
615
616         bool success = setup_network(mesh);
617         return success ? arg : NULL;
618 }
619 #endif // HAVE_SETNS
620
621 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
622         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
623
624         if(!confbase || !*confbase) {
625                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
626                 meshlink_errno = MESHLINK_EINVAL;
627                 return NULL;
628         }
629
630         if(!appname || !*appname) {
631                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
632                 meshlink_errno = MESHLINK_EINVAL;
633                 return NULL;
634         }
635
636         if(strchr(appname, ' ')) {
637                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
638                 meshlink_errno = MESHLINK_EINVAL;
639                 return NULL;
640         }
641
642         if(name && !check_id(name)) {
643                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
644                 meshlink_errno = MESHLINK_EINVAL;
645                 return NULL;
646         }
647
648         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
649                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
650                 meshlink_errno = MESHLINK_EINVAL;
651                 return NULL;
652         }
653
654         meshlink_open_params_t *params = xzalloc(sizeof * params);
655
656         params->confbase = xstrdup(confbase);
657         params->name = name ? xstrdup(name) : NULL;
658         params->appname = xstrdup(appname);
659         params->devclass = devclass;
660         params->netns = -1;
661
662         xasprintf(&params->lock_filename, "%s" SLASH "meshlink.lock", confbase);
663
664         return params;
665 }
666
667 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
668         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
669
670         if(!params) {
671                 meshlink_errno = MESHLINK_EINVAL;
672                 return false;
673         }
674
675         params->netns = netns;
676
677         return true;
678 }
679
680 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
681         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
682
683         if(!params) {
684                 meshlink_errno = MESHLINK_EINVAL;
685                 return false;
686         }
687
688         if((!key && keylen) || (key && !keylen)) {
689                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
690                 meshlink_errno = MESHLINK_EINVAL;
691                 return false;
692         }
693
694         params->key = key;
695         params->keylen = keylen;
696
697         return true;
698 }
699
700 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
701         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
702
703         if(!params) {
704                 meshlink_errno = MESHLINK_EINVAL;
705                 return false;
706         }
707
708         params->storage_policy = policy;
709
710         return true;
711 }
712
713 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
714         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
715
716         if(!params || !filename) {
717                 meshlink_errno = MESHLINK_EINVAL;
718                 return false;
719         }
720
721         free(params->lock_filename);
722         params->lock_filename = xstrdup(filename);
723
724         return true;
725 }
726
727 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
728         logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
729
730         if(!mesh || !new_key || !new_keylen) {
731                 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
732                 meshlink_errno = MESHLINK_EINVAL;
733                 return false;
734         }
735
736         if(pthread_mutex_lock(&mesh->mutex) != 0) {
737                 abort();
738         }
739
740         // Create hash for the new key
741         void *new_config_key;
742         new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
743
744         if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
745                 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
746                 meshlink_errno = MESHLINK_EINTERNAL;
747                 pthread_mutex_unlock(&mesh->mutex);
748                 return false;
749         }
750
751         // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
752
753         if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
754                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
755                 meshlink_errno = MESHLINK_ESTORAGE;
756                 pthread_mutex_unlock(&mesh->mutex);
757                 return false;
758         }
759
760         devtool_keyrotate_probe(1);
761
762         // Rename confbase/current/ to confbase/old
763
764         if(!config_rename(mesh, "current", "old")) {
765                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
766                 meshlink_errno = MESHLINK_ESTORAGE;
767                 pthread_mutex_unlock(&mesh->mutex);
768                 return false;
769         }
770
771         devtool_keyrotate_probe(2);
772
773         // Rename confbase/new/ to confbase/current
774
775         if(!config_rename(mesh, "new", "current")) {
776                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
777                 meshlink_errno = MESHLINK_ESTORAGE;
778                 pthread_mutex_unlock(&mesh->mutex);
779                 return false;
780         }
781
782         devtool_keyrotate_probe(3);
783
784         // Cleanup the "old" confbase sub-directory
785
786         if(!config_destroy(mesh->confbase, "old")) {
787                 pthread_mutex_unlock(&mesh->mutex);
788                 return false;
789         }
790
791         // Change the mesh handle key with new key
792
793         free(mesh->config_key);
794         mesh->config_key = new_config_key;
795
796         pthread_mutex_unlock(&mesh->mutex);
797
798         return true;
799 }
800
801 void meshlink_open_params_free(meshlink_open_params_t *params) {
802         logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
803
804         if(!params) {
805                 meshlink_errno = MESHLINK_EINVAL;
806                 return;
807         }
808
809         free(params->confbase);
810         free(params->name);
811         free(params->appname);
812         free(params->lock_filename);
813
814         free(params);
815 }
816
817 /// Device class traits
818 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
819         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
820         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
821         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 },     // DEV_CLASS_PORTABLE
822         { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 },     // DEV_CLASS_UNKNOWN
823 };
824
825 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
826         logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
827
828         if(!confbase || !*confbase) {
829                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
830                 meshlink_errno = MESHLINK_EINVAL;
831                 return NULL;
832         }
833
834         char lock_filename[PATH_MAX];
835         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
836
837         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
838         meshlink_open_params_t params = {
839                 .confbase = (char *)confbase,
840                 .lock_filename = lock_filename,
841                 .name = (char *)name,
842                 .appname = (char *)appname,
843                 .devclass = devclass,
844                 .netns = -1,
845         };
846
847         return meshlink_open_ex(&params);
848 }
849
850 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) {
851         logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
852
853         if(!confbase || !*confbase) {
854                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
855                 meshlink_errno = MESHLINK_EINVAL;
856                 return NULL;
857         }
858
859         char lock_filename[PATH_MAX];
860         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
861
862         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
863         meshlink_open_params_t params = {
864                 .confbase = (char *)confbase,
865                 .lock_filename = lock_filename,
866                 .name = (char *)name,
867                 .appname = (char *)appname,
868                 .devclass = devclass,
869                 .netns = -1,
870         };
871
872         if(!meshlink_open_params_set_storage_key(&params, key, keylen)) {
873                 return false;
874         }
875
876         return meshlink_open_ex(&params);
877 }
878
879 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
880         logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
881
882         if(!name) {
883                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
884                 meshlink_errno = MESHLINK_EINVAL;
885                 return NULL;
886         }
887
888         if(!check_id(name)) {
889                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
890                 meshlink_errno = MESHLINK_EINVAL;
891                 return NULL;
892         }
893
894         if(!appname || !*appname) {
895                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
896                 meshlink_errno = MESHLINK_EINVAL;
897                 return NULL;
898         }
899
900         if(strchr(appname, ' ')) {
901                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
902                 meshlink_errno = MESHLINK_EINVAL;
903                 return NULL;
904         }
905
906         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
907                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
908                 meshlink_errno = MESHLINK_EINVAL;
909                 return NULL;
910         }
911
912         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
913         meshlink_open_params_t params = {
914                 .name = (char *)name,
915                 .appname = (char *)appname,
916                 .devclass = devclass,
917                 .netns = -1,
918         };
919
920         return meshlink_open_ex(&params);
921 }
922
923 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
924         logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
925
926         // Validate arguments provided by the application
927         if(!params->appname || !*params->appname) {
928                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
929                 meshlink_errno = MESHLINK_EINVAL;
930                 return NULL;
931         }
932
933         if(strchr(params->appname, ' ')) {
934                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
935                 meshlink_errno = MESHLINK_EINVAL;
936                 return NULL;
937         }
938
939         if(params->name && !check_id(params->name)) {
940                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
941                 meshlink_errno = MESHLINK_EINVAL;
942                 return NULL;
943         }
944
945         if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
946                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
947                 meshlink_errno = MESHLINK_EINVAL;
948                 return NULL;
949         }
950
951         if((params->key && !params->keylen) || (!params->key && params->keylen)) {
952                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
953                 meshlink_errno = MESHLINK_EINVAL;
954                 return NULL;
955         }
956
957         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
958
959         if(params->confbase) {
960                 mesh->confbase = xstrdup(params->confbase);
961         }
962
963         mesh->appname = xstrdup(params->appname);
964         mesh->devclass = params->devclass;
965         mesh->netns = params->netns;
966         mesh->log_cb = global_log_cb;
967         mesh->log_level = global_log_level;
968         mesh->packet = xmalloc(sizeof(vpn_packet_t));
969
970         randomize(&mesh->prng_state, sizeof(mesh->prng_state));
971
972         do {
973                 randomize(&mesh->session_id, sizeof(mesh->session_id));
974         } while(mesh->session_id == 0);
975
976         memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
977
978         mesh->name = params->name ? xstrdup(params->name) : NULL;
979
980         // Hash the key
981         if(params->key) {
982                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
983
984                 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
985                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
986                         meshlink_close(mesh);
987                         meshlink_errno = MESHLINK_EINTERNAL;
988                         return NULL;
989                 }
990         }
991
992         // initialize mutexes and conds
993         pthread_mutexattr_t attr;
994         pthread_mutexattr_init(&attr);
995
996         if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
997                 abort();
998         }
999
1000         pthread_mutex_init(&mesh->mutex, &attr);
1001         pthread_cond_init(&mesh->cond, NULL);
1002
1003         mesh->threadstarted = false;
1004         event_loop_init(&mesh->loop);
1005         mesh->loop.data = mesh;
1006
1007         meshlink_queue_init(&mesh->outpacketqueue);
1008
1009         // Atomically lock the configuration directory.
1010         if(!main_config_lock(mesh, params->lock_filename)) {
1011                 meshlink_close(mesh);
1012                 return NULL;
1013         }
1014
1015         // If no configuration exists yet, create it.
1016
1017         bool new_configuration = false;
1018
1019         if(!meshlink_confbase_exists(mesh)) {
1020                 if(!mesh->name) {
1021                         logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1022                         meshlink_close(mesh);
1023                         meshlink_errno = MESHLINK_ESTORAGE;
1024                         return NULL;
1025                 }
1026
1027                 if(!meshlink_setup(mesh)) {
1028                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1029                         meshlink_close(mesh);
1030                         return NULL;
1031                 }
1032
1033                 new_configuration = true;
1034         } else {
1035                 if(!meshlink_read_config(mesh)) {
1036                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1037                         meshlink_close(mesh);
1038                         return NULL;
1039                 }
1040         }
1041
1042         mesh->storage_policy = params->storage_policy;
1043
1044 #ifdef HAVE_MINGW
1045         struct WSAData wsa_state;
1046         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1047 #endif
1048
1049         // Setup up everything
1050         // TODO: we should not open listening sockets yet
1051
1052         bool success = false;
1053
1054         if(mesh->netns != -1) {
1055 #ifdef HAVE_SETNS
1056                 pthread_t thr;
1057
1058                 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1059                         void *retval = NULL;
1060                         success = pthread_join(thr, &retval) == 0 && retval;
1061                 }
1062
1063 #else
1064                 meshlink_errno = MESHLINK_EINTERNAL;
1065                 return NULL;
1066
1067 #endif // HAVE_SETNS
1068         } else {
1069                 success = setup_network(mesh);
1070         }
1071
1072         if(!success) {
1073                 meshlink_close(mesh);
1074                 meshlink_errno = MESHLINK_ENETWORK;
1075                 return NULL;
1076         }
1077
1078         if(!node_write_config(mesh, mesh->self, new_configuration)) {
1079                 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1080                 return NULL;
1081         }
1082
1083         idle_set(&mesh->loop, idle, mesh);
1084
1085         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1086         return mesh;
1087 }
1088
1089 static void *meshlink_main_loop(void *arg) {
1090         meshlink_handle_t *mesh = arg;
1091
1092         if(mesh->netns != -1) {
1093 #ifdef HAVE_SETNS
1094
1095                 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1096                         pthread_cond_signal(&mesh->cond);
1097                         return NULL;
1098                 }
1099
1100 #else
1101                 pthread_cond_signal(&mesh->cond);
1102                 return NULL;
1103 #endif // HAVE_SETNS
1104         }
1105
1106         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1107                 abort();
1108         }
1109
1110         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1111         pthread_cond_broadcast(&mesh->cond);
1112         main_loop(mesh);
1113         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1114
1115         pthread_mutex_unlock(&mesh->mutex);
1116
1117         return NULL;
1118 }
1119
1120 bool meshlink_start(meshlink_handle_t *mesh) {
1121         if(!mesh) {
1122                 meshlink_errno = MESHLINK_EINVAL;
1123                 return false;
1124         }
1125
1126         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1127
1128         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1129                 abort();
1130         }
1131
1132         assert(mesh->self);
1133         assert(mesh->private_key);
1134         assert(mesh->self->ecdsa);
1135         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1136
1137         if(mesh->threadstarted) {
1138                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1139                 pthread_mutex_unlock(&mesh->mutex);
1140                 return true;
1141         }
1142
1143         // Reset node connection timers
1144         if(mesh->peer) {
1145                 mesh->peer->last_connect_try = 0;
1146         }
1147
1148         //Check that a valid name is set
1149         if(!mesh->name) {
1150                 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1151                 meshlink_errno = MESHLINK_EINVAL;
1152                 pthread_mutex_unlock(&mesh->mutex);
1153                 return false;
1154         }
1155
1156         init_outgoings(mesh);
1157
1158         // Start the main thread
1159
1160         event_loop_start(&mesh->loop);
1161
1162         // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1163         pthread_attr_t attr;
1164         pthread_attr_init(&attr);
1165         pthread_attr_setstacksize(&attr, 1024 * 1024);
1166
1167         if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1168                 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1169                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1170                 meshlink_errno = MESHLINK_EINTERNAL;
1171                 event_loop_stop(&mesh->loop);
1172                 pthread_mutex_unlock(&mesh->mutex);
1173                 return false;
1174         }
1175
1176         pthread_cond_wait(&mesh->cond, &mesh->mutex);
1177         mesh->threadstarted = true;
1178
1179         pthread_mutex_unlock(&mesh->mutex);
1180         return true;
1181 }
1182
1183 void meshlink_stop(meshlink_handle_t *mesh) {
1184         logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1185
1186         if(!mesh) {
1187                 meshlink_errno = MESHLINK_EINVAL;
1188                 return;
1189         }
1190
1191         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1192                 abort();
1193         }
1194
1195         // Shut down the main thread
1196         event_loop_stop(&mesh->loop);
1197
1198         // TODO: send something to a local socket to kick the event loop
1199
1200         if(mesh->threadstarted) {
1201                 // Wait for the main thread to finish
1202                 pthread_mutex_unlock(&mesh->mutex);
1203
1204                 if(pthread_join(mesh->thread, NULL) != 0) {
1205                         abort();
1206                 }
1207
1208                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1209                         abort();
1210                 }
1211
1212                 mesh->threadstarted = false;
1213         }
1214
1215         // Close all metaconnections
1216         if(mesh->connection) {
1217                 mesh->connection->outgoing = NULL;
1218                 terminate_connection(mesh, mesh->connection, false);
1219         }
1220
1221         exit_outgoings(mesh);
1222
1223         // Try to write out any changed node config files, ignore errors at this point.
1224         if(mesh->peer && mesh->peer->status.dirty) {
1225                 if(!node_write_config(mesh, mesh->peer, false)) {
1226                         // ignore
1227                 }
1228         }
1229
1230         pthread_mutex_unlock(&mesh->mutex);
1231 }
1232
1233 void meshlink_close(meshlink_handle_t *mesh) {
1234         logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1235
1236         if(!mesh) {
1237                 meshlink_errno = MESHLINK_EINVAL;
1238                 return;
1239         }
1240
1241         // stop can be called even if mesh has not been started
1242         meshlink_stop(mesh);
1243
1244         // lock is not released after this
1245         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1246                 abort();
1247         }
1248
1249         // Close and free all resources used.
1250
1251         close_network_connections(mesh);
1252
1253         logger(mesh, MESHLINK_INFO, "Terminating");
1254
1255         event_loop_exit(&mesh->loop);
1256
1257 #ifdef HAVE_MINGW
1258
1259         if(mesh->confbase) {
1260                 WSACleanup();
1261         }
1262
1263 #endif
1264
1265         if(mesh->netns != -1) {
1266                 close(mesh->netns);
1267         }
1268
1269         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1270                 free(packet);
1271         }
1272
1273         meshlink_queue_exit(&mesh->outpacketqueue);
1274
1275         free(mesh->name);
1276         free(mesh->appname);
1277         free(mesh->confbase);
1278         free(mesh->config_key);
1279         free(mesh->external_address_url);
1280         free(mesh->packet);
1281         ecdsa_free(mesh->private_key);
1282
1283         main_config_unlock(mesh);
1284
1285         pthread_mutex_unlock(&mesh->mutex);
1286         pthread_mutex_destroy(&mesh->mutex);
1287
1288         memset(mesh, 0, sizeof(*mesh));
1289
1290         free(mesh);
1291 }
1292
1293 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1294         logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1295
1296         if(!params) {
1297                 meshlink_errno = MESHLINK_EINVAL;
1298                 return false;
1299         }
1300
1301         if(!params->confbase) {
1302                 /* Ephemeral instances */
1303                 return true;
1304         }
1305
1306         /* Exit early if the confbase directory itself doesn't exist */
1307         if(access(params->confbase, F_OK) && errno == ENOENT) {
1308                 return true;
1309         }
1310
1311         /* Take the lock the same way meshlink_open() would. */
1312         FILE *lockfile = fopen(params->lock_filename, "w+");
1313
1314         if(!lockfile) {
1315                 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1316                 meshlink_errno = MESHLINK_ESTORAGE;
1317                 return false;
1318         }
1319
1320 #ifdef FD_CLOEXEC
1321         fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1322 #endif
1323
1324 #ifdef HAVE_MINGW
1325         // TODO: use _locking()?
1326 #else
1327
1328         if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1329                 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1330                 fclose(lockfile);
1331                 meshlink_errno = MESHLINK_EBUSY;
1332                 return false;
1333         }
1334
1335 #endif
1336
1337         if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1338                 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1339                 return false;
1340         }
1341
1342         if(unlink(params->lock_filename)) {
1343                 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1344                 fclose(lockfile);
1345                 meshlink_errno = MESHLINK_ESTORAGE;
1346                 return false;
1347         }
1348
1349         fclose(lockfile);
1350
1351         if(!sync_path(params->confbase)) {
1352                 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1353                 meshlink_errno = MESHLINK_ESTORAGE;
1354                 return false;
1355         }
1356
1357         return true;
1358 }
1359
1360 bool meshlink_destroy(const char *confbase) {
1361         logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1362
1363         char lock_filename[PATH_MAX];
1364         snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1365
1366         meshlink_open_params_t params = {
1367                 .confbase = (char *)confbase,
1368                 .lock_filename = lock_filename,
1369         };
1370
1371         return meshlink_destroy_ex(&params);
1372 }
1373
1374 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1375         logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1376
1377         if(!mesh) {
1378                 meshlink_errno = MESHLINK_EINVAL;
1379                 return;
1380         }
1381
1382         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1383                 abort();
1384         }
1385
1386         mesh->receive_cb = cb;
1387         pthread_mutex_unlock(&mesh->mutex);
1388 }
1389
1390 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1391         logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1392
1393         if(!mesh) {
1394                 meshlink_errno = MESHLINK_EINVAL;
1395                 return;
1396         }
1397
1398         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1399                 abort();
1400         }
1401
1402         mesh->connection_try_cb = cb;
1403         pthread_mutex_unlock(&mesh->mutex);
1404 }
1405
1406 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1407         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1408
1409         if(!mesh) {
1410                 meshlink_errno = MESHLINK_EINVAL;
1411                 return;
1412         }
1413
1414         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1415                 abort();
1416         }
1417
1418         mesh->node_status_cb = cb;
1419         pthread_mutex_unlock(&mesh->mutex);
1420 }
1421
1422 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1423         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
1424
1425         if(!mesh) {
1426                 meshlink_errno = MESHLINK_EINVAL;
1427                 return;
1428         }
1429
1430         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1431                 abort();
1432         }
1433
1434         mesh->node_pmtu_cb = cb;
1435         pthread_mutex_unlock(&mesh->mutex);
1436 }
1437
1438 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1439         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1440
1441         if(!mesh) {
1442                 meshlink_errno = MESHLINK_EINVAL;
1443                 return;
1444         }
1445
1446         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1447                 abort();
1448         }
1449
1450         mesh->node_duplicate_cb = cb;
1451         pthread_mutex_unlock(&mesh->mutex);
1452 }
1453
1454 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1455         logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1456
1457         if(mesh) {
1458                 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1459                         abort();
1460                 }
1461
1462                 mesh->log_cb = cb;
1463                 mesh->log_level = cb ? level : 0;
1464                 pthread_mutex_unlock(&mesh->mutex);
1465         } else {
1466                 global_log_cb = cb;
1467                 global_log_level = cb ? level : 0;
1468         }
1469 }
1470
1471 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1472         logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1473
1474         if(!mesh) {
1475                 meshlink_errno = MESHLINK_EINVAL;
1476                 return;
1477         }
1478
1479         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1480                 abort();
1481         }
1482
1483         mesh->error_cb = cb;
1484         pthread_mutex_unlock(&mesh->mutex);
1485 }
1486
1487 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1488         meshlink_packethdr_t *hdr;
1489
1490         if(len > MAXSIZE - sizeof(*hdr)) {
1491                 meshlink_errno = MESHLINK_EINVAL;
1492                 return false;
1493         }
1494
1495         node_t *n = (node_t *)destination;
1496
1497         if(n->status.blacklisted) {
1498                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1499                 meshlink_errno = MESHLINK_EBLACKLISTED;
1500                 return false;
1501         }
1502
1503         // Prepare the packet
1504         packet->probe = false;
1505         packet->tcp = false;
1506         packet->len = len + sizeof(*hdr);
1507
1508         hdr = (meshlink_packethdr_t *)packet->data;
1509         memset(hdr, 0, sizeof(*hdr));
1510         // leave the last byte as 0 to make sure strings are always
1511         // null-terminated if they are longer than the buffer
1512         strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
1513         strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
1514
1515         memcpy(packet->data + sizeof(*hdr), data, len);
1516
1517         return true;
1518 }
1519
1520 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1521         assert(mesh);
1522         assert(destination);
1523         assert(data);
1524         assert(len);
1525
1526         // Prepare the packet
1527         if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
1528                 return false;
1529         }
1530
1531         // Send it immediately
1532         route(mesh, mesh->self, mesh->packet);
1533
1534         return true;
1535 }
1536
1537 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1538         logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
1539
1540         // Validate arguments
1541         if(!mesh || !destination) {
1542                 meshlink_errno = MESHLINK_EINVAL;
1543                 return false;
1544         }
1545
1546         if(!len) {
1547                 return true;
1548         }
1549
1550         if(!data) {
1551                 meshlink_errno = MESHLINK_EINVAL;
1552                 return false;
1553         }
1554
1555         // Prepare the packet
1556         vpn_packet_t *packet = malloc(sizeof(*packet));
1557
1558         if(!packet) {
1559                 meshlink_errno = MESHLINK_ENOMEM;
1560                 return false;
1561         }
1562
1563         if(!prepare_packet(mesh, destination, data, len, packet)) {
1564                 free(packet);
1565                 return false;
1566         }
1567
1568         // Queue it
1569         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1570                 free(packet);
1571                 meshlink_errno = MESHLINK_ENOMEM;
1572                 return false;
1573         }
1574
1575         logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
1576
1577         // Notify event loop
1578         signal_trigger(&mesh->loop, &mesh->datafromapp);
1579
1580         return true;
1581 }
1582
1583 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1584         (void)loop;
1585         meshlink_handle_t *mesh = data;
1586
1587         logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
1588
1589         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1590                 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
1591                 mesh->self->in_packets++;
1592                 mesh->self->in_bytes += packet->len;
1593                 route(mesh, mesh->self, packet);
1594                 free(packet);
1595         }
1596 }
1597
1598 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1599         if(!mesh || !destination) {
1600                 meshlink_errno = MESHLINK_EINVAL;
1601                 return -1;
1602         }
1603
1604         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1605                 abort();
1606         }
1607
1608         node_t *n = (node_t *)destination;
1609
1610         if(!n->status.reachable) {
1611                 pthread_mutex_unlock(&mesh->mutex);
1612                 return 0;
1613
1614         } else if(n->mtuprobes > 30 && n->minmtu) {
1615                 pthread_mutex_unlock(&mesh->mutex);
1616                 return n->minmtu;
1617         } else {
1618                 pthread_mutex_unlock(&mesh->mutex);
1619                 return MTU;
1620         }
1621 }
1622
1623 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1624         if(!mesh || !node) {
1625                 meshlink_errno = MESHLINK_EINVAL;
1626                 return NULL;
1627         }
1628
1629         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1630                 abort();
1631         }
1632
1633         node_t *n = (node_t *)node;
1634
1635         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1636                 meshlink_errno = MESHLINK_EINTERNAL;
1637                 pthread_mutex_unlock(&mesh->mutex);
1638                 return false;
1639         }
1640
1641         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1642
1643         if(!fingerprint) {
1644                 meshlink_errno = MESHLINK_EINTERNAL;
1645         }
1646
1647         pthread_mutex_unlock(&mesh->mutex);
1648         return fingerprint;
1649 }
1650
1651 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1652         if(!mesh) {
1653                 meshlink_errno = MESHLINK_EINVAL;
1654                 return NULL;
1655         }
1656
1657         return (meshlink_node_t *)mesh->self;
1658 }
1659
1660 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1661         if(!mesh || !name) {
1662                 meshlink_errno = MESHLINK_EINVAL;
1663                 return NULL;
1664         }
1665
1666         node_t *n = NULL;
1667
1668         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1669                 abort();
1670         }
1671
1672         n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1673         pthread_mutex_unlock(&mesh->mutex);
1674
1675         if(!n) {
1676                 meshlink_errno = MESHLINK_ENOENT;
1677         }
1678
1679         return (meshlink_node_t *)n;
1680 }
1681
1682 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1683         logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
1684
1685         if(!mesh || !data || !len || !signature || !siglen) {
1686                 meshlink_errno = MESHLINK_EINVAL;
1687                 return false;
1688         }
1689
1690         if(*siglen < MESHLINK_SIGLEN) {
1691                 meshlink_errno = MESHLINK_EINVAL;
1692                 return false;
1693         }
1694
1695         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1696                 abort();
1697         }
1698
1699         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1700                 meshlink_errno = MESHLINK_EINTERNAL;
1701                 pthread_mutex_unlock(&mesh->mutex);
1702                 return false;
1703         }
1704
1705         *siglen = MESHLINK_SIGLEN;
1706         pthread_mutex_unlock(&mesh->mutex);
1707         return true;
1708 }
1709
1710 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1711         logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
1712
1713         if(!mesh || !source || !data || !len || !signature) {
1714                 meshlink_errno = MESHLINK_EINVAL;
1715                 return false;
1716         }
1717
1718         if(siglen != MESHLINK_SIGLEN) {
1719                 meshlink_errno = MESHLINK_EINVAL;
1720                 return false;
1721         }
1722
1723         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1724                 abort();
1725         }
1726
1727         bool rval = false;
1728
1729         struct node_t *n = (struct node_t *)source;
1730
1731         if(!node_read_public_key(mesh, n)) {
1732                 meshlink_errno = MESHLINK_EINTERNAL;
1733                 rval = false;
1734         } else {
1735                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1736         }
1737
1738         pthread_mutex_unlock(&mesh->mutex);
1739         return rval;
1740 }
1741
1742 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1743         logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
1744
1745         if(!mesh || !node || !address) {
1746                 meshlink_errno = MESHLINK_EINVAL;
1747                 return false;
1748         }
1749
1750         if(!is_valid_hostname(address)) {
1751                 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
1752                 meshlink_errno = MESHLINK_EINVAL;
1753                 return false;
1754         }
1755
1756         if((node_t *)node != mesh->self && !port) {
1757                 logger(mesh, MESHLINK_ERROR, "Missing port number!");
1758                 meshlink_errno = MESHLINK_EINVAL;
1759                 return false;
1760
1761         }
1762
1763         if(port && !is_valid_port(port)) {
1764                 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
1765                 meshlink_errno = MESHLINK_EINVAL;
1766                 return false;
1767         }
1768
1769         char *canonical_address;
1770
1771         xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
1772
1773         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1774                 abort();
1775         }
1776
1777         node_t *n = (node_t *)node;
1778         free(n->canonical_address);
1779         n->canonical_address = canonical_address;
1780
1781         if(!node_write_config(mesh, n, false)) {
1782                 pthread_mutex_unlock(&mesh->mutex);
1783                 return false;
1784         }
1785
1786         pthread_mutex_unlock(&mesh->mutex);
1787
1788         return config_sync(mesh, "current");
1789 }
1790
1791 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
1792         logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
1793
1794         if(!mesh || !node) {
1795                 meshlink_errno = MESHLINK_EINVAL;
1796                 return false;
1797         }
1798
1799         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1800                 abort();
1801         }
1802
1803         node_t *n = (node_t *)node;
1804         free(n->canonical_address);
1805         n->canonical_address = NULL;
1806
1807         if(!node_write_config(mesh, n, false)) {
1808                 pthread_mutex_unlock(&mesh->mutex);
1809                 return false;
1810         }
1811
1812         pthread_mutex_unlock(&mesh->mutex);
1813
1814         return config_sync(mesh, "current");
1815 }
1816
1817 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1818         logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
1819
1820         if(!mesh || !invitation) {
1821                 meshlink_errno = MESHLINK_EINVAL;
1822                 return false;
1823         }
1824
1825         if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
1826                 meshlink_errno = MESHLINK_EINVAL;
1827                 return false;
1828         }
1829
1830         join_state_t state = {
1831                 .mesh = mesh,
1832                 .sock = -1,
1833         };
1834
1835         ecdsa_t *key = NULL;
1836         ecdsa_t *hiskey = NULL;
1837
1838         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1839         char copy[strlen(invitation) + 1];
1840
1841         if(pthread_mutex_lock(&mesh->mutex) != 0) {
1842                 abort();
1843         }
1844
1845         //Before doing meshlink_join make sure we are not connected to another mesh
1846         if(mesh->threadstarted) {
1847                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
1848                 meshlink_errno = MESHLINK_EINVAL;
1849                 goto exit;
1850         }
1851
1852         // 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.
1853         if(mesh->peer) {
1854                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
1855                 meshlink_errno = MESHLINK_EINVAL;
1856                 goto exit;
1857         }
1858
1859         strcpy(copy, invitation);
1860
1861         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1862
1863         char *slash = strchr(copy, '/');
1864
1865         if(!slash) {
1866                 goto invalid;
1867         }
1868
1869         *slash++ = 0;
1870
1871         if(strlen(slash) != 48) {
1872                 goto invalid;
1873         }
1874
1875         char *address = copy;
1876         char *port = NULL;
1877
1878         if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
1879                 goto invalid;
1880         }
1881
1882         if(mesh->inviter_commits_first) {
1883                 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
1884         }
1885
1886         // Generate a throw-away key for the invitation.
1887         key = ecdsa_generate();
1888
1889         if(!key) {
1890                 meshlink_errno = MESHLINK_EINTERNAL;
1891                 goto exit;
1892         }
1893
1894         char *b64key = ecdsa_get_base64_public_key(key);
1895         char *comma;
1896
1897         while(address && *address) {
1898                 // We allow commas in the address part to support multiple addresses in one invitation URL.
1899                 comma = strchr(address, ',');
1900
1901                 if(comma) {
1902                         *comma++ = 0;
1903                 }
1904
1905                 // Split of the port
1906                 port = strrchr(address, ':');
1907
1908                 if(!port) {
1909                         goto invalid;
1910                 }
1911
1912                 *port++ = 0;
1913
1914                 // IPv6 address are enclosed in brackets, per RFC 3986
1915                 if(*address == '[') {
1916                         address++;
1917                         char *bracket = strchr(address, ']');
1918
1919                         if(!bracket) {
1920                                 goto invalid;
1921                         }
1922
1923                         *bracket++ = 0;
1924
1925                         if(*bracket) {
1926                                 goto invalid;
1927                         }
1928                 }
1929
1930                 // Connect to the meshlink daemon mentioned in the URL.
1931                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1932
1933                 if(ai) {
1934                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1935                                 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
1936
1937                                 if(state.sock == -1) {
1938                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1939                                         meshlink_errno = MESHLINK_ENETWORK;
1940                                         continue;
1941                                 }
1942
1943 #ifdef SO_NOSIGPIPE
1944                                 int nosigpipe = 1;
1945                                 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
1946 #endif
1947
1948                                 set_timeout(state.sock, 5000);
1949
1950                                 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
1951                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1952                                         meshlink_errno = MESHLINK_ENETWORK;
1953                                         closesocket(state.sock);
1954                                         state.sock = -1;
1955                                         continue;
1956                                 }
1957
1958                                 break;
1959                         }
1960
1961                         freeaddrinfo(ai);
1962                 } else {
1963                         meshlink_errno = MESHLINK_ERESOLV;
1964                 }
1965
1966                 if(state.sock != -1 || !comma) {
1967                         break;
1968                 }
1969
1970                 address = comma;
1971         }
1972
1973         if(state.sock == -1) {
1974                 goto exit;
1975         }
1976
1977         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1978
1979         // Tell him we have an invitation, and give him our throw-away key.
1980
1981         state.blen = 0;
1982
1983         if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
1984                 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1985                 meshlink_errno = MESHLINK_ENETWORK;
1986                 goto exit;
1987         }
1988
1989         free(b64key);
1990
1991         char hisname[4096] = "";
1992         int code, hismajor, hisminor = 0;
1993
1994         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) {
1995                 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
1996                 meshlink_errno = MESHLINK_ENETWORK;
1997                 goto exit;
1998         }
1999
2000         // Check if the hash of the key he gave us matches the hash in the URL.
2001         char *fingerprint = state.line + 2;
2002         char hishash[64];
2003
2004         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2005                 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
2006                 meshlink_errno = MESHLINK_EINTERNAL;
2007                 goto exit;
2008         }
2009
2010         if(memcmp(hishash, state.hash, 18)) {
2011                 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
2012                 meshlink_errno = MESHLINK_EPEER;
2013                 goto exit;
2014         }
2015
2016         hiskey = ecdsa_set_base64_public_key(fingerprint);
2017
2018         if(!hiskey) {
2019                 meshlink_errno = MESHLINK_EINTERNAL;
2020                 goto exit;
2021         }
2022
2023         // Start an SPTPS session
2024         if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2025                 meshlink_errno = MESHLINK_EINTERNAL;
2026                 goto exit;
2027         }
2028
2029         // Feed rest of input buffer to SPTPS
2030         if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2031                 meshlink_errno = MESHLINK_EPEER;
2032                 goto exit;
2033         }
2034
2035         ssize_t len;
2036         logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2037
2038         while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2039                 if(len < 0) {
2040                         if(errno == EINTR) {
2041                                 continue;
2042                         }
2043
2044                         logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2045                         meshlink_errno = MESHLINK_ENETWORK;
2046                         goto exit;
2047                 }
2048
2049                 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2050                         meshlink_errno = MESHLINK_EPEER;
2051                         goto exit;
2052                 }
2053         }
2054
2055         if(!state.success) {
2056                 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2057                 meshlink_errno = MESHLINK_EPEER;
2058                 goto exit;
2059         }
2060
2061         sptps_stop(&state.sptps);
2062         ecdsa_free(hiskey);
2063         ecdsa_free(key);
2064         closesocket(state.sock);
2065
2066         pthread_mutex_unlock(&mesh->mutex);
2067         return true;
2068
2069 invalid:
2070         logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2071         meshlink_errno = MESHLINK_EINVAL;
2072 exit:
2073         sptps_stop(&state.sptps);
2074         ecdsa_free(hiskey);
2075         ecdsa_free(key);
2076
2077         if(state.sock != -1) {
2078                 closesocket(state.sock);
2079         }
2080
2081         pthread_mutex_unlock(&mesh->mutex);
2082         return false;
2083 }
2084
2085 char *meshlink_export(meshlink_handle_t *mesh) {
2086         if(!mesh) {
2087                 meshlink_errno = MESHLINK_EINVAL;
2088                 return NULL;
2089         }
2090
2091         // Create a config file on the fly.
2092
2093         uint8_t buf[4096];
2094         packmsg_output_t out = {buf, sizeof(buf)};
2095         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2096         packmsg_add_str(&out, mesh->name);
2097         packmsg_add_str(&out, CORE_MESH);
2098
2099         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2100                 abort();
2101         }
2102
2103         packmsg_add_int32(&out, mesh->self->devclass);
2104         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2105         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2106
2107         if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2108                 char *canonical_address = NULL;
2109                 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
2110                 packmsg_add_str(&out, canonical_address);
2111                 free(canonical_address);
2112         } else {
2113                 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2114         }
2115
2116         uint32_t count = 0;
2117
2118         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2119                 if(mesh->self->recent[i].sa.sa_family) {
2120                         count++;
2121                 } else {
2122                         break;
2123                 }
2124         }
2125
2126         packmsg_add_array(&out, count);
2127
2128         for(uint32_t i = 0; i < count; i++) {
2129                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2130         }
2131
2132         packmsg_add_int64(&out, 0);
2133         packmsg_add_int64(&out, 0);
2134
2135         pthread_mutex_unlock(&mesh->mutex);
2136
2137         if(!packmsg_output_ok(&out)) {
2138                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2139                 meshlink_errno = MESHLINK_EINTERNAL;
2140                 return NULL;
2141         }
2142
2143         // Prepare a base64-encoded packmsg array containing our config file
2144
2145         uint32_t len = packmsg_output_size(&out, buf);
2146         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2147         uint8_t *buf2 = xmalloc(len2);
2148         packmsg_output_t out2 = {buf2, len2};
2149         packmsg_add_array(&out2, 1);
2150         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2151
2152         if(!packmsg_output_ok(&out2)) {
2153                 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
2154                 meshlink_errno = MESHLINK_EINTERNAL;
2155                 free(buf2);
2156                 return NULL;
2157         }
2158
2159         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2160
2161         return (char *)buf2;
2162 }
2163
2164 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2165         logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
2166
2167         if(!mesh || !data) {
2168                 meshlink_errno = MESHLINK_EINVAL;
2169                 return false;
2170         }
2171
2172         size_t datalen = strlen(data);
2173         uint8_t *buf = xmalloc(datalen);
2174         int buflen = b64decode(data, buf, datalen);
2175
2176         if(!buflen) {
2177                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2178                 free(buf);
2179                 meshlink_errno = MESHLINK_EPEER;
2180                 return false;
2181         }
2182
2183         packmsg_input_t in = {buf, buflen};
2184         uint32_t count = packmsg_get_array(&in);
2185
2186         if(!count) {
2187                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2188                 free(buf);
2189                 meshlink_errno = MESHLINK_EPEER;
2190                 return false;
2191         }
2192
2193         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2194                 abort();
2195         }
2196
2197         while(count--) {
2198                 const void *data2;
2199                 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
2200
2201                 if(!len2) {
2202                         break;
2203                 }
2204
2205                 packmsg_input_t in2 = {data2, len2};
2206                 uint32_t version = packmsg_get_uint32(&in2);
2207                 char *name = packmsg_get_str_dup(&in2);
2208
2209                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2210                         free(name);
2211                         packmsg_input_invalidate(&in);
2212                         break;
2213                 }
2214
2215                 if(!check_id(name)) {
2216                         free(name);
2217                         break;
2218                 }
2219
2220                 node_t *n = lookup_node(mesh, name);
2221
2222                 if(n) {
2223                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2224                         free(name);
2225                         continue;
2226                 }
2227
2228                 n = new_node();
2229                 n->name = name;
2230
2231                 config_t config = {data2, len2};
2232
2233                 if(!node_read_from_config(mesh, n, &config)) {
2234                         free_node(n);
2235                         packmsg_input_invalidate(&in);
2236                         break;
2237                 }
2238
2239                 if(!node_write_config(mesh, n, true)) {
2240                         free_node(n);
2241                         free(buf);
2242                         return false;
2243                 }
2244
2245                 node_add(mesh, n);
2246         }
2247
2248         pthread_mutex_unlock(&mesh->mutex);
2249
2250         free(buf);
2251
2252         if(!packmsg_done(&in)) {
2253                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2254                 meshlink_errno = MESHLINK_EPEER;
2255                 return false;
2256         }
2257
2258         if(!config_sync(mesh, "current")) {
2259                 return false;
2260         }
2261
2262         return true;
2263 }
2264
2265 /* Hint that a hostname may be found at an address
2266  * See header file for detailed comment.
2267  */
2268 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2269         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
2270
2271         if(!mesh || !node || !addr) {
2272                 meshlink_errno = EINVAL;
2273                 return;
2274         }
2275
2276         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2277                 abort();
2278         }
2279
2280         node_t *n = (node_t *)node;
2281
2282         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
2283                 if(!node_write_config(mesh, n, false)) {
2284                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
2285                 }
2286         }
2287
2288         pthread_mutex_unlock(&mesh->mutex);
2289         // @TODO do we want to fire off a connection attempt right away?
2290 }
2291
2292 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2293         (void)port;
2294         node_t *n = utcp->priv;
2295         meshlink_handle_t *mesh = n->mesh;
2296
2297         if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
2298                 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
2299         } else {
2300                 return mesh->channel_accept_cb;
2301         }
2302 }
2303
2304 /* Finish one AIO buffer, return true if the channel is still open. */
2305 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2306         meshlink_aio_buffer_t *aio = *head;
2307         *head = aio->next;
2308
2309         if(channel->c) {
2310                 channel->in_callback = true;
2311
2312                 if(aio->data) {
2313                         if(aio->cb.buffer) {
2314                                 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
2315                         }
2316                 } else {
2317                         if(aio->cb.fd) {
2318                                 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2319                         }
2320                 }
2321
2322                 channel->in_callback = false;
2323
2324                 if(!channel->c) {
2325                         free(aio);
2326                         free(channel);
2327                         return false;
2328                 }
2329         }
2330
2331         free(aio);
2332         return true;
2333 }
2334
2335 /* Finish all AIO buffers, return true if the channel is still open. */
2336 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
2337         while(*head) {
2338                 if(!aio_finish_one(mesh, channel, head)) {
2339                         return false;
2340                 }
2341         }
2342
2343         return true;
2344 }
2345
2346 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2347         meshlink_channel_t *channel = connection->priv;
2348
2349         if(!channel) {
2350                 abort();
2351         }
2352
2353         node_t *n = channel->node;
2354         meshlink_handle_t *mesh = n->mesh;
2355
2356         if(n->status.destroyed) {
2357                 meshlink_channel_close(mesh, channel);
2358                 return len;
2359         }
2360
2361         const char *p = data;
2362         size_t left = len;
2363
2364         while(channel->aio_receive) {
2365                 if(!len) {
2366                         /* This receive callback signalled an error, abort all outstanding AIO buffers. */
2367                         if(!aio_abort(mesh, channel, &channel->aio_receive)) {
2368                                 return len;
2369                         }
2370
2371                         break;
2372                 }
2373
2374                 meshlink_aio_buffer_t *aio = channel->aio_receive;
2375                 size_t todo = aio->len - aio->done;
2376
2377                 if(todo > left) {
2378                         todo = left;
2379                 }
2380
2381                 if(aio->data) {
2382                         memcpy((char *)aio->data + aio->done, p, todo);
2383                 } else {
2384                         ssize_t result = write(aio->fd, p, todo);
2385
2386                         if(result <= 0) {
2387                                 if(result < 0 && errno == EINTR) {
2388                                         continue;
2389                                 }
2390
2391                                 /* Writing to fd failed, cancel just this AIO buffer. */
2392                                 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
2393
2394                                 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2395                                         return len;
2396                                 }
2397
2398                                 continue;
2399                         }
2400
2401                         todo = result;
2402                 }
2403
2404                 aio->done += todo;
2405                 p += todo;
2406                 left -= todo;
2407
2408                 if(aio->done == aio->len) {
2409                         if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
2410                                 return len;
2411                         }
2412                 }
2413
2414                 if(!left) {
2415                         return len;
2416                 }
2417         }
2418
2419         if(channel->receive_cb) {
2420                 channel->receive_cb(mesh, channel, p, left);
2421         }
2422
2423         return len;
2424 }
2425
2426 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2427         node_t *n = utcp_connection->utcp->priv;
2428
2429         if(!n) {
2430                 abort();
2431         }
2432
2433         meshlink_handle_t *mesh = n->mesh;
2434
2435         if(!mesh->channel_accept_cb) {
2436                 return;
2437         }
2438
2439         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2440         channel->node = n;
2441         channel->c = utcp_connection;
2442
2443         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2444                 utcp_accept(utcp_connection, channel_recv, channel);
2445         } else {
2446                 free(channel);
2447         }
2448 }
2449
2450 static void channel_retransmit(struct utcp_connection *utcp_connection) {
2451         node_t *n = utcp_connection->utcp->priv;
2452         meshlink_handle_t *mesh = n->mesh;
2453
2454         if(n->mtuprobes == 31 && n->mtutimeout.cb) {
2455                 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
2456                         0, 0
2457                 });
2458         }
2459 }
2460
2461 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2462         node_t *n = utcp->priv;
2463
2464         if(n->status.destroyed) {
2465                 return -1;
2466         }
2467
2468         meshlink_handle_t *mesh = n->mesh;
2469         return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2470 }
2471
2472 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2473         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2474
2475         if(!mesh || !channel) {
2476                 meshlink_errno = MESHLINK_EINVAL;
2477                 return;
2478         }
2479
2480         channel->receive_cb = cb;
2481 }
2482
2483 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2484         (void)mesh;
2485         node_t *n = (node_t *)source;
2486
2487         if(!n->utcp) {
2488                 abort();
2489         }
2490
2491         utcp_recv(n->utcp, data, len);
2492 }
2493
2494 static void channel_poll(struct utcp_connection *connection, size_t len) {
2495         meshlink_channel_t *channel = connection->priv;
2496
2497         if(!channel) {
2498                 abort();
2499         }
2500
2501         node_t *n = channel->node;
2502         meshlink_handle_t *mesh = n->mesh;
2503
2504         while(channel->aio_send) {
2505                 if(!len) {
2506                         /* This poll callback signalled an error, abort all outstanding AIO buffers. */
2507                         if(!aio_abort(mesh, channel, &channel->aio_send)) {
2508                                 return;
2509                         }
2510
2511                         break;
2512                 }
2513
2514                 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
2515                 meshlink_aio_buffer_t *aio = channel->aio_send;
2516                 size_t todo = aio->len - aio->done;
2517                 ssize_t sent;
2518
2519                 if(todo > len) {
2520                         todo = len;
2521                 }
2522
2523                 if(aio->data) {
2524                         sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
2525                 } else {
2526                         /* Limit the amount we read at once to avoid stack overflows */
2527                         if(todo > 65536) {
2528                                 todo = 65536;
2529                         }
2530
2531                         char buf[todo];
2532                         ssize_t result = read(aio->fd, buf, todo);
2533
2534                         if(result > 0) {
2535                                 todo = result;
2536                                 sent = utcp_send(connection, buf, todo);
2537                         } else {
2538                                 if(result < 0 && errno == EINTR) {
2539                                         continue;
2540                                 }
2541
2542                                 /* Reading from fd failed, cancel just this AIO buffer. */
2543                                 if(result != 0) {
2544                                         logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
2545                                 }
2546
2547                                 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2548                                         return;
2549                                 }
2550
2551                                 continue;
2552                         }
2553                 }
2554
2555                 if(sent != (ssize_t)todo) {
2556                         /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
2557                         if(!aio_abort(mesh, channel, &channel->aio_send)) {
2558                                 return;
2559                         }
2560
2561                         len = 0;
2562                         break;
2563                 }
2564
2565                 aio->done += sent;
2566                 len -= sent;
2567
2568                 /* If we didn't finish this buffer, exit early. */
2569                 if(aio->done < aio->len) {
2570                         return;
2571                 }
2572
2573                 /* Signal completion of this buffer, and go to the next one. */
2574                 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
2575                         return;
2576                 }
2577
2578                 if(!len) {
2579                         return;
2580                 }
2581         }
2582
2583         if(channel->poll_cb) {
2584                 channel->poll_cb(mesh, channel, len);
2585         } else {
2586                 utcp_set_poll_cb(connection, NULL);
2587         }
2588 }
2589
2590 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2591         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
2592
2593         if(!mesh || !channel) {
2594                 meshlink_errno = MESHLINK_EINVAL;
2595                 return;
2596         }
2597
2598         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2599                 abort();
2600         }
2601
2602         channel->poll_cb = cb;
2603         utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
2604         pthread_mutex_unlock(&mesh->mutex);
2605 }
2606
2607 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
2608         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
2609
2610         if(!mesh) {
2611                 meshlink_errno = MESHLINK_EINVAL;
2612                 return;
2613         }
2614
2615         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2616                 abort();
2617         }
2618
2619         mesh->channel_listen_cb = cb;
2620
2621         pthread_mutex_unlock(&mesh->mutex);
2622 }
2623
2624 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2625         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
2626
2627         if(!mesh) {
2628                 meshlink_errno = MESHLINK_EINVAL;
2629                 return;
2630         }
2631
2632         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2633                 abort();
2634         }
2635
2636         mesh->channel_accept_cb = cb;
2637         mesh->receive_cb = channel_receive;
2638
2639         if(mesh->peer) {
2640                 mesh->peer->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, mesh->peer);
2641                 utcp_set_mtu(mesh->peer->utcp, mesh->peer->mtu - sizeof(meshlink_packethdr_t));
2642                 utcp_set_retransmit_cb(mesh->peer->utcp, channel_retransmit);
2643         }
2644
2645         pthread_mutex_unlock(&mesh->mutex);
2646 }
2647
2648 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2649         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
2650
2651         meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
2652 }
2653
2654 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
2655         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
2656
2657         meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
2658 }
2659
2660 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2661         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2662
2663         if(!mesh || !channel) {
2664                 meshlink_errno = MESHLINK_EINVAL;
2665                 return;
2666         }
2667
2668         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2669                 abort();
2670         }
2671
2672         utcp_set_sndbuf(channel->c, buf, size);
2673         pthread_mutex_unlock(&mesh->mutex);
2674 }
2675
2676 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
2677         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
2678
2679         if(!mesh || !channel) {
2680                 meshlink_errno = MESHLINK_EINVAL;
2681                 return;
2682         }
2683
2684         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2685                 abort();
2686         }
2687
2688         utcp_set_rcvbuf(channel->c, buf, size);
2689         pthread_mutex_unlock(&mesh->mutex);
2690 }
2691
2692 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
2693         logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
2694
2695         if(!mesh || !channel) {
2696                 meshlink_errno = MESHLINK_EINVAL;
2697                 return;
2698         }
2699
2700         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2701                 abort();
2702         }
2703
2704         utcp_set_flags(channel->c, flags);
2705         pthread_mutex_unlock(&mesh->mutex);
2706 }
2707
2708 meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
2709         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu, %u)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len, flags);
2710
2711         if(data && len) {
2712                 abort();        // TODO: handle non-NULL data
2713         }
2714
2715         if(!mesh || !node) {
2716                 meshlink_errno = MESHLINK_EINVAL;
2717                 return NULL;
2718         }
2719
2720         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2721                 abort();
2722         }
2723
2724         node_t *n = (node_t *)node;
2725
2726         if(!n->utcp) {
2727                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2728                 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
2729                 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
2730                 mesh->receive_cb = channel_receive;
2731
2732                 if(!n->utcp) {
2733                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2734                         pthread_mutex_unlock(&mesh->mutex);
2735                         return NULL;
2736                 }
2737         }
2738
2739         if(n->status.blacklisted) {
2740                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2741                 meshlink_errno = MESHLINK_EBLACKLISTED;
2742                 pthread_mutex_unlock(&mesh->mutex);
2743                 return NULL;
2744         }
2745
2746         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2747         channel->node = n;
2748         channel->receive_cb = cb;
2749
2750         if(data && !len) {
2751                 channel->priv = (void *)data;
2752         }
2753
2754         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2755
2756         pthread_mutex_unlock(&mesh->mutex);
2757
2758         if(!channel->c) {
2759                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2760                 free(channel);
2761                 return NULL;
2762         }
2763
2764         return channel;
2765 }
2766
2767 meshlink_channel_t *meshlink_channel_open(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len) {
2768         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
2769
2770         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2771 }
2772
2773 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2774         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
2775
2776         if(!mesh || !channel) {
2777                 meshlink_errno = MESHLINK_EINVAL;
2778                 return;
2779         }
2780
2781         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2782                 abort();
2783         }
2784
2785         utcp_shutdown(channel->c, direction);
2786         pthread_mutex_unlock(&mesh->mutex);
2787 }
2788
2789 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2790         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
2791
2792         if(!mesh || !channel) {
2793                 meshlink_errno = MESHLINK_EINVAL;
2794                 return;
2795         }
2796
2797         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2798                 abort();
2799         }
2800
2801         if(channel->c) {
2802                 utcp_close(channel->c);
2803                 channel->c = NULL;
2804
2805                 /* Clean up any outstanding AIO buffers. */
2806                 aio_abort(mesh, channel, &channel->aio_send);
2807                 aio_abort(mesh, channel, &channel->aio_receive);
2808         }
2809
2810         if(!channel->in_callback) {
2811                 free(channel);
2812         }
2813
2814         pthread_mutex_unlock(&mesh->mutex);
2815 }
2816
2817 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2818         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
2819
2820         if(!mesh || !channel) {
2821                 meshlink_errno = MESHLINK_EINVAL;
2822                 return;
2823         }
2824
2825         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2826                 abort();
2827         }
2828
2829         if(channel->c) {
2830                 utcp_abort(channel->c);
2831                 channel->c = NULL;
2832
2833                 /* Clean up any outstanding AIO buffers. */
2834                 aio_abort(mesh, channel, &channel->aio_send);
2835                 aio_abort(mesh, channel, &channel->aio_receive);
2836         }
2837
2838         if(!channel->in_callback) {
2839                 free(channel);
2840         }
2841
2842         pthread_mutex_unlock(&mesh->mutex);
2843 }
2844
2845 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2846         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
2847
2848         if(!mesh || !channel) {
2849                 meshlink_errno = MESHLINK_EINVAL;
2850                 return -1;
2851         }
2852
2853         if(!len) {
2854                 return 0;
2855         }
2856
2857         if(!data) {
2858                 meshlink_errno = MESHLINK_EINVAL;
2859                 return -1;
2860         }
2861
2862         // TODO: more finegrained locking.
2863         // Ideally we want to put the data into the UTCP connection's send buffer.
2864         // Then, preferably only if there is room in the receiver window,
2865         // kick the meshlink thread to go send packets.
2866
2867         ssize_t retval;
2868
2869         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2870                 abort();
2871         }
2872
2873         /* Disallow direct calls to utcp_send() while we still have AIO active. */
2874         if(channel->aio_send) {
2875                 retval = 0;
2876         } else {
2877                 retval = utcp_send(channel->c, data, len);
2878         }
2879
2880         pthread_mutex_unlock(&mesh->mutex);
2881
2882         if(retval < 0) {
2883                 meshlink_errno = MESHLINK_ENETWORK;
2884         }
2885
2886         return retval;
2887 }
2888
2889 bool meshlink_channel_aio_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
2890         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
2891
2892         if(!mesh || !channel) {
2893                 meshlink_errno = MESHLINK_EINVAL;
2894                 return false;
2895         }
2896
2897         if(!len || !data) {
2898                 meshlink_errno = MESHLINK_EINVAL;
2899                 return false;
2900         }
2901
2902         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2903         aio->data = data;
2904         aio->len = len;
2905         aio->cb.buffer = cb;
2906         aio->priv = priv;
2907
2908         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2909                 abort();
2910         }
2911
2912         /* Append the AIO buffer descriptor to the end of the chain */
2913         meshlink_aio_buffer_t **p = &channel->aio_send;
2914
2915         while(*p) {
2916                 p = &(*p)->next;
2917         }
2918
2919         *p = aio;
2920
2921         /* Ensure the poll callback is set, and call it right now to push data if possible */
2922         utcp_set_poll_cb(channel->c, channel_poll);
2923         size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
2924
2925         if(todo) {
2926                 channel_poll(channel->c, todo);
2927         }
2928
2929         pthread_mutex_unlock(&mesh->mutex);
2930
2931         return true;
2932 }
2933
2934 bool meshlink_channel_aio_fd_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
2935         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
2936
2937         if(!mesh || !channel) {
2938                 meshlink_errno = MESHLINK_EINVAL;
2939                 return false;
2940         }
2941
2942         if(!len || fd == -1) {
2943                 meshlink_errno = MESHLINK_EINVAL;
2944                 return false;
2945         }
2946
2947         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2948         aio->fd = fd;
2949         aio->len = len;
2950         aio->cb.fd = cb;
2951         aio->priv = priv;
2952
2953         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2954                 abort();
2955         }
2956
2957         /* Append the AIO buffer descriptor to the end of the chain */
2958         meshlink_aio_buffer_t **p = &channel->aio_send;
2959
2960         while(*p) {
2961                 p = &(*p)->next;
2962         }
2963
2964         *p = aio;
2965
2966         /* Ensure the poll callback is set, and call it right now to push data if possible */
2967         utcp_set_poll_cb(channel->c, channel_poll);
2968         size_t left = utcp_get_rcvbuf_free(channel->c);
2969
2970         if(left) {
2971                 channel_poll(channel->c, left);
2972         }
2973
2974         pthread_mutex_unlock(&mesh->mutex);
2975
2976         return true;
2977 }
2978
2979 bool meshlink_channel_aio_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
2980         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
2981
2982         if(!mesh || !channel) {
2983                 meshlink_errno = MESHLINK_EINVAL;
2984                 return false;
2985         }
2986
2987         if(!len || !data) {
2988                 meshlink_errno = MESHLINK_EINVAL;
2989                 return false;
2990         }
2991
2992         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
2993         aio->data = data;
2994         aio->len = len;
2995         aio->cb.buffer = cb;
2996         aio->priv = priv;
2997
2998         if(pthread_mutex_lock(&mesh->mutex) != 0) {
2999                 abort();
3000         }
3001
3002         /* Append the AIO buffer descriptor to the end of the chain */
3003         meshlink_aio_buffer_t **p = &channel->aio_receive;
3004
3005         while(*p) {
3006                 p = &(*p)->next;
3007         }
3008
3009         *p = aio;
3010
3011         pthread_mutex_unlock(&mesh->mutex);
3012
3013         return true;
3014 }
3015
3016 bool meshlink_channel_aio_fd_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
3017         logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
3018
3019         if(!mesh || !channel) {
3020                 meshlink_errno = MESHLINK_EINVAL;
3021                 return false;
3022         }
3023
3024         if(!len || fd == -1) {
3025                 meshlink_errno = MESHLINK_EINVAL;
3026                 return false;
3027         }
3028
3029         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3030         aio->fd = fd;
3031         aio->len = len;
3032         aio->cb.fd = cb;
3033         aio->priv = priv;
3034
3035         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3036                 abort();
3037         }
3038
3039         /* Append the AIO buffer descriptor to the end of the chain */
3040         meshlink_aio_buffer_t **p = &channel->aio_receive;
3041
3042         while(*p) {
3043                 p = &(*p)->next;
3044         }
3045
3046         *p = aio;
3047
3048         pthread_mutex_unlock(&mesh->mutex);
3049
3050         return true;
3051 }
3052
3053 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3054         if(!mesh || !channel) {
3055                 meshlink_errno = MESHLINK_EINVAL;
3056                 return -1;
3057         }
3058
3059         return channel->c->flags;
3060 }
3061
3062 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3063         if(!mesh || !channel) {
3064                 meshlink_errno = MESHLINK_EINVAL;
3065                 return -1;
3066         }
3067
3068         return utcp_get_sendq(channel->c);
3069 }
3070
3071 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3072         if(!mesh || !channel) {
3073                 meshlink_errno = MESHLINK_EINVAL;
3074                 return -1;
3075         }
3076
3077         return utcp_get_recvq(channel->c);
3078 }
3079
3080 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3081         if(!mesh || !channel) {
3082                 meshlink_errno = MESHLINK_EINVAL;
3083                 return -1;
3084         }
3085
3086         return utcp_get_mss(channel->node->utcp);
3087 }
3088
3089 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3090         logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
3091
3092         if(!mesh || !node) {
3093                 meshlink_errno = MESHLINK_EINVAL;
3094                 return;
3095         }
3096
3097         node_t *n = (node_t *)node;
3098
3099         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3100                 abort();
3101         }
3102
3103         if(!n->utcp) {
3104                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3105                 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3106                 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3107         }
3108
3109         utcp_set_user_timeout(n->utcp, timeout);
3110
3111         pthread_mutex_unlock(&mesh->mutex);
3112 }
3113
3114 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3115         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3116                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3117                 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3118                 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3119         }
3120
3121         if(mesh->node_status_cb) {
3122                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3123         }
3124
3125         if(mesh->node_pmtu_cb) {
3126                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3127         }
3128 }
3129
3130 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3131         utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
3132
3133         if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3134                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3135         }
3136 }
3137
3138 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3139         if(!mesh->node_duplicate_cb || n->status.duplicate) {
3140                 return;
3141         }
3142
3143         n->status.duplicate = true;
3144         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3145 }
3146
3147 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
3148         logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
3149
3150         if(!mesh) {
3151                 meshlink_errno = MESHLINK_EINVAL;
3152                 return;
3153         }
3154
3155         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3156                 abort();
3157         }
3158
3159         pthread_mutex_unlock(&mesh->mutex);
3160 }
3161
3162 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3163         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
3164
3165         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3166                 meshlink_errno = EINVAL;
3167                 return;
3168         }
3169
3170         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3171                 meshlink_errno = EINVAL;
3172                 return;
3173         }
3174
3175         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3176                 abort();
3177         }
3178
3179         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3180         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3181         pthread_mutex_unlock(&mesh->mutex);
3182 }
3183
3184 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3185         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
3186
3187         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3188                 meshlink_errno = EINVAL;
3189                 return;
3190         }
3191
3192         if(fast_retry_period < 0) {
3193                 meshlink_errno = EINVAL;
3194                 return;
3195         }
3196
3197         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3198                 abort();
3199         }
3200
3201         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3202         pthread_mutex_unlock(&mesh->mutex);
3203 }
3204
3205 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
3206         logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
3207
3208         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3209                 meshlink_errno = EINVAL;
3210                 return;
3211         }
3212
3213         if(maxtimeout < 0) {
3214                 meshlink_errno = EINVAL;
3215                 return;
3216         }
3217
3218         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3219                 abort();
3220         }
3221
3222         mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
3223         pthread_mutex_unlock(&mesh->mutex);
3224 }
3225
3226 void meshlink_reset_timers(struct meshlink_handle *mesh) {
3227         logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
3228
3229         if(!mesh) {
3230                 return;
3231         }
3232
3233         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3234                 abort();
3235         }
3236
3237         handle_network_change(mesh, true);
3238
3239         pthread_mutex_unlock(&mesh->mutex);
3240 }
3241
3242 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3243         logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
3244
3245         if(!mesh) {
3246                 meshlink_errno = EINVAL;
3247                 return;
3248         }
3249
3250         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3251                 abort();
3252         }
3253
3254         mesh->inviter_commits_first = inviter_commits_first;
3255         pthread_mutex_unlock(&mesh->mutex);
3256 }
3257
3258 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
3259         logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
3260
3261         if(!mesh || granularity < 0) {
3262                 meshlink_errno = EINVAL;
3263                 return;
3264         }
3265
3266         utcp_set_clock_granularity(granularity);
3267 }
3268
3269 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
3270         logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
3271
3272         if(!mesh) {
3273                 meshlink_errno = EINVAL;
3274                 return;
3275         }
3276
3277         if(pthread_mutex_lock(&mesh->mutex) != 0) {
3278                 abort();
3279         }
3280
3281         mesh->storage_policy = policy;
3282         pthread_mutex_unlock(&mesh->mutex);
3283 }
3284
3285 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3286         (void)online;
3287
3288         if(!mesh->loop.running) {
3289                 return;
3290         }
3291
3292         retry(mesh);
3293         signal_trigger(&mesh->loop, &mesh->datafromapp);
3294 }
3295
3296 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
3297         // We should only call the callback function if we are in the background thread.
3298         if(!mesh->error_cb) {
3299                 return;
3300         }
3301
3302         if(!mesh->threadstarted) {
3303                 return;
3304         }
3305
3306         if(mesh->thread == pthread_self()) {
3307                 mesh->error_cb(mesh, cb_errno);
3308         }
3309 }
3310
3311 static void __attribute__((constructor)) meshlink_init(void) {
3312         crypto_init();
3313         utcp_set_clock_granularity(10000);
3314 }
3315
3316 static void __attribute__((destructor)) meshlink_exit(void) {
3317         crypto_exit();
3318 }