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