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