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