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