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