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