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