]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Use the first working outgoing socket during meshlink_join().
[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                                 break;
2774                         }
2775
2776                         freeaddrinfo(ai);
2777                 } else {
2778                         meshlink_errno = MESHLINK_ERESOLV;
2779                 }
2780
2781                 if(state.sock != -1 || !comma) {
2782                         break;
2783                 }
2784
2785                 address = comma;
2786         }
2787
2788         if(state.sock == -1) {
2789                 goto exit;
2790         }
2791
2792         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2793
2794         // Tell him we have an invitation, and give him our throw-away key.
2795
2796         state.blen = 0;
2797
2798         if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2799                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2800                 meshlink_errno = MESHLINK_ENETWORK;
2801                 goto exit;
2802         }
2803
2804         free(b64key);
2805
2806         char hisname[4096] = "";
2807         int code, hismajor, hisminor = 0;
2808
2809         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) {
2810                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2811                 meshlink_errno = MESHLINK_ENETWORK;
2812                 goto exit;
2813         }
2814
2815         // Check if the hash of the key he gave us matches the hash in the URL.
2816         char *fingerprint = state.line + 2;
2817         char hishash[64];
2818
2819         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2820                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2821                 meshlink_errno = MESHLINK_EINTERNAL;
2822                 goto exit;
2823         }
2824
2825         if(memcmp(hishash, state.hash, 18)) {
2826                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2827                 meshlink_errno = MESHLINK_EPEER;
2828                 goto exit;
2829         }
2830
2831         hiskey = ecdsa_set_base64_public_key(fingerprint);
2832
2833         if(!hiskey) {
2834                 meshlink_errno = MESHLINK_EINTERNAL;
2835                 goto exit;
2836         }
2837
2838         // Start an SPTPS session
2839         if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2840                 meshlink_errno = MESHLINK_EINTERNAL;
2841                 goto exit;
2842         }
2843
2844         // Feed rest of input buffer to SPTPS
2845         if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2846                 meshlink_errno = MESHLINK_EPEER;
2847                 goto exit;
2848         }
2849
2850         ssize_t len;
2851         logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2852
2853         while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2854                 if(len < 0) {
2855                         if(errno == EINTR) {
2856                                 continue;
2857                         }
2858
2859                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2860                         meshlink_errno = MESHLINK_ENETWORK;
2861                         goto exit;
2862                 }
2863
2864                 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2865                         meshlink_errno = MESHLINK_EPEER;
2866                         goto exit;
2867                 }
2868         }
2869
2870         if(!state.success) {
2871                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2872                 meshlink_errno = MESHLINK_EPEER;
2873                 goto exit;
2874         }
2875
2876         sptps_stop(&state.sptps);
2877         ecdsa_free(hiskey);
2878         ecdsa_free(key);
2879         closesocket(state.sock);
2880
2881         pthread_mutex_unlock(&mesh->mutex);
2882         return true;
2883
2884 invalid:
2885         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2886         meshlink_errno = MESHLINK_EINVAL;
2887 exit:
2888         sptps_stop(&state.sptps);
2889         ecdsa_free(hiskey);
2890         ecdsa_free(key);
2891
2892         if(state.sock != -1) {
2893                 closesocket(state.sock);
2894         }
2895
2896         pthread_mutex_unlock(&mesh->mutex);
2897         return false;
2898 }
2899
2900 char *meshlink_export(meshlink_handle_t *mesh) {
2901         if(!mesh) {
2902                 meshlink_errno = MESHLINK_EINVAL;
2903                 return NULL;
2904         }
2905
2906         // Create a config file on the fly.
2907
2908         uint8_t buf[4096];
2909         packmsg_output_t out = {buf, sizeof(buf)};
2910         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2911         packmsg_add_str(&out, mesh->name);
2912         packmsg_add_str(&out, CORE_MESH);
2913
2914         pthread_mutex_lock(&mesh->mutex);
2915
2916         packmsg_add_int32(&out, mesh->self->devclass);
2917         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2918         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2919         packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2920
2921         uint32_t count = 0;
2922
2923         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2924                 if(mesh->self->recent[i].sa.sa_family) {
2925                         count++;
2926                 } else {
2927                         break;
2928                 }
2929         }
2930
2931         packmsg_add_array(&out, count);
2932
2933         for(uint32_t i = 0; i < count; i++) {
2934                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2935         }
2936
2937         packmsg_add_int64(&out, 0);
2938         packmsg_add_int64(&out, 0);
2939
2940         pthread_mutex_unlock(&mesh->mutex);
2941
2942         if(!packmsg_output_ok(&out)) {
2943                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2944                 meshlink_errno = MESHLINK_EINTERNAL;
2945                 return NULL;
2946         }
2947
2948         // Prepare a base64-encoded packmsg array containing our config file
2949
2950         uint32_t len = packmsg_output_size(&out, buf);
2951         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2952         uint8_t *buf2 = xmalloc(len2);
2953         packmsg_output_t out2 = {buf2, len2};
2954         packmsg_add_array(&out2, 1);
2955         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2956
2957         if(!packmsg_output_ok(&out2)) {
2958                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2959                 meshlink_errno = MESHLINK_EINTERNAL;
2960                 free(buf2);
2961                 return NULL;
2962         }
2963
2964         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2965
2966         return (char *)buf2;
2967 }
2968
2969 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2970         if(!mesh || !data) {
2971                 meshlink_errno = MESHLINK_EINVAL;
2972                 return false;
2973         }
2974
2975         size_t datalen = strlen(data);
2976         uint8_t *buf = xmalloc(datalen);
2977         int buflen = b64decode(data, buf, datalen);
2978
2979         if(!buflen) {
2980                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2981                 meshlink_errno = MESHLINK_EPEER;
2982                 return false;
2983         }
2984
2985         packmsg_input_t in = {buf, buflen};
2986         uint32_t count = packmsg_get_array(&in);
2987
2988         if(!count) {
2989                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2990                 meshlink_errno = MESHLINK_EPEER;
2991                 return false;
2992         }
2993
2994         pthread_mutex_lock(&mesh->mutex);
2995
2996         while(count--) {
2997                 const void *data;
2998                 uint32_t len = packmsg_get_bin_raw(&in, &data);
2999
3000                 if(!len) {
3001                         break;
3002                 }
3003
3004                 packmsg_input_t in2 = {data, len};
3005                 uint32_t version = packmsg_get_uint32(&in2);
3006                 char *name = packmsg_get_str_dup(&in2);
3007
3008                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3009                         free(name);
3010                         packmsg_input_invalidate(&in);
3011                         break;
3012                 }
3013
3014                 if(!check_id(name)) {
3015                         free(name);
3016                         break;
3017                 }
3018
3019                 node_t *n = lookup_node(mesh, name);
3020
3021                 if(n) {
3022                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3023                         free(name);
3024                         continue;
3025                 }
3026
3027                 n = new_node();
3028                 n->name = name;
3029
3030                 config_t config = {data, len};
3031
3032                 if(!node_read_from_config(mesh, n, &config)) {
3033                         free_node(n);
3034                         packmsg_input_invalidate(&in);
3035                         break;
3036                 }
3037
3038                 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3039                 n->last_reachable = 0;
3040                 n->last_unreachable = 0;
3041
3042                 if(!node_write_config(mesh, n)) {
3043                         free_node(n);
3044                         return false;
3045                 }
3046
3047                 node_add(mesh, n);
3048         }
3049
3050         pthread_mutex_unlock(&mesh->mutex);
3051
3052         free(buf);
3053
3054         if(!packmsg_done(&in)) {
3055                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3056                 meshlink_errno = MESHLINK_EPEER;
3057                 return false;
3058         }
3059
3060         if(!config_sync(mesh, "current")) {
3061                 return false;
3062         }
3063
3064         return true;
3065 }
3066
3067 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3068         if(n == mesh->self) {
3069                 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3070                 meshlink_errno = MESHLINK_EINVAL;
3071                 return false;
3072         }
3073
3074         if(n->status.blacklisted) {
3075                 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3076                 return true;
3077         }
3078
3079         n->status.blacklisted = true;
3080
3081         /* Immediately shut down any connections we have with the blacklisted node.
3082          * We can't call terminate_connection(), because we might be called from a callback function.
3083          */
3084         for list_each(connection_t, c, mesh->connections) {
3085                 if(c->node == n) {
3086                         shutdown(c->socket, SHUT_RDWR);
3087                 }
3088         }
3089
3090         utcp_abort_all_connections(n->utcp);
3091
3092         n->mtu = 0;
3093         n->minmtu = 0;
3094         n->maxmtu = MTU;
3095         n->mtuprobes = 0;
3096         n->status.udp_confirmed = false;
3097
3098         if(n->status.reachable) {
3099                 n->last_unreachable = mesh->loop.now.tv_sec;
3100         }
3101
3102         /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3103          * manually call the status callback if necessary.
3104          */
3105         if(n->status.reachable && mesh->node_status_cb) {
3106                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3107         }
3108
3109         return node_write_config(mesh, n) && config_sync(mesh, "current");
3110 }
3111
3112 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3113         if(!mesh || !node) {
3114                 meshlink_errno = MESHLINK_EINVAL;
3115                 return false;
3116         }
3117
3118         pthread_mutex_lock(&mesh->mutex);
3119
3120         if(!blacklist(mesh, (node_t *)node)) {
3121                 pthread_mutex_unlock(&mesh->mutex);
3122                 return false;
3123         }
3124
3125         pthread_mutex_unlock(&mesh->mutex);
3126
3127         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3128         return true;
3129 }
3130
3131 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3132         if(!mesh || !name) {
3133                 meshlink_errno = MESHLINK_EINVAL;
3134                 return false;
3135         }
3136
3137         pthread_mutex_lock(&mesh->mutex);
3138
3139         node_t *n = lookup_node(mesh, (char *)name);
3140
3141         if(!n) {
3142                 n = new_node();
3143                 n->name = xstrdup(name);
3144                 node_add(mesh, n);
3145         }
3146
3147         if(!blacklist(mesh, (node_t *)n)) {
3148                 pthread_mutex_unlock(&mesh->mutex);
3149                 return false;
3150         }
3151
3152         pthread_mutex_unlock(&mesh->mutex);
3153
3154         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3155         return true;
3156 }
3157
3158 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3159         if(n == mesh->self) {
3160                 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3161                 meshlink_errno = MESHLINK_EINVAL;
3162                 return false;
3163         }
3164
3165         if(!n->status.blacklisted) {
3166                 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3167                 return true;
3168         }
3169
3170         n->status.blacklisted = false;
3171
3172         if(n->status.reachable) {
3173                 n->last_reachable = mesh->loop.now.tv_sec;
3174                 update_node_status(mesh, n);
3175         }
3176
3177         return node_write_config(mesh, n) && config_sync(mesh, "current");
3178 }
3179
3180 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3181         if(!mesh || !node) {
3182                 meshlink_errno = MESHLINK_EINVAL;
3183                 return false;
3184         }
3185
3186         pthread_mutex_lock(&mesh->mutex);
3187
3188         if(!whitelist(mesh, (node_t *)node)) {
3189                 pthread_mutex_unlock(&mesh->mutex);
3190                 return false;
3191         }
3192
3193         pthread_mutex_unlock(&mesh->mutex);
3194
3195         logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3196         return true;
3197 }
3198
3199 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3200         if(!mesh || !name) {
3201                 meshlink_errno = MESHLINK_EINVAL;
3202                 return false;
3203         }
3204
3205         pthread_mutex_lock(&mesh->mutex);
3206
3207         node_t *n = lookup_node(mesh, (char *)name);
3208
3209         if(!n) {
3210                 n = new_node();
3211                 n->name = xstrdup(name);
3212                 node_add(mesh, n);
3213         }
3214
3215         if(!whitelist(mesh, (node_t *)n)) {
3216                 pthread_mutex_unlock(&mesh->mutex);
3217                 return false;
3218         }
3219
3220         pthread_mutex_unlock(&mesh->mutex);
3221
3222         logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3223         return true;
3224 }
3225
3226 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3227         mesh->default_blacklist = blacklist;
3228 }
3229
3230 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3231         if(!mesh || !node) {
3232                 meshlink_errno = MESHLINK_EINVAL;
3233                 return false;
3234         }
3235
3236         node_t *n = (node_t *)node;
3237
3238         pthread_mutex_lock(&mesh->mutex);
3239
3240         /* Check that the node is not reachable */
3241         if(n->status.reachable || n->connection) {
3242                 pthread_mutex_unlock(&mesh->mutex);
3243                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3244                 return false;
3245         }
3246
3247         /* Check that we don't have any active UTCP connections */
3248         if(n->utcp && utcp_is_active(n->utcp)) {
3249                 pthread_mutex_unlock(&mesh->mutex);
3250                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3251                 return false;
3252         }
3253
3254         /* Check that we have no active connections to this node */
3255         for list_each(connection_t, c, mesh->connections) {
3256                 if(c->node == n) {
3257                         pthread_mutex_unlock(&mesh->mutex);
3258                         logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3259                         return false;
3260                 }
3261         }
3262
3263         /* Remove any pending outgoings to this node */
3264         if(mesh->outgoings) {
3265                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3266                         if(outgoing->node == n) {
3267                                 list_delete_node(mesh->outgoings, node);
3268                         }
3269                 }
3270         }
3271
3272         /* Delete the config file for this node */
3273         if(!config_delete(mesh, "current", n->name)) {
3274                 pthread_mutex_unlock(&mesh->mutex);
3275                 return false;
3276         }
3277
3278         /* Delete the node struct and any remaining edges referencing this node */
3279         node_del(mesh, n);
3280
3281         pthread_mutex_unlock(&mesh->mutex);
3282
3283         return config_sync(mesh, "current");
3284 }
3285
3286 /* Hint that a hostname may be found at an address
3287  * See header file for detailed comment.
3288  */
3289 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3290         if(!mesh || !node || !addr) {
3291                 meshlink_errno = EINVAL;
3292                 return;
3293         }
3294
3295         pthread_mutex_lock(&mesh->mutex);
3296
3297         node_t *n = (node_t *)node;
3298
3299         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3300                 if(!node_write_config(mesh, n)) {
3301                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3302                 }
3303         }
3304
3305         pthread_mutex_unlock(&mesh->mutex);
3306         // @TODO do we want to fire off a connection attempt right away?
3307 }
3308
3309 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3310         (void)port;
3311         node_t *n = utcp->priv;
3312         meshlink_handle_t *mesh = n->mesh;
3313         return mesh->channel_accept_cb;
3314 }
3315
3316 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3317         if(aio->data) {
3318                 if(aio->cb.buffer) {
3319                         aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3320                 }
3321         } else {
3322                 if(aio->cb.fd) {
3323                         aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3324                 }
3325         }
3326 }
3327
3328 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3329         meshlink_channel_t *channel = connection->priv;
3330
3331         if(!channel) {
3332                 abort();
3333         }
3334
3335         node_t *n = channel->node;
3336         meshlink_handle_t *mesh = n->mesh;
3337
3338         if(n->status.destroyed) {
3339                 meshlink_channel_close(mesh, channel);
3340                 return len;
3341         }
3342
3343         const char *p = data;
3344         size_t left = len;
3345
3346         while(channel->aio_receive) {
3347                 meshlink_aio_buffer_t *aio = channel->aio_receive;
3348                 size_t todo = aio->len - aio->done;
3349
3350                 if(todo > left) {
3351                         todo = left;
3352                 }
3353
3354                 if(aio->data) {
3355                         memcpy((char *)aio->data + aio->done, p, todo);
3356                 } else {
3357                         ssize_t result = write(aio->fd, p, todo);
3358
3359                         if(result > 0) {
3360                                 todo = result;
3361                         }
3362                 }
3363
3364                 aio->done += todo;
3365
3366                 if(aio->done == aio->len) {
3367                         channel->aio_receive = aio->next;
3368                         aio_signal(mesh, channel, aio);
3369                         free(aio);
3370                 }
3371
3372                 p += todo;
3373                 left -= todo;
3374
3375                 if(!left && len) {
3376                         return len;
3377                 }
3378         }
3379
3380         if(channel->receive_cb) {
3381                 channel->receive_cb(mesh, channel, p, left);
3382         }
3383
3384         return len;
3385 }
3386
3387 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3388         node_t *n = utcp_connection->utcp->priv;
3389
3390         if(!n) {
3391                 abort();
3392         }
3393
3394         meshlink_handle_t *mesh = n->mesh;
3395
3396         if(!mesh->channel_accept_cb) {
3397                 return;
3398         }
3399
3400         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3401         channel->node = n;
3402         channel->c = utcp_connection;
3403
3404         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3405                 utcp_accept(utcp_connection, channel_recv, channel);
3406         } else {
3407                 free(channel);
3408         }
3409 }
3410
3411 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3412         node_t *n = utcp->priv;
3413
3414         if(n->status.destroyed) {
3415                 return -1;
3416         }
3417
3418         meshlink_handle_t *mesh = n->mesh;
3419         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3420 }
3421
3422 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3423         if(!mesh || !channel) {
3424                 meshlink_errno = MESHLINK_EINVAL;
3425                 return;
3426         }
3427
3428         channel->receive_cb = cb;
3429 }
3430
3431 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3432         (void)mesh;
3433         node_t *n = (node_t *)source;
3434
3435         if(!n->utcp) {
3436                 abort();
3437         }
3438
3439         utcp_recv(n->utcp, data, len);
3440 }
3441
3442 static void channel_poll(struct utcp_connection *connection, size_t len) {
3443         meshlink_channel_t *channel = connection->priv;
3444
3445         if(!channel) {
3446                 abort();
3447         }
3448
3449         node_t *n = channel->node;
3450         meshlink_handle_t *mesh = n->mesh;
3451         meshlink_aio_buffer_t *aio = channel->aio_send;
3452
3453         if(aio) {
3454                 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3455                 size_t left = aio->len - aio->done;
3456                 ssize_t sent;
3457
3458                 if(len > left) {
3459                         len = left;
3460                 }
3461
3462                 if(aio->data) {
3463                         sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3464                 } else {
3465                         char buf[65536];
3466                         size_t todo = utcp_get_sndbuf_free(connection);
3467
3468                         if(todo > left) {
3469                                 todo = left;
3470                         }
3471
3472                         if(todo > sizeof(buf)) {
3473                                 todo = sizeof(buf);
3474                         }
3475
3476                         ssize_t result = read(aio->fd, buf, todo);
3477
3478                         if(result > 0) {
3479                                 sent = utcp_send(connection, buf, result);
3480                         } else {
3481                                 sent = result;
3482                         }
3483                 }
3484
3485                 if(sent >= 0) {
3486                         aio->done += sent;
3487                 }
3488
3489                 /* If the buffer is now completely sent, call the callback and dispose of it. */
3490                 if(aio->done >= aio->len) {
3491                         channel->aio_send = aio->next;
3492                         aio_signal(mesh, channel, aio);
3493                         free(aio);
3494                 }
3495         } else {
3496                 if(channel->poll_cb) {
3497                         channel->poll_cb(mesh, channel, len);
3498                 } else {
3499                         utcp_set_poll_cb(connection, NULL);
3500                 }
3501         }
3502 }
3503
3504 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3505         if(!mesh || !channel) {
3506                 meshlink_errno = MESHLINK_EINVAL;
3507                 return;
3508         }
3509
3510         pthread_mutex_lock(&mesh->mutex);
3511         channel->poll_cb = cb;
3512         utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3513         pthread_mutex_unlock(&mesh->mutex);
3514 }
3515
3516 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3517         if(!mesh) {
3518                 meshlink_errno = MESHLINK_EINVAL;
3519                 return;
3520         }
3521
3522         pthread_mutex_lock(&mesh->mutex);
3523         mesh->channel_accept_cb = cb;
3524         mesh->receive_cb = channel_receive;
3525
3526         for splay_each(node_t, n, mesh->nodes) {
3527                 if(!n->utcp && n != mesh->self) {
3528                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3529                 }
3530         }
3531
3532         pthread_mutex_unlock(&mesh->mutex);
3533 }
3534
3535 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3536         (void)mesh;
3537
3538         if(!channel) {
3539                 meshlink_errno = MESHLINK_EINVAL;
3540                 return;
3541         }
3542
3543         pthread_mutex_lock(&mesh->mutex);
3544         utcp_set_sndbuf(channel->c, size);
3545         pthread_mutex_unlock(&mesh->mutex);
3546 }
3547
3548 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3549         (void)mesh;
3550
3551         if(!channel) {
3552                 meshlink_errno = MESHLINK_EINVAL;
3553                 return;
3554         }
3555
3556         pthread_mutex_lock(&mesh->mutex);
3557         utcp_set_rcvbuf(channel->c, size);
3558         pthread_mutex_unlock(&mesh->mutex);
3559 }
3560
3561 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) {
3562         if(data && len) {
3563                 abort();        // TODO: handle non-NULL data
3564         }
3565
3566         if(!mesh || !node) {
3567                 meshlink_errno = MESHLINK_EINVAL;
3568                 return NULL;
3569         }
3570
3571         pthread_mutex_lock(&mesh->mutex);
3572
3573         node_t *n = (node_t *)node;
3574
3575         if(!n->utcp) {
3576                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3577                 mesh->receive_cb = channel_receive;
3578
3579                 if(!n->utcp) {
3580                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3581                         pthread_mutex_unlock(&mesh->mutex);
3582                         return NULL;
3583                 }
3584         }
3585
3586         if(n->status.blacklisted) {
3587                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3588                 meshlink_errno = MESHLINK_EBLACKLISTED;
3589                 pthread_mutex_unlock(&mesh->mutex);
3590                 return NULL;
3591         }
3592
3593         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3594         channel->node = n;
3595         channel->receive_cb = cb;
3596
3597         if(data && !len) {
3598                 channel->priv = (void *)data;
3599         }
3600
3601         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3602
3603         pthread_mutex_unlock(&mesh->mutex);
3604
3605         if(!channel->c) {
3606                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3607                 free(channel);
3608                 return NULL;
3609         }
3610
3611         return channel;
3612 }
3613
3614 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) {
3615         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3616 }
3617
3618 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3619         if(!mesh || !channel) {
3620                 meshlink_errno = MESHLINK_EINVAL;
3621                 return;
3622         }
3623
3624         pthread_mutex_lock(&mesh->mutex);
3625         utcp_shutdown(channel->c, direction);
3626         pthread_mutex_unlock(&mesh->mutex);
3627 }
3628
3629 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3630         if(!mesh || !channel) {
3631                 meshlink_errno = MESHLINK_EINVAL;
3632                 return;
3633         }
3634
3635         pthread_mutex_lock(&mesh->mutex);
3636
3637         utcp_close(channel->c);
3638
3639         /* Clean up any outstanding AIO buffers. */
3640         for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3641                 next = aio->next;
3642                 aio_signal(mesh, channel, aio);
3643                 free(aio);
3644         }
3645
3646         for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3647                 next = aio->next;
3648                 aio_signal(mesh, channel, aio);
3649                 free(aio);
3650         }
3651
3652         pthread_mutex_unlock(&mesh->mutex);
3653
3654         free(channel);
3655 }
3656
3657 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3658         if(!mesh || !channel) {
3659                 meshlink_errno = MESHLINK_EINVAL;
3660                 return -1;
3661         }
3662
3663         if(!len) {
3664                 return 0;
3665         }
3666
3667         if(!data) {
3668                 meshlink_errno = MESHLINK_EINVAL;
3669                 return -1;
3670         }
3671
3672         // TODO: more finegrained locking.
3673         // Ideally we want to put the data into the UTCP connection's send buffer.
3674         // Then, preferably only if there is room in the receiver window,
3675         // kick the meshlink thread to go send packets.
3676
3677         ssize_t retval;
3678
3679         pthread_mutex_lock(&mesh->mutex);
3680
3681         /* Disallow direct calls to utcp_send() while we still have AIO active. */
3682         if(channel->aio_send) {
3683                 retval = 0;
3684         } else {
3685                 retval = utcp_send(channel->c, data, len);
3686         }
3687
3688         pthread_mutex_unlock(&mesh->mutex);
3689
3690         if(retval < 0) {
3691                 meshlink_errno = MESHLINK_ENETWORK;
3692         }
3693
3694         return retval;
3695 }
3696
3697 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) {
3698         if(!mesh || !channel) {
3699                 meshlink_errno = MESHLINK_EINVAL;
3700                 return false;
3701         }
3702
3703         if(!len || !data) {
3704                 meshlink_errno = MESHLINK_EINVAL;
3705                 return false;
3706         }
3707
3708         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3709         aio->data = data;
3710         aio->len = len;
3711         aio->cb.buffer = cb;
3712         aio->priv = priv;
3713
3714         pthread_mutex_lock(&mesh->mutex);
3715
3716         /* Append the AIO buffer descriptor to the end of the chain */
3717         meshlink_aio_buffer_t **p = &channel->aio_send;
3718
3719         while(*p) {
3720                 p = &(*p)->next;
3721         }
3722
3723         *p = aio;
3724
3725         /* Ensure the poll callback is set, and call it right now to push data if possible */
3726         utcp_set_poll_cb(channel->c, channel_poll);
3727         channel_poll(channel->c, len);
3728
3729         pthread_mutex_unlock(&mesh->mutex);
3730
3731         return true;
3732 }
3733
3734 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) {
3735         if(!mesh || !channel) {
3736                 meshlink_errno = MESHLINK_EINVAL;
3737                 return false;
3738         }
3739
3740         if(!len || fd == -1) {
3741                 meshlink_errno = MESHLINK_EINVAL;
3742                 return false;
3743         }
3744
3745         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3746         aio->fd = fd;
3747         aio->len = len;
3748         aio->cb.fd = cb;
3749         aio->priv = priv;
3750
3751         pthread_mutex_lock(&mesh->mutex);
3752
3753         /* Append the AIO buffer descriptor to the end of the chain */
3754         meshlink_aio_buffer_t **p = &channel->aio_send;
3755
3756         while(*p) {
3757                 p = &(*p)->next;
3758         }
3759
3760         *p = aio;
3761
3762         /* Ensure the poll callback is set, and call it right now to push data if possible */
3763         utcp_set_poll_cb(channel->c, channel_poll);
3764         channel_poll(channel->c, len);
3765
3766         pthread_mutex_unlock(&mesh->mutex);
3767
3768         return true;
3769 }
3770
3771 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) {
3772         if(!mesh || !channel) {
3773                 meshlink_errno = MESHLINK_EINVAL;
3774                 return false;
3775         }
3776
3777         if(!len || !data) {
3778                 meshlink_errno = MESHLINK_EINVAL;
3779                 return false;
3780         }
3781
3782         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3783         aio->data = data;
3784         aio->len = len;
3785         aio->cb.buffer = cb;
3786         aio->priv = priv;
3787
3788         pthread_mutex_lock(&mesh->mutex);
3789
3790         /* Append the AIO buffer descriptor to the end of the chain */
3791         meshlink_aio_buffer_t **p = &channel->aio_receive;
3792
3793         while(*p) {
3794                 p = &(*p)->next;
3795         }
3796
3797         *p = aio;
3798
3799         pthread_mutex_unlock(&mesh->mutex);
3800
3801         return true;
3802 }
3803
3804 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) {
3805         if(!mesh || !channel) {
3806                 meshlink_errno = MESHLINK_EINVAL;
3807                 return false;
3808         }
3809
3810         if(!len || fd == -1) {
3811                 meshlink_errno = MESHLINK_EINVAL;
3812                 return false;
3813         }
3814
3815         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3816         aio->fd = fd;
3817         aio->len = len;
3818         aio->cb.fd = cb;
3819         aio->priv = priv;
3820
3821         pthread_mutex_lock(&mesh->mutex);
3822
3823         /* Append the AIO buffer descriptor to the end of the chain */
3824         meshlink_aio_buffer_t **p = &channel->aio_receive;
3825
3826         while(*p) {
3827                 p = &(*p)->next;
3828         }
3829
3830         *p = aio;
3831
3832         pthread_mutex_unlock(&mesh->mutex);
3833
3834         return true;
3835 }
3836
3837 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3838         if(!mesh || !channel) {
3839                 meshlink_errno = MESHLINK_EINVAL;
3840                 return -1;
3841         }
3842
3843         return channel->c->flags;
3844 }
3845
3846 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3847         if(!mesh || !channel) {
3848                 meshlink_errno = MESHLINK_EINVAL;
3849                 return -1;
3850         }
3851
3852         return utcp_get_sendq(channel->c);
3853 }
3854
3855 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3856         if(!mesh || !channel) {
3857                 meshlink_errno = MESHLINK_EINVAL;
3858                 return -1;
3859         }
3860
3861         return utcp_get_recvq(channel->c);
3862 }
3863
3864 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3865         if(!mesh || !node) {
3866                 meshlink_errno = MESHLINK_EINVAL;
3867                 return;
3868         }
3869
3870         node_t *n = (node_t *)node;
3871
3872         pthread_mutex_lock(&mesh->mutex);
3873
3874         if(!n->utcp) {
3875                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3876         }
3877
3878         utcp_set_user_timeout(n->utcp, timeout);
3879
3880         pthread_mutex_unlock(&mesh->mutex);
3881 }
3882
3883 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3884         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3885                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3886         }
3887
3888         if(mesh->node_status_cb) {
3889                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3890         }
3891
3892         if(mesh->node_pmtu_cb) {
3893                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3894         }
3895 }
3896
3897 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3898         if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3899                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3900         }
3901 }
3902
3903 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3904         if(!mesh->node_duplicate_cb || n->status.duplicate) {
3905                 return;
3906         }
3907
3908         n->status.duplicate = true;
3909         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3910 }
3911
3912 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3913 #if HAVE_CATTA
3914
3915         if(!mesh) {
3916                 meshlink_errno = MESHLINK_EINVAL;
3917                 return;
3918         }
3919
3920         pthread_mutex_lock(&mesh->mutex);
3921
3922         if(mesh->discovery == enable) {
3923                 goto end;
3924         }
3925
3926         if(mesh->threadstarted) {
3927                 if(enable) {
3928                         discovery_start(mesh);
3929                 } else {
3930                         discovery_stop(mesh);
3931                 }
3932         }
3933
3934         mesh->discovery = enable;
3935
3936 end:
3937         pthread_mutex_unlock(&mesh->mutex);
3938 #else
3939         (void)mesh;
3940         (void)enable;
3941         meshlink_errno = MESHLINK_ENOTSUP;
3942 #endif
3943 }
3944
3945 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3946         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3947                 meshlink_errno = EINVAL;
3948                 return;
3949         }
3950
3951         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3952                 meshlink_errno = EINVAL;
3953                 return;
3954         }
3955
3956         pthread_mutex_lock(&mesh->mutex);
3957         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3958         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3959         pthread_mutex_unlock(&mesh->mutex);
3960 }
3961
3962 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3963         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3964                 meshlink_errno = EINVAL;
3965                 return;
3966         }
3967
3968         if(fast_retry_period < 0) {
3969                 meshlink_errno = EINVAL;
3970                 return;
3971         }
3972
3973         pthread_mutex_lock(&mesh->mutex);
3974         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3975         pthread_mutex_unlock(&mesh->mutex);
3976 }
3977
3978 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3979         if(!mesh) {
3980                 meshlink_errno = EINVAL;
3981                 return;
3982         }
3983
3984         pthread_mutex_lock(&mesh->mutex);
3985         mesh->inviter_commits_first = inviter_commits_first;
3986         pthread_mutex_unlock(&mesh->mutex);
3987 }
3988
3989 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3990         (void)online;
3991
3992         if(!mesh->connections || !mesh->loop.running) {
3993                 return;
3994         }
3995
3996         retry(mesh);
3997 }
3998
3999 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
4000         // We should only call the callback function if we are in the background thread.
4001         if(!mesh->error_cb) {
4002                 return;
4003         }
4004
4005         if(!mesh->threadstarted) {
4006                 return;
4007         }
4008
4009         if(mesh->thread == pthread_self()) {
4010                 mesh->error_cb(mesh, meshlink_errno);
4011         }
4012 }
4013
4014 static void __attribute__((constructor)) meshlink_init(void) {
4015         crypto_init();
4016 }
4017
4018 static void __attribute__((destructor)) meshlink_exit(void) {
4019         crypto_exit();
4020 }