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