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