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