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