]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Move assert()s that dereference a pointer to after the pointer NULL check.
[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         if(!mesh) {
1562                 meshlink_errno = MESHLINK_EINVAL;
1563                 return false;
1564         }
1565
1566         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1567
1568         pthread_mutex_lock(&mesh->mutex);
1569
1570         assert(mesh->self);
1571         assert(mesh->private_key);
1572         assert(mesh->self->ecdsa);
1573         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1574
1575         if(mesh->threadstarted) {
1576                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1577                 pthread_mutex_unlock(&mesh->mutex);
1578                 return true;
1579         }
1580
1581         if(mesh->listen_socket[0].tcp.fd < 0) {
1582                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1583                 meshlink_errno = MESHLINK_ENETWORK;
1584                 return false;
1585         }
1586
1587         // TODO: open listening sockets first
1588
1589         //Check that a valid name is set
1590         if(!mesh->name) {
1591                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1592                 meshlink_errno = MESHLINK_EINVAL;
1593                 pthread_mutex_unlock(&mesh->mutex);
1594                 return false;
1595         }
1596
1597         init_outgoings(mesh);
1598
1599         // Start the main thread
1600
1601         event_loop_start(&mesh->loop);
1602
1603         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1604                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1605                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1606                 meshlink_errno = MESHLINK_EINTERNAL;
1607                 event_loop_stop(&mesh->loop);
1608                 pthread_mutex_unlock(&mesh->mutex);
1609                 return false;
1610         }
1611
1612         pthread_cond_wait(&mesh->cond, &mesh->mutex);
1613         mesh->threadstarted = true;
1614
1615         // Ensure we are considered reachable
1616         graph(mesh);
1617
1618         pthread_mutex_unlock(&mesh->mutex);
1619         return true;
1620 }
1621
1622 void meshlink_stop(meshlink_handle_t *mesh) {
1623         if(!mesh) {
1624                 meshlink_errno = MESHLINK_EINVAL;
1625                 return;
1626         }
1627
1628         pthread_mutex_lock(&mesh->mutex);
1629         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1630
1631         // Shut down the main thread
1632         event_loop_stop(&mesh->loop);
1633
1634         // Send ourselves a UDP packet to kick the event loop
1635         for(int i = 0; i < mesh->listen_sockets; i++) {
1636                 sockaddr_t sa;
1637                 socklen_t salen = sizeof(sa);
1638
1639                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1640                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1641                         continue;
1642                 }
1643
1644                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1645                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1646                 }
1647         }
1648
1649         if(mesh->threadstarted) {
1650                 // Wait for the main thread to finish
1651                 pthread_mutex_unlock(&mesh->mutex);
1652                 pthread_join(mesh->thread, NULL);
1653                 pthread_mutex_lock(&mesh->mutex);
1654
1655                 mesh->threadstarted = false;
1656         }
1657
1658         // Close all metaconnections
1659         if(mesh->connections) {
1660                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1661                         next = node->next;
1662                         connection_t *c = node->data;
1663                         c->outgoing = NULL;
1664                         terminate_connection(mesh, c, false);
1665                 }
1666         }
1667
1668         exit_outgoings(mesh);
1669
1670         // Ensure we are considered unreachable
1671         if(mesh->nodes) {
1672                 graph(mesh);
1673         }
1674
1675         // Try to write out any changed node config files, ignore errors at this point.
1676         if(mesh->nodes) {
1677                 for splay_each(node_t, n, mesh->nodes) {
1678                         if(n->status.dirty) {
1679                                 n->status.dirty = !node_write_config(mesh, n);
1680                         }
1681                 }
1682         }
1683
1684         pthread_mutex_unlock(&mesh->mutex);
1685 }
1686
1687 void meshlink_close(meshlink_handle_t *mesh) {
1688         if(!mesh) {
1689                 meshlink_errno = MESHLINK_EINVAL;
1690                 return;
1691         }
1692
1693         // stop can be called even if mesh has not been started
1694         meshlink_stop(mesh);
1695
1696         // lock is not released after this
1697         pthread_mutex_lock(&mesh->mutex);
1698
1699         // Close and free all resources used.
1700
1701         close_network_connections(mesh);
1702
1703         logger(mesh, MESHLINK_INFO, "Terminating");
1704
1705         event_loop_exit(&mesh->loop);
1706
1707 #ifdef HAVE_MINGW
1708
1709         if(mesh->confbase) {
1710                 WSACleanup();
1711         }
1712
1713 #endif
1714
1715         ecdsa_free(mesh->invitation_key);
1716
1717         if(mesh->netns != -1) {
1718                 close(mesh->netns);
1719         }
1720
1721         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1722                 free(packet);
1723         }
1724
1725         meshlink_queue_exit(&mesh->outpacketqueue);
1726
1727         free(mesh->name);
1728         free(mesh->appname);
1729         free(mesh->confbase);
1730         free(mesh->config_key);
1731         ecdsa_free(mesh->private_key);
1732
1733         main_config_unlock(mesh);
1734
1735         pthread_mutex_unlock(&mesh->mutex);
1736         pthread_mutex_destroy(&mesh->mutex);
1737
1738         memset(mesh, 0, sizeof(*mesh));
1739
1740         free(mesh);
1741 }
1742
1743 bool meshlink_destroy(const char *confbase) {
1744         if(!confbase) {
1745                 meshlink_errno = MESHLINK_EINVAL;
1746                 return false;
1747         }
1748
1749         /* Exit early if the confbase directory itself doesn't exist */
1750         if(access(confbase, F_OK) && errno == ENOENT) {
1751                 return true;
1752         }
1753
1754         /* Take the lock the same way meshlink_open() would. */
1755         char lockfilename[PATH_MAX];
1756         snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1757
1758         FILE *lockfile = fopen(lockfilename, "w+");
1759
1760         if(!lockfile) {
1761                 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1762                 meshlink_errno = MESHLINK_ESTORAGE;
1763                 return false;
1764         }
1765
1766 #ifdef FD_CLOEXEC
1767         fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1768 #endif
1769
1770 #ifdef HAVE_MINGW
1771         // TODO: use _locking()?
1772 #else
1773
1774         if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1775                 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1776                 fclose(lockfile);
1777                 meshlink_errno = MESHLINK_EBUSY;
1778                 return false;
1779         }
1780
1781 #endif
1782
1783         if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1784                 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1785                 return false;
1786         }
1787
1788         if(unlink(lockfilename)) {
1789                 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1790                 fclose(lockfile);
1791                 meshlink_errno = MESHLINK_ESTORAGE;
1792                 return false;
1793         }
1794
1795         fclose(lockfile);
1796
1797         if(!sync_path(confbase)) {
1798                 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1799                 meshlink_errno = MESHLINK_ESTORAGE;
1800                 return false;
1801         }
1802
1803         return true;
1804 }
1805
1806 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1807         if(!mesh) {
1808                 meshlink_errno = MESHLINK_EINVAL;
1809                 return;
1810         }
1811
1812         pthread_mutex_lock(&mesh->mutex);
1813         mesh->receive_cb = cb;
1814         pthread_mutex_unlock(&mesh->mutex);
1815 }
1816
1817 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1818         if(!mesh) {
1819                 meshlink_errno = MESHLINK_EINVAL;
1820                 return;
1821         }
1822
1823         pthread_mutex_lock(&mesh->mutex);
1824         mesh->connection_try_cb = cb;
1825         pthread_mutex_unlock(&mesh->mutex);
1826 }
1827
1828 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1829         if(!mesh) {
1830                 meshlink_errno = MESHLINK_EINVAL;
1831                 return;
1832         }
1833
1834         pthread_mutex_lock(&mesh->mutex);
1835         mesh->node_status_cb = cb;
1836         pthread_mutex_unlock(&mesh->mutex);
1837 }
1838
1839 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1840         if(!mesh) {
1841                 meshlink_errno = MESHLINK_EINVAL;
1842                 return;
1843         }
1844
1845         pthread_mutex_lock(&mesh->mutex);
1846         mesh->node_pmtu_cb = cb;
1847         pthread_mutex_unlock(&mesh->mutex);
1848 }
1849
1850 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1851         if(!mesh) {
1852                 meshlink_errno = MESHLINK_EINVAL;
1853                 return;
1854         }
1855
1856         pthread_mutex_lock(&mesh->mutex);
1857         mesh->node_duplicate_cb = cb;
1858         pthread_mutex_unlock(&mesh->mutex);
1859 }
1860
1861 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1862         if(mesh) {
1863                 pthread_mutex_lock(&mesh->mutex);
1864                 mesh->log_cb = cb;
1865                 mesh->log_level = cb ? level : 0;
1866                 pthread_mutex_unlock(&mesh->mutex);
1867         } else {
1868                 global_log_cb = cb;
1869                 global_log_level = cb ? level : 0;
1870         }
1871 }
1872
1873 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1874         if(!mesh) {
1875                 meshlink_errno = MESHLINK_EINVAL;
1876                 return;
1877         }
1878
1879         pthread_mutex_lock(&mesh->mutex);
1880         mesh->error_cb = cb;
1881         pthread_mutex_unlock(&mesh->mutex);
1882 }
1883
1884 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1885         meshlink_packethdr_t *hdr;
1886
1887         // Validate arguments
1888         if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1889                 meshlink_errno = MESHLINK_EINVAL;
1890                 return false;
1891         }
1892
1893         if(!len) {
1894                 return true;
1895         }
1896
1897         if(!data) {
1898                 meshlink_errno = MESHLINK_EINVAL;
1899                 return false;
1900         }
1901
1902         node_t *n = (node_t *)destination;
1903
1904         if(n->status.blacklisted) {
1905                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1906                 meshlink_errno = MESHLINK_EBLACKLISTED;
1907                 return false;
1908         }
1909
1910         // Prepare the packet
1911         vpn_packet_t *packet = malloc(sizeof(*packet));
1912
1913         if(!packet) {
1914                 meshlink_errno = MESHLINK_ENOMEM;
1915                 return false;
1916         }
1917
1918         packet->probe = false;
1919         packet->tcp = false;
1920         packet->len = len + sizeof(*hdr);
1921
1922         hdr = (meshlink_packethdr_t *)packet->data;
1923         memset(hdr, 0, sizeof(*hdr));
1924         // leave the last byte as 0 to make sure strings are always
1925         // null-terminated if they are longer than the buffer
1926         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1927         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1928
1929         memcpy(packet->data + sizeof(*hdr), data, len);
1930
1931         // Queue it
1932         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1933                 free(packet);
1934                 meshlink_errno = MESHLINK_ENOMEM;
1935                 return false;
1936         }
1937
1938         // Notify event loop
1939         signal_trigger(&mesh->loop, &mesh->datafromapp);
1940
1941         return true;
1942 }
1943
1944 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1945         (void)loop;
1946         meshlink_handle_t *mesh = data;
1947         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1948
1949         if(!packet) {
1950                 return;
1951         }
1952
1953         mesh->self->in_packets++;
1954         mesh->self->in_bytes += packet->len;
1955         route(mesh, mesh->self, packet);
1956
1957         free(packet);
1958 }
1959
1960 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1961         if(!mesh || !destination) {
1962                 meshlink_errno = MESHLINK_EINVAL;
1963                 return -1;
1964         }
1965
1966         pthread_mutex_lock(&mesh->mutex);
1967
1968         node_t *n = (node_t *)destination;
1969
1970         if(!n->status.reachable) {
1971                 pthread_mutex_unlock(&mesh->mutex);
1972                 return 0;
1973
1974         } else if(n->mtuprobes > 30 && n->minmtu) {
1975                 pthread_mutex_unlock(&mesh->mutex);
1976                 return n->minmtu;
1977         } else {
1978                 pthread_mutex_unlock(&mesh->mutex);
1979                 return MTU;
1980         }
1981 }
1982
1983 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1984         if(!mesh || !node) {
1985                 meshlink_errno = MESHLINK_EINVAL;
1986                 return NULL;
1987         }
1988
1989         pthread_mutex_lock(&mesh->mutex);
1990
1991         node_t *n = (node_t *)node;
1992
1993         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1994                 meshlink_errno = MESHLINK_EINTERNAL;
1995                 pthread_mutex_unlock(&mesh->mutex);
1996                 return false;
1997         }
1998
1999         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2000
2001         if(!fingerprint) {
2002                 meshlink_errno = MESHLINK_EINTERNAL;
2003         }
2004
2005         pthread_mutex_unlock(&mesh->mutex);
2006         return fingerprint;
2007 }
2008
2009 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2010         if(!mesh) {
2011                 meshlink_errno = MESHLINK_EINVAL;
2012                 return NULL;
2013         }
2014
2015         return (meshlink_node_t *)mesh->self;
2016 }
2017
2018 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2019         if(!mesh || !name) {
2020                 meshlink_errno = MESHLINK_EINVAL;
2021                 return NULL;
2022         }
2023
2024         node_t *n = NULL;
2025
2026         pthread_mutex_lock(&mesh->mutex);
2027         n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2028         pthread_mutex_unlock(&mesh->mutex);
2029
2030         if(!n) {
2031                 meshlink_errno = MESHLINK_ENOENT;
2032         }
2033
2034         return (meshlink_node_t *)n;
2035 }
2036
2037 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2038         if(!mesh || !name) {
2039                 meshlink_errno = MESHLINK_EINVAL;
2040                 return NULL;
2041         }
2042
2043         meshlink_submesh_t *submesh = NULL;
2044
2045         pthread_mutex_lock(&mesh->mutex);
2046         submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2047         pthread_mutex_unlock(&mesh->mutex);
2048
2049         if(!submesh) {
2050                 meshlink_errno = MESHLINK_ENOENT;
2051         }
2052
2053         return submesh;
2054 }
2055
2056 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2057         if(!mesh || !nmemb || (*nmemb && !nodes)) {
2058                 meshlink_errno = MESHLINK_EINVAL;
2059                 return NULL;
2060         }
2061
2062         meshlink_node_t **result;
2063
2064         //lock mesh->nodes
2065         pthread_mutex_lock(&mesh->mutex);
2066
2067         *nmemb = mesh->nodes->count;
2068         result = realloc(nodes, *nmemb * sizeof(*nodes));
2069
2070         if(result) {
2071                 meshlink_node_t **p = result;
2072
2073                 for splay_each(node_t, n, mesh->nodes) {
2074                         *p++ = (meshlink_node_t *)n;
2075                 }
2076         } else {
2077                 *nmemb = 0;
2078                 free(nodes);
2079                 meshlink_errno = MESHLINK_ENOMEM;
2080         }
2081
2082         pthread_mutex_unlock(&mesh->mutex);
2083
2084         return result;
2085 }
2086
2087 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) {
2088         meshlink_node_t **result;
2089
2090         pthread_mutex_lock(&mesh->mutex);
2091
2092         *nmemb = 0;
2093
2094         for splay_each(node_t, n, mesh->nodes) {
2095                 if(search_node(n, condition)) {
2096                         ++*nmemb;
2097                 }
2098         }
2099
2100         if(*nmemb == 0) {
2101                 free(nodes);
2102                 pthread_mutex_unlock(&mesh->mutex);
2103                 return NULL;
2104         }
2105
2106         result = realloc(nodes, *nmemb * sizeof(*nodes));
2107
2108         if(result) {
2109                 meshlink_node_t **p = result;
2110
2111                 for splay_each(node_t, n, mesh->nodes) {
2112                         if(search_node(n, condition)) {
2113                                 *p++ = (meshlink_node_t *)n;
2114                         }
2115                 }
2116         } else {
2117                 *nmemb = 0;
2118                 free(nodes);
2119                 meshlink_errno = MESHLINK_ENOMEM;
2120         }
2121
2122         pthread_mutex_unlock(&mesh->mutex);
2123
2124         return result;
2125 }
2126
2127 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2128         dev_class_t *devclass = (dev_class_t *)condition;
2129
2130         if(*devclass == (dev_class_t)node->devclass) {
2131                 return true;
2132         }
2133
2134         return false;
2135 }
2136
2137 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2138         if(condition == node->submesh) {
2139                 return true;
2140         }
2141
2142         return false;
2143 }
2144
2145 struct time_range {
2146         time_t start;
2147         time_t end;
2148 };
2149
2150 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2151         const struct time_range *range = condition;
2152         time_t start = node->last_reachable;
2153         time_t end = node->last_unreachable;
2154
2155         if(end < start) {
2156                 end = time(NULL);
2157
2158                 if(end < start) {
2159                         start = end;
2160                 }
2161         }
2162
2163         if(range->end >= range->start) {
2164                 return start <= range->end && end >= range->start;
2165         } else {
2166                 return start > range->start || end < range->end;
2167         }
2168 }
2169
2170 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) {
2171         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2172                 meshlink_errno = MESHLINK_EINVAL;
2173                 return NULL;
2174         }
2175
2176         return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2177 }
2178
2179 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2180         if(!mesh || !submesh || !nmemb) {
2181                 meshlink_errno = MESHLINK_EINVAL;
2182                 return NULL;
2183         }
2184
2185         return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2186 }
2187
2188 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) {
2189         if(!mesh || !nmemb) {
2190                 meshlink_errno = MESHLINK_EINVAL;
2191                 return NULL;
2192         }
2193
2194         struct time_range range = {start, end};
2195
2196         return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2197 }
2198
2199 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2200         if(!mesh || !node) {
2201                 meshlink_errno = MESHLINK_EINVAL;
2202                 return -1;
2203         }
2204
2205         dev_class_t devclass;
2206
2207         pthread_mutex_lock(&mesh->mutex);
2208
2209         devclass = ((node_t *)node)->devclass;
2210
2211         pthread_mutex_unlock(&mesh->mutex);
2212
2213         return devclass;
2214 }
2215
2216 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2217         if(!mesh || !node) {
2218                 meshlink_errno = MESHLINK_EINVAL;
2219                 return NULL;
2220         }
2221
2222         node_t *n = (node_t *)node;
2223
2224         meshlink_submesh_t *s;
2225
2226         s = (meshlink_submesh_t *)n->submesh;
2227
2228         return s;
2229 }
2230
2231 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2232         if(!mesh || !node) {
2233                 meshlink_errno = MESHLINK_EINVAL;
2234                 return NULL;
2235         }
2236
2237         node_t *n = (node_t *)node;
2238         bool reachable;
2239
2240         pthread_mutex_lock(&mesh->mutex);
2241         reachable = n->status.reachable && !n->status.blacklisted;
2242
2243         if(last_reachable) {
2244                 *last_reachable = n->last_reachable;
2245         }
2246
2247         if(last_unreachable) {
2248                 *last_unreachable = n->last_unreachable;
2249         }
2250
2251         pthread_mutex_unlock(&mesh->mutex);
2252
2253         return reachable;
2254 }
2255
2256 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2257         if(!mesh || !data || !len || !signature || !siglen) {
2258                 meshlink_errno = MESHLINK_EINVAL;
2259                 return false;
2260         }
2261
2262         if(*siglen < MESHLINK_SIGLEN) {
2263                 meshlink_errno = MESHLINK_EINVAL;
2264                 return false;
2265         }
2266
2267         pthread_mutex_lock(&mesh->mutex);
2268
2269         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2270                 meshlink_errno = MESHLINK_EINTERNAL;
2271                 pthread_mutex_unlock(&mesh->mutex);
2272                 return false;
2273         }
2274
2275         *siglen = MESHLINK_SIGLEN;
2276         pthread_mutex_unlock(&mesh->mutex);
2277         return true;
2278 }
2279
2280 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2281         if(!mesh || !source || !data || !len || !signature) {
2282                 meshlink_errno = MESHLINK_EINVAL;
2283                 return false;
2284         }
2285
2286         if(siglen != MESHLINK_SIGLEN) {
2287                 meshlink_errno = MESHLINK_EINVAL;
2288                 return false;
2289         }
2290
2291         pthread_mutex_lock(&mesh->mutex);
2292
2293         bool rval = false;
2294
2295         struct node_t *n = (struct node_t *)source;
2296
2297         if(!node_read_public_key(mesh, n)) {
2298                 meshlink_errno = MESHLINK_EINTERNAL;
2299                 rval = false;
2300         } else {
2301                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2302         }
2303
2304         pthread_mutex_unlock(&mesh->mutex);
2305         return rval;
2306 }
2307
2308 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2309         pthread_mutex_lock(&mesh->mutex);
2310
2311         size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2312
2313         if(!count) {
2314                 // TODO: Update invitation key if necessary?
2315         }
2316
2317         pthread_mutex_unlock(&mesh->mutex);
2318
2319         return mesh->invitation_key;
2320 }
2321
2322 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2323         if(!mesh || !node || !address) {
2324                 meshlink_errno = MESHLINK_EINVAL;
2325                 return false;
2326         }
2327
2328         if(!is_valid_hostname(address)) {
2329                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2330                 meshlink_errno = MESHLINK_EINVAL;
2331                 return false;
2332         }
2333
2334         if(port && !is_valid_port(port)) {
2335                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2336                 meshlink_errno = MESHLINK_EINVAL;
2337                 return false;
2338         }
2339
2340         char *canonical_address;
2341
2342         if(port) {
2343                 xasprintf(&canonical_address, "%s %s", address, port);
2344         } else {
2345                 canonical_address = xstrdup(address);
2346         }
2347
2348         pthread_mutex_lock(&mesh->mutex);
2349
2350         node_t *n = (node_t *)node;
2351         free(n->canonical_address);
2352         n->canonical_address = canonical_address;
2353
2354         if(!node_write_config(mesh, n)) {
2355                 pthread_mutex_unlock(&mesh->mutex);
2356                 return false;
2357         }
2358
2359         pthread_mutex_unlock(&mesh->mutex);
2360
2361         return config_sync(mesh, "current");
2362 }
2363
2364 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2365         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2366 }
2367
2368 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2369         if(!mesh) {
2370                 meshlink_errno = MESHLINK_EINVAL;
2371                 return false;
2372         }
2373
2374         char *address = meshlink_get_external_address(mesh);
2375
2376         if(!address) {
2377                 return false;
2378         }
2379
2380         bool rval = meshlink_add_address(mesh, address);
2381         free(address);
2382
2383         return rval;
2384 }
2385
2386 int meshlink_get_port(meshlink_handle_t *mesh) {
2387         if(!mesh) {
2388                 meshlink_errno = MESHLINK_EINVAL;
2389                 return -1;
2390         }
2391
2392         if(!mesh->myport) {
2393                 meshlink_errno = MESHLINK_EINTERNAL;
2394                 return -1;
2395         }
2396
2397         int port;
2398
2399         pthread_mutex_lock(&mesh->mutex);
2400         port = atoi(mesh->myport);
2401         pthread_mutex_unlock(&mesh->mutex);
2402
2403         return port;
2404 }
2405
2406 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2407         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2408                 meshlink_errno = MESHLINK_EINVAL;
2409                 return false;
2410         }
2411
2412         if(mesh->myport && port == atoi(mesh->myport)) {
2413                 return true;
2414         }
2415
2416         if(!try_bind(port)) {
2417                 meshlink_errno = MESHLINK_ENETWORK;
2418                 return false;
2419         }
2420
2421         devtool_trybind_probe();
2422
2423         bool rval = false;
2424
2425         pthread_mutex_lock(&mesh->mutex);
2426
2427         if(mesh->threadstarted) {
2428                 meshlink_errno = MESHLINK_EINVAL;
2429                 goto done;
2430         }
2431
2432         free(mesh->myport);
2433         xasprintf(&mesh->myport, "%d", port);
2434
2435         /* Close down the network. This also deletes mesh->self. */
2436         close_network_connections(mesh);
2437
2438         /* Recreate mesh->self. */
2439         mesh->self = new_node();
2440         mesh->self->name = xstrdup(mesh->name);
2441         mesh->self->devclass = mesh->devclass;
2442         mesh->self->session_id = mesh->session_id;
2443         xasprintf(&mesh->myport, "%d", port);
2444
2445         if(!node_read_public_key(mesh, mesh->self)) {
2446                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2447                 meshlink_errno = MESHLINK_ESTORAGE;
2448                 free_node(mesh->self);
2449                 mesh->self = NULL;
2450                 goto done;
2451         } else if(!setup_network(mesh)) {
2452                 meshlink_errno = MESHLINK_ENETWORK;
2453                 goto done;
2454         }
2455
2456         /* Rebuild our own list of recent addresses */
2457         memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2458         add_local_addresses(mesh);
2459
2460         /* Write meshlink.conf with the updated port number */
2461         write_main_config_files(mesh);
2462
2463         rval = config_sync(mesh, "current");
2464
2465 done:
2466         pthread_mutex_unlock(&mesh->mutex);
2467
2468         return rval && meshlink_get_port(mesh) == port;
2469 }
2470
2471 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2472         mesh->invitation_timeout = timeout;
2473 }
2474
2475 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2476         meshlink_submesh_t *s = NULL;
2477
2478         if(!mesh) {
2479                 meshlink_errno = MESHLINK_EINVAL;
2480                 return NULL;
2481         }
2482
2483         if(submesh) {
2484                 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2485
2486                 if(s != submesh) {
2487                         logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2488                         meshlink_errno = MESHLINK_EINVAL;
2489                         return NULL;
2490                 }
2491         } else {
2492                 s = (meshlink_submesh_t *)mesh->self->submesh;
2493         }
2494
2495         pthread_mutex_lock(&mesh->mutex);
2496
2497         // Check validity of the new node's name
2498         if(!check_id(name)) {
2499                 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2500                 meshlink_errno = MESHLINK_EINVAL;
2501                 pthread_mutex_unlock(&mesh->mutex);
2502                 return NULL;
2503         }
2504
2505         // Ensure no host configuration file with that name exists
2506         if(config_exists(mesh, "current", name)) {
2507                 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2508                 meshlink_errno = MESHLINK_EEXIST;
2509                 pthread_mutex_unlock(&mesh->mutex);
2510                 return NULL;
2511         }
2512
2513         // Ensure no other nodes know about this name
2514         if(lookup_node(mesh, name)) {
2515                 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2516                 meshlink_errno = MESHLINK_EEXIST;
2517                 pthread_mutex_unlock(&mesh->mutex);
2518                 return NULL;
2519         }
2520
2521         // Get the local address
2522         char *address = get_my_hostname(mesh, flags);
2523
2524         if(!address) {
2525                 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2526                 meshlink_errno = MESHLINK_ERESOLV;
2527                 pthread_mutex_unlock(&mesh->mutex);
2528                 return NULL;
2529         }
2530
2531         if(!refresh_invitation_key(mesh)) {
2532                 meshlink_errno = MESHLINK_EINTERNAL;
2533                 pthread_mutex_unlock(&mesh->mutex);
2534                 return NULL;
2535         }
2536
2537         // If we changed our own host config file, write it out now
2538         if(mesh->self->status.dirty) {
2539                 if(!node_write_config(mesh, mesh->self)) {
2540                         logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2541                         pthread_mutex_unlock(&mesh->mutex);
2542                         return NULL;
2543                 }
2544         }
2545
2546         char hash[64];
2547
2548         // Create a hash of the key.
2549         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2550         sha512(fingerprint, strlen(fingerprint), hash);
2551         b64encode_urlsafe(hash, hash, 18);
2552
2553         // Create a random cookie for this invitation.
2554         char cookie[25];
2555         randomize(cookie, 18);
2556
2557         // Create a filename that doesn't reveal the cookie itself
2558         char buf[18 + strlen(fingerprint)];
2559         char cookiehash[64];
2560         memcpy(buf, cookie, 18);
2561         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2562         sha512(buf, sizeof(buf), cookiehash);
2563         b64encode_urlsafe(cookiehash, cookiehash, 18);
2564
2565         b64encode_urlsafe(cookie, cookie, 18);
2566
2567         free(fingerprint);
2568
2569         /* Construct the invitation file */
2570         uint8_t outbuf[4096];
2571         packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2572
2573         packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2574         packmsg_add_str(&inv, name);
2575         packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2576         packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2577
2578         /* TODO: Add several host config files to bootstrap connections.
2579          * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2580          * and are not blacklisted.
2581          */
2582         config_t configs[5];
2583         memset(configs, 0, sizeof(configs));
2584         int count = 0;
2585
2586         if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2587                 count++;
2588         }
2589
2590         /* Append host config files to the invitation file */
2591         packmsg_add_array(&inv, count);
2592
2593         for(int i = 0; i < count; i++) {
2594                 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2595                 config_free(&configs[i]);
2596         }
2597
2598         config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2599
2600         if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2601                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2602                 meshlink_errno = MESHLINK_ESTORAGE;
2603                 pthread_mutex_unlock(&mesh->mutex);
2604                 return NULL;
2605         }
2606
2607         // Create an URL from the local address, key hash and cookie
2608         char *url;
2609         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2610         free(address);
2611
2612         pthread_mutex_unlock(&mesh->mutex);
2613         return url;
2614 }
2615
2616 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2617         return meshlink_invite_ex(mesh, submesh, name, 0);
2618 }
2619
2620 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2621         if(!mesh || !invitation) {
2622                 meshlink_errno = MESHLINK_EINVAL;
2623                 return false;
2624         }
2625
2626         join_state_t state = {
2627                 .mesh = mesh,
2628                 .sock = -1,
2629         };
2630
2631         ecdsa_t *key = NULL;
2632         ecdsa_t *hiskey = NULL;
2633
2634         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2635         char copy[strlen(invitation) + 1];
2636
2637         pthread_mutex_lock(&mesh->mutex);
2638
2639         //Before doing meshlink_join make sure we are not connected to another mesh
2640         if(mesh->threadstarted) {
2641                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2642                 meshlink_errno = MESHLINK_EINVAL;
2643                 goto exit;
2644         }
2645
2646         // 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.
2647         if(mesh->nodes->count > 1) {
2648                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2649                 meshlink_errno = MESHLINK_EINVAL;
2650                 goto exit;
2651         }
2652
2653         strcpy(copy, invitation);
2654
2655         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2656
2657         char *slash = strchr(copy, '/');
2658
2659         if(!slash) {
2660                 goto invalid;
2661         }
2662
2663         *slash++ = 0;
2664
2665         if(strlen(slash) != 48) {
2666                 goto invalid;
2667         }
2668
2669         char *address = copy;
2670         char *port = NULL;
2671
2672         if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2673                 goto invalid;
2674         }
2675
2676         if(mesh->inviter_commits_first) {
2677                 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2678         }
2679
2680         // Generate a throw-away key for the invitation.
2681         key = ecdsa_generate();
2682
2683         if(!key) {
2684                 meshlink_errno = MESHLINK_EINTERNAL;
2685                 goto exit;
2686         }
2687
2688         char *b64key = ecdsa_get_base64_public_key(key);
2689         char *comma;
2690
2691         while(address && *address) {
2692                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2693                 comma = strchr(address, ',');
2694
2695                 if(comma) {
2696                         *comma++ = 0;
2697                 }
2698
2699                 // Split of the port
2700                 port = strrchr(address, ':');
2701
2702                 if(!port) {
2703                         goto invalid;
2704                 }
2705
2706                 *port++ = 0;
2707
2708                 // IPv6 address are enclosed in brackets, per RFC 3986
2709                 if(*address == '[') {
2710                         address++;
2711                         char *bracket = strchr(address, ']');
2712
2713                         if(!bracket) {
2714                                 goto invalid;
2715                         }
2716
2717                         *bracket++ = 0;
2718
2719                         if(*bracket) {
2720                                 goto invalid;
2721                         }
2722                 }
2723
2724                 // Connect to the meshlink daemon mentioned in the URL.
2725                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2726
2727                 if(ai) {
2728                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2729                                 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2730
2731                                 if(state.sock == -1) {
2732                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2733                                         meshlink_errno = MESHLINK_ENETWORK;
2734                                         continue;
2735                                 }
2736
2737                                 set_timeout(state.sock, 5000);
2738
2739                                 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2740                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2741                                         meshlink_errno = MESHLINK_ENETWORK;
2742                                         closesocket(state.sock);
2743                                         state.sock = -1;
2744                                         continue;
2745                                 }
2746                         }
2747
2748                         freeaddrinfo(ai);
2749                 } else {
2750                         meshlink_errno = MESHLINK_ERESOLV;
2751                 }
2752
2753                 if(state.sock != -1 || !comma) {
2754                         break;
2755                 }
2756
2757                 address = comma;
2758         }
2759
2760         if(state.sock == -1) {
2761                 goto exit;
2762         }
2763
2764         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2765
2766         // Tell him we have an invitation, and give him our throw-away key.
2767
2768         state.blen = 0;
2769
2770         if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2771                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2772                 meshlink_errno = MESHLINK_ENETWORK;
2773                 goto exit;
2774         }
2775
2776         free(b64key);
2777
2778         char hisname[4096] = "";
2779         int code, hismajor, hisminor = 0;
2780
2781         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) {
2782                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2783                 meshlink_errno = MESHLINK_ENETWORK;
2784                 goto exit;
2785         }
2786
2787         // Check if the hash of the key he gave us matches the hash in the URL.
2788         char *fingerprint = state.line + 2;
2789         char hishash[64];
2790
2791         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2792                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2793                 meshlink_errno = MESHLINK_EINTERNAL;
2794                 goto exit;
2795         }
2796
2797         if(memcmp(hishash, state.hash, 18)) {
2798                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2799                 meshlink_errno = MESHLINK_EPEER;
2800                 goto exit;
2801         }
2802
2803         hiskey = ecdsa_set_base64_public_key(fingerprint);
2804
2805         if(!hiskey) {
2806                 meshlink_errno = MESHLINK_EINTERNAL;
2807                 goto exit;
2808         }
2809
2810         // Start an SPTPS session
2811         if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2812                 meshlink_errno = MESHLINK_EINTERNAL;
2813                 goto exit;
2814         }
2815
2816         // Feed rest of input buffer to SPTPS
2817         if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2818                 meshlink_errno = MESHLINK_EPEER;
2819                 goto exit;
2820         }
2821
2822         ssize_t len;
2823         logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2824
2825         while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2826                 if(len < 0) {
2827                         if(errno == EINTR) {
2828                                 continue;
2829                         }
2830
2831                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2832                         meshlink_errno = MESHLINK_ENETWORK;
2833                         goto exit;
2834                 }
2835
2836                 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2837                         meshlink_errno = MESHLINK_EPEER;
2838                         goto exit;
2839                 }
2840         }
2841
2842         if(!state.success) {
2843                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2844                 meshlink_errno = MESHLINK_EPEER;
2845                 goto exit;
2846         }
2847
2848         sptps_stop(&state.sptps);
2849         ecdsa_free(hiskey);
2850         ecdsa_free(key);
2851         closesocket(state.sock);
2852
2853         pthread_mutex_unlock(&mesh->mutex);
2854         return true;
2855
2856 invalid:
2857         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2858         meshlink_errno = MESHLINK_EINVAL;
2859 exit:
2860         sptps_stop(&state.sptps);
2861         ecdsa_free(hiskey);
2862         ecdsa_free(key);
2863
2864         if(state.sock != -1) {
2865                 closesocket(state.sock);
2866         }
2867
2868         pthread_mutex_unlock(&mesh->mutex);
2869         return false;
2870 }
2871
2872 char *meshlink_export(meshlink_handle_t *mesh) {
2873         if(!mesh) {
2874                 meshlink_errno = MESHLINK_EINVAL;
2875                 return NULL;
2876         }
2877
2878         // Create a config file on the fly.
2879
2880         uint8_t buf[4096];
2881         packmsg_output_t out = {buf, sizeof(buf)};
2882         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2883         packmsg_add_str(&out, mesh->name);
2884         packmsg_add_str(&out, CORE_MESH);
2885
2886         pthread_mutex_lock(&mesh->mutex);
2887
2888         packmsg_add_int32(&out, mesh->self->devclass);
2889         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2890         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2891         packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2892
2893         uint32_t count = 0;
2894
2895         for(uint32_t i = 0; i < MAX_RECENT; i++) {
2896                 if(mesh->self->recent[i].sa.sa_family) {
2897                         count++;
2898                 } else {
2899                         break;
2900                 }
2901         }
2902
2903         packmsg_add_array(&out, count);
2904
2905         for(uint32_t i = 0; i < count; i++) {
2906                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2907         }
2908
2909         packmsg_add_int64(&out, 0);
2910         packmsg_add_int64(&out, 0);
2911
2912         pthread_mutex_unlock(&mesh->mutex);
2913
2914         if(!packmsg_output_ok(&out)) {
2915                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2916                 meshlink_errno = MESHLINK_EINTERNAL;
2917                 return NULL;
2918         }
2919
2920         // Prepare a base64-encoded packmsg array containing our config file
2921
2922         uint32_t len = packmsg_output_size(&out, buf);
2923         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2924         uint8_t *buf2 = xmalloc(len2);
2925         packmsg_output_t out2 = {buf2, len2};
2926         packmsg_add_array(&out2, 1);
2927         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2928
2929         if(!packmsg_output_ok(&out2)) {
2930                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2931                 meshlink_errno = MESHLINK_EINTERNAL;
2932                 free(buf2);
2933                 return NULL;
2934         }
2935
2936         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2937
2938         return (char *)buf2;
2939 }
2940
2941 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2942         if(!mesh || !data) {
2943                 meshlink_errno = MESHLINK_EINVAL;
2944                 return false;
2945         }
2946
2947         size_t datalen = strlen(data);
2948         uint8_t *buf = xmalloc(datalen);
2949         int buflen = b64decode(data, buf, datalen);
2950
2951         if(!buflen) {
2952                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2953                 meshlink_errno = MESHLINK_EPEER;
2954                 return false;
2955         }
2956
2957         packmsg_input_t in = {buf, buflen};
2958         uint32_t count = packmsg_get_array(&in);
2959
2960         if(!count) {
2961                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2962                 meshlink_errno = MESHLINK_EPEER;
2963                 return false;
2964         }
2965
2966         pthread_mutex_lock(&mesh->mutex);
2967
2968         while(count--) {
2969                 const void *data;
2970                 uint32_t len = packmsg_get_bin_raw(&in, &data);
2971
2972                 if(!len) {
2973                         break;
2974                 }
2975
2976                 packmsg_input_t in2 = {data, len};
2977                 uint32_t version = packmsg_get_uint32(&in2);
2978                 char *name = packmsg_get_str_dup(&in2);
2979
2980                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2981                         free(name);
2982                         packmsg_input_invalidate(&in);
2983                         break;
2984                 }
2985
2986                 if(!check_id(name)) {
2987                         free(name);
2988                         break;
2989                 }
2990
2991                 node_t *n = lookup_node(mesh, name);
2992
2993                 if(n) {
2994                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2995                         free(name);
2996                         continue;
2997                 }
2998
2999                 n = new_node();
3000                 n->name = name;
3001
3002                 config_t config = {data, len};
3003
3004                 if(!node_read_from_config(mesh, n, &config)) {
3005                         free_node(n);
3006                         packmsg_input_invalidate(&in);
3007                         break;
3008                 }
3009
3010                 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3011                 n->last_reachable = 0;
3012                 n->last_unreachable = 0;
3013
3014                 if(!node_write_config(mesh, n)) {
3015                         free_node(n);
3016                         return false;
3017                 }
3018
3019                 node_add(mesh, n);
3020         }
3021
3022         pthread_mutex_unlock(&mesh->mutex);
3023
3024         free(buf);
3025
3026         if(!packmsg_done(&in)) {
3027                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3028                 meshlink_errno = MESHLINK_EPEER;
3029                 return false;
3030         }
3031
3032         if(!config_sync(mesh, "current")) {
3033                 return false;
3034         }
3035
3036         return true;
3037 }
3038
3039 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3040         if(n == mesh->self) {
3041                 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3042                 meshlink_errno = MESHLINK_EINVAL;
3043                 return false;
3044         }
3045
3046         if(n->status.blacklisted) {
3047                 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3048                 return true;
3049         }
3050
3051         n->status.blacklisted = true;
3052
3053         /* Immediately shut down any connections we have with the blacklisted node.
3054          * We can't call terminate_connection(), because we might be called from a callback function.
3055          */
3056         for list_each(connection_t, c, mesh->connections) {
3057                 if(c->node == n) {
3058                         shutdown(c->socket, SHUT_RDWR);
3059                 }
3060         }
3061
3062         utcp_abort_all_connections(n->utcp);
3063
3064         n->mtu = 0;
3065         n->minmtu = 0;
3066         n->maxmtu = MTU;
3067         n->mtuprobes = 0;
3068         n->status.udp_confirmed = false;
3069
3070         if(n->status.reachable) {
3071                 n->last_unreachable = mesh->loop.now.tv_sec;
3072         }
3073
3074         /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3075          * manually call the status callback if necessary.
3076          */
3077         if(n->status.reachable && mesh->node_status_cb) {
3078                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3079         }
3080
3081         return node_write_config(mesh, n) && config_sync(mesh, "current");
3082 }
3083
3084 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3085         if(!mesh || !node) {
3086                 meshlink_errno = MESHLINK_EINVAL;
3087                 return false;
3088         }
3089
3090         pthread_mutex_lock(&mesh->mutex);
3091
3092         if(!blacklist(mesh, (node_t *)node)) {
3093                 pthread_mutex_unlock(&mesh->mutex);
3094                 return false;
3095         }
3096
3097         pthread_mutex_unlock(&mesh->mutex);
3098
3099         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3100         return true;
3101 }
3102
3103 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3104         if(!mesh || !name) {
3105                 meshlink_errno = MESHLINK_EINVAL;
3106                 return false;
3107         }
3108
3109         pthread_mutex_lock(&mesh->mutex);
3110
3111         node_t *n = lookup_node(mesh, (char *)name);
3112
3113         if(!n) {
3114                 n = new_node();
3115                 n->name = xstrdup(name);
3116                 node_add(mesh, n);
3117         }
3118
3119         if(!blacklist(mesh, (node_t *)n)) {
3120                 pthread_mutex_unlock(&mesh->mutex);
3121                 return false;
3122         }
3123
3124         pthread_mutex_unlock(&mesh->mutex);
3125
3126         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3127         return true;
3128 }
3129
3130 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3131         if(n == mesh->self) {
3132                 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3133                 meshlink_errno = MESHLINK_EINVAL;
3134                 return false;
3135         }
3136
3137         if(!n->status.blacklisted) {
3138                 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3139                 return true;
3140         }
3141
3142         n->status.blacklisted = false;
3143
3144         if(n->status.reachable) {
3145                 n->last_reachable = mesh->loop.now.tv_sec;
3146                 update_node_status(mesh, n);
3147         }
3148
3149         return node_write_config(mesh, n) && config_sync(mesh, "current");
3150 }
3151
3152 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3153         if(!mesh || !node) {
3154                 meshlink_errno = MESHLINK_EINVAL;
3155                 return false;
3156         }
3157
3158         pthread_mutex_lock(&mesh->mutex);
3159
3160         if(!whitelist(mesh, (node_t *)node)) {
3161                 pthread_mutex_unlock(&mesh->mutex);
3162                 return false;
3163         }
3164
3165         pthread_mutex_unlock(&mesh->mutex);
3166
3167         logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3168         return true;
3169 }
3170
3171 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3172         if(!mesh || !name) {
3173                 meshlink_errno = MESHLINK_EINVAL;
3174                 return false;
3175         }
3176
3177         pthread_mutex_lock(&mesh->mutex);
3178
3179         node_t *n = lookup_node(mesh, (char *)name);
3180
3181         if(!n) {
3182                 n = new_node();
3183                 n->name = xstrdup(name);
3184                 node_add(mesh, n);
3185         }
3186
3187         if(!whitelist(mesh, (node_t *)n)) {
3188                 pthread_mutex_unlock(&mesh->mutex);
3189                 return false;
3190         }
3191
3192         pthread_mutex_unlock(&mesh->mutex);
3193
3194         logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3195         return true;
3196 }
3197
3198 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3199         mesh->default_blacklist = blacklist;
3200 }
3201
3202 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3203         if(!mesh || !node) {
3204                 meshlink_errno = MESHLINK_EINVAL;
3205                 return false;
3206         }
3207
3208         node_t *n = (node_t *)node;
3209
3210         pthread_mutex_lock(&mesh->mutex);
3211
3212         /* Check that the node is not reachable */
3213         if(n->status.reachable || n->connection) {
3214                 pthread_mutex_unlock(&mesh->mutex);
3215                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3216                 return false;
3217         }
3218
3219         /* Check that we don't have any active UTCP connections */
3220         if(n->utcp && utcp_is_active(n->utcp)) {
3221                 pthread_mutex_unlock(&mesh->mutex);
3222                 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3223                 return false;
3224         }
3225
3226         /* Check that we have no active connections to this node */
3227         for list_each(connection_t, c, mesh->connections) {
3228                 if(c->node == n) {
3229                         pthread_mutex_unlock(&mesh->mutex);
3230                         logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3231                         return false;
3232                 }
3233         }
3234
3235         /* Remove any pending outgoings to this node */
3236         if(mesh->outgoings) {
3237                 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3238                         if(outgoing->node == n) {
3239                                 list_delete_node(mesh->outgoings, node);
3240                         }
3241                 }
3242         }
3243
3244         /* Delete the config file for this node */
3245         if(!config_delete(mesh, "current", n->name)) {
3246                 pthread_mutex_unlock(&mesh->mutex);
3247                 return false;
3248         }
3249
3250         /* Delete the node struct and any remaining edges referencing this node */
3251         node_del(mesh, n);
3252
3253         pthread_mutex_unlock(&mesh->mutex);
3254
3255         return config_sync(mesh, "current");
3256 }
3257
3258 /* Hint that a hostname may be found at an address
3259  * See header file for detailed comment.
3260  */
3261 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3262         if(!mesh || !node || !addr) {
3263                 meshlink_errno = EINVAL;
3264                 return;
3265         }
3266
3267         pthread_mutex_lock(&mesh->mutex);
3268
3269         node_t *n = (node_t *)node;
3270
3271         if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3272                 if(!node_write_config(mesh, n)) {
3273                         logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3274                 }
3275         }
3276
3277         pthread_mutex_unlock(&mesh->mutex);
3278         // @TODO do we want to fire off a connection attempt right away?
3279 }
3280
3281 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3282         (void)port;
3283         node_t *n = utcp->priv;
3284         meshlink_handle_t *mesh = n->mesh;
3285         return mesh->channel_accept_cb;
3286 }
3287
3288 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3289         if(aio->data) {
3290                 if(aio->cb.buffer) {
3291                         aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3292                 }
3293         } else {
3294                 if(aio->cb.fd) {
3295                         aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3296                 }
3297         }
3298 }
3299
3300 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3301         meshlink_channel_t *channel = connection->priv;
3302
3303         if(!channel) {
3304                 abort();
3305         }
3306
3307         node_t *n = channel->node;
3308         meshlink_handle_t *mesh = n->mesh;
3309
3310         if(n->status.destroyed) {
3311                 meshlink_channel_close(mesh, channel);
3312                 return len;
3313         }
3314
3315         const char *p = data;
3316         size_t left = len;
3317
3318         while(channel->aio_receive) {
3319                 meshlink_aio_buffer_t *aio = channel->aio_receive;
3320                 size_t todo = aio->len - aio->done;
3321
3322                 if(todo > left) {
3323                         todo = left;
3324                 }
3325
3326                 if(aio->data) {
3327                         memcpy((char *)aio->data + aio->done, p, todo);
3328                 } else {
3329                         ssize_t result = write(aio->fd, p, todo);
3330
3331                         if(result > 0) {
3332                                 todo = result;
3333                         }
3334                 }
3335
3336                 aio->done += todo;
3337
3338                 if(aio->done == aio->len) {
3339                         channel->aio_receive = aio->next;
3340                         aio_signal(mesh, channel, aio);
3341                         free(aio);
3342                 }
3343
3344                 p += todo;
3345                 left -= todo;
3346
3347                 if(!left && len) {
3348                         return len;
3349                 }
3350         }
3351
3352         if(channel->receive_cb) {
3353                 channel->receive_cb(mesh, channel, p, left);
3354         }
3355
3356         return len;
3357 }
3358
3359 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3360         node_t *n = utcp_connection->utcp->priv;
3361
3362         if(!n) {
3363                 abort();
3364         }
3365
3366         meshlink_handle_t *mesh = n->mesh;
3367
3368         if(!mesh->channel_accept_cb) {
3369                 return;
3370         }
3371
3372         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3373         channel->node = n;
3374         channel->c = utcp_connection;
3375
3376         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3377                 utcp_accept(utcp_connection, channel_recv, channel);
3378         } else {
3379                 free(channel);
3380         }
3381 }
3382
3383 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3384         node_t *n = utcp->priv;
3385
3386         if(n->status.destroyed) {
3387                 return -1;
3388         }
3389
3390         meshlink_handle_t *mesh = n->mesh;
3391         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3392 }
3393
3394 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3395         if(!mesh || !channel) {
3396                 meshlink_errno = MESHLINK_EINVAL;
3397                 return;
3398         }
3399
3400         channel->receive_cb = cb;
3401 }
3402
3403 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3404         (void)mesh;
3405         node_t *n = (node_t *)source;
3406
3407         if(!n->utcp) {
3408                 abort();
3409         }
3410
3411         utcp_recv(n->utcp, data, len);
3412 }
3413
3414 static void channel_poll(struct utcp_connection *connection, size_t len) {
3415         meshlink_channel_t *channel = connection->priv;
3416
3417         if(!channel) {
3418                 abort();
3419         }
3420
3421         node_t *n = channel->node;
3422         meshlink_handle_t *mesh = n->mesh;
3423         meshlink_aio_buffer_t *aio = channel->aio_send;
3424
3425         if(aio) {
3426                 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3427                 size_t left = aio->len - aio->done;
3428                 ssize_t sent;
3429
3430                 if(len > left) {
3431                         len = left;
3432                 }
3433
3434                 if(aio->data) {
3435                         sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3436                 } else {
3437                         char buf[65536];
3438                         size_t todo = utcp_get_sndbuf_free(connection);
3439
3440                         if(todo > left) {
3441                                 todo = left;
3442                         }
3443
3444                         if(todo > sizeof(buf)) {
3445                                 todo = sizeof(buf);
3446                         }
3447
3448                         ssize_t result = read(aio->fd, buf, todo);
3449
3450                         if(result > 0) {
3451                                 sent = utcp_send(connection, buf, result);
3452                         } else {
3453                                 sent = result;
3454                         }
3455                 }
3456
3457                 if(sent >= 0) {
3458                         aio->done += sent;
3459                 }
3460
3461                 /* If the buffer is now completely sent, call the callback and dispose of it. */
3462                 if(aio->done >= aio->len) {
3463                         channel->aio_send = aio->next;
3464                         aio_signal(mesh, channel, aio);
3465                         free(aio);
3466                 }
3467         } else {
3468                 if(channel->poll_cb) {
3469                         channel->poll_cb(mesh, channel, len);
3470                 } else {
3471                         utcp_set_poll_cb(connection, NULL);
3472                 }
3473         }
3474 }
3475
3476 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3477         if(!mesh || !channel) {
3478                 meshlink_errno = MESHLINK_EINVAL;
3479                 return;
3480         }
3481
3482         pthread_mutex_lock(&mesh->mutex);
3483         channel->poll_cb = cb;
3484         utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3485         pthread_mutex_unlock(&mesh->mutex);
3486 }
3487
3488 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3489         if(!mesh) {
3490                 meshlink_errno = MESHLINK_EINVAL;
3491                 return;
3492         }
3493
3494         pthread_mutex_lock(&mesh->mutex);
3495         mesh->channel_accept_cb = cb;
3496         mesh->receive_cb = channel_receive;
3497
3498         for splay_each(node_t, n, mesh->nodes) {
3499                 if(!n->utcp && n != mesh->self) {
3500                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3501                 }
3502         }
3503
3504         pthread_mutex_unlock(&mesh->mutex);
3505 }
3506
3507 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3508         (void)mesh;
3509
3510         if(!channel) {
3511                 meshlink_errno = MESHLINK_EINVAL;
3512                 return;
3513         }
3514
3515         pthread_mutex_lock(&mesh->mutex);
3516         utcp_set_sndbuf(channel->c, size);
3517         pthread_mutex_unlock(&mesh->mutex);
3518 }
3519
3520 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3521         (void)mesh;
3522
3523         if(!channel) {
3524                 meshlink_errno = MESHLINK_EINVAL;
3525                 return;
3526         }
3527
3528         pthread_mutex_lock(&mesh->mutex);
3529         utcp_set_rcvbuf(channel->c, size);
3530         pthread_mutex_unlock(&mesh->mutex);
3531 }
3532
3533 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) {
3534         if(data && len) {
3535                 abort();        // TODO: handle non-NULL data
3536         }
3537
3538         if(!mesh || !node) {
3539                 meshlink_errno = MESHLINK_EINVAL;
3540                 return NULL;
3541         }
3542
3543         pthread_mutex_lock(&mesh->mutex);
3544
3545         node_t *n = (node_t *)node;
3546
3547         if(!n->utcp) {
3548                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3549                 mesh->receive_cb = channel_receive;
3550
3551                 if(!n->utcp) {
3552                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3553                         pthread_mutex_unlock(&mesh->mutex);
3554                         return NULL;
3555                 }
3556         }
3557
3558         if(n->status.blacklisted) {
3559                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3560                 meshlink_errno = MESHLINK_EBLACKLISTED;
3561                 pthread_mutex_unlock(&mesh->mutex);
3562                 return NULL;
3563         }
3564
3565         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3566         channel->node = n;
3567         channel->receive_cb = cb;
3568
3569         if(data && !len) {
3570                 channel->priv = (void *)data;
3571         }
3572
3573         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3574
3575         pthread_mutex_unlock(&mesh->mutex);
3576
3577         if(!channel->c) {
3578                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3579                 free(channel);
3580                 return NULL;
3581         }
3582
3583         return channel;
3584 }
3585
3586 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) {
3587         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3588 }
3589
3590 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3591         if(!mesh || !channel) {
3592                 meshlink_errno = MESHLINK_EINVAL;
3593                 return;
3594         }
3595
3596         pthread_mutex_lock(&mesh->mutex);
3597         utcp_shutdown(channel->c, direction);
3598         pthread_mutex_unlock(&mesh->mutex);
3599 }
3600
3601 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3602         if(!mesh || !channel) {
3603                 meshlink_errno = MESHLINK_EINVAL;
3604                 return;
3605         }
3606
3607         pthread_mutex_lock(&mesh->mutex);
3608
3609         utcp_close(channel->c);
3610
3611         /* Clean up any outstanding AIO buffers. */
3612         for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3613                 next = aio->next;
3614                 aio_signal(mesh, channel, aio);
3615                 free(aio);
3616         }
3617
3618         for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3619                 next = aio->next;
3620                 aio_signal(mesh, channel, aio);
3621                 free(aio);
3622         }
3623
3624         pthread_mutex_unlock(&mesh->mutex);
3625
3626         free(channel);
3627 }
3628
3629 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3630         if(!mesh || !channel) {
3631                 meshlink_errno = MESHLINK_EINVAL;
3632                 return -1;
3633         }
3634
3635         if(!len) {
3636                 return 0;
3637         }
3638
3639         if(!data) {
3640                 meshlink_errno = MESHLINK_EINVAL;
3641                 return -1;
3642         }
3643
3644         // TODO: more finegrained locking.
3645         // Ideally we want to put the data into the UTCP connection's send buffer.
3646         // Then, preferably only if there is room in the receiver window,
3647         // kick the meshlink thread to go send packets.
3648
3649         ssize_t retval;
3650
3651         pthread_mutex_lock(&mesh->mutex);
3652
3653         /* Disallow direct calls to utcp_send() while we still have AIO active. */
3654         if(channel->aio_send) {
3655                 retval = 0;
3656         } else {
3657                 retval = utcp_send(channel->c, data, len);
3658         }
3659
3660         pthread_mutex_unlock(&mesh->mutex);
3661
3662         if(retval < 0) {
3663                 meshlink_errno = MESHLINK_ENETWORK;
3664         }
3665
3666         return retval;
3667 }
3668
3669 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) {
3670         if(!mesh || !channel) {
3671                 meshlink_errno = MESHLINK_EINVAL;
3672                 return false;
3673         }
3674
3675         if(!len || !data) {
3676                 meshlink_errno = MESHLINK_EINVAL;
3677                 return false;
3678         }
3679
3680         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3681         aio->data = data;
3682         aio->len = len;
3683         aio->cb.buffer = cb;
3684         aio->priv = priv;
3685
3686         pthread_mutex_lock(&mesh->mutex);
3687
3688         /* Append the AIO buffer descriptor to the end of the chain */
3689         meshlink_aio_buffer_t **p = &channel->aio_send;
3690
3691         while(*p) {
3692                 p = &(*p)->next;
3693         }
3694
3695         *p = aio;
3696
3697         /* Ensure the poll callback is set, and call it right now to push data if possible */
3698         utcp_set_poll_cb(channel->c, channel_poll);
3699         channel_poll(channel->c, len);
3700
3701         pthread_mutex_unlock(&mesh->mutex);
3702
3703         return true;
3704 }
3705
3706 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) {
3707         if(!mesh || !channel) {
3708                 meshlink_errno = MESHLINK_EINVAL;
3709                 return false;
3710         }
3711
3712         if(!len || fd == -1) {
3713                 meshlink_errno = MESHLINK_EINVAL;
3714                 return false;
3715         }
3716
3717         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3718         aio->fd = fd;
3719         aio->len = len;
3720         aio->cb.fd = cb;
3721         aio->priv = priv;
3722
3723         pthread_mutex_lock(&mesh->mutex);
3724
3725         /* Append the AIO buffer descriptor to the end of the chain */
3726         meshlink_aio_buffer_t **p = &channel->aio_send;
3727
3728         while(*p) {
3729                 p = &(*p)->next;
3730         }
3731
3732         *p = aio;
3733
3734         /* Ensure the poll callback is set, and call it right now to push data if possible */
3735         utcp_set_poll_cb(channel->c, channel_poll);
3736         channel_poll(channel->c, len);
3737
3738         pthread_mutex_unlock(&mesh->mutex);
3739
3740         return true;
3741 }
3742
3743 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) {
3744         if(!mesh || !channel) {
3745                 meshlink_errno = MESHLINK_EINVAL;
3746                 return false;
3747         }
3748
3749         if(!len || !data) {
3750                 meshlink_errno = MESHLINK_EINVAL;
3751                 return false;
3752         }
3753
3754         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3755         aio->data = data;
3756         aio->len = len;
3757         aio->cb.buffer = cb;
3758         aio->priv = priv;
3759
3760         pthread_mutex_lock(&mesh->mutex);
3761
3762         /* Append the AIO buffer descriptor to the end of the chain */
3763         meshlink_aio_buffer_t **p = &channel->aio_receive;
3764
3765         while(*p) {
3766                 p = &(*p)->next;
3767         }
3768
3769         *p = aio;
3770
3771         pthread_mutex_unlock(&mesh->mutex);
3772
3773         return true;
3774 }
3775
3776 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) {
3777         if(!mesh || !channel) {
3778                 meshlink_errno = MESHLINK_EINVAL;
3779                 return false;
3780         }
3781
3782         if(!len || fd == -1) {
3783                 meshlink_errno = MESHLINK_EINVAL;
3784                 return false;
3785         }
3786
3787         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3788         aio->fd = fd;
3789         aio->len = len;
3790         aio->cb.fd = cb;
3791         aio->priv = priv;
3792
3793         pthread_mutex_lock(&mesh->mutex);
3794
3795         /* Append the AIO buffer descriptor to the end of the chain */
3796         meshlink_aio_buffer_t **p = &channel->aio_receive;
3797
3798         while(*p) {
3799                 p = &(*p)->next;
3800         }
3801
3802         *p = aio;
3803
3804         pthread_mutex_unlock(&mesh->mutex);
3805
3806         return true;
3807 }
3808
3809 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3810         if(!mesh || !channel) {
3811                 meshlink_errno = MESHLINK_EINVAL;
3812                 return -1;
3813         }
3814
3815         return channel->c->flags;
3816 }
3817
3818 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3819         if(!mesh || !channel) {
3820                 meshlink_errno = MESHLINK_EINVAL;
3821                 return -1;
3822         }
3823
3824         return utcp_get_sendq(channel->c);
3825 }
3826
3827 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3828         if(!mesh || !channel) {
3829                 meshlink_errno = MESHLINK_EINVAL;
3830                 return -1;
3831         }
3832
3833         return utcp_get_recvq(channel->c);
3834 }
3835
3836 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3837         if(!mesh || !node) {
3838                 meshlink_errno = MESHLINK_EINVAL;
3839                 return;
3840         }
3841
3842         node_t *n = (node_t *)node;
3843
3844         pthread_mutex_lock(&mesh->mutex);
3845
3846         if(!n->utcp) {
3847                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3848         }
3849
3850         utcp_set_user_timeout(n->utcp, timeout);
3851
3852         pthread_mutex_unlock(&mesh->mutex);
3853 }
3854
3855 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3856         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3857                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3858         }
3859
3860         if(mesh->node_status_cb) {
3861                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3862         }
3863
3864         if(mesh->node_pmtu_cb) {
3865                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3866         }
3867 }
3868
3869 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3870         if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3871                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3872         }
3873 }
3874
3875 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3876         if(!mesh->node_duplicate_cb || n->status.duplicate) {
3877                 return;
3878         }
3879
3880         n->status.duplicate = true;
3881         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3882 }
3883
3884 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3885 #if HAVE_CATTA
3886
3887         if(!mesh) {
3888                 meshlink_errno = MESHLINK_EINVAL;
3889                 return;
3890         }
3891
3892         pthread_mutex_lock(&mesh->mutex);
3893
3894         if(mesh->discovery == enable) {
3895                 goto end;
3896         }
3897
3898         if(mesh->threadstarted) {
3899                 if(enable) {
3900                         discovery_start(mesh);
3901                 } else {
3902                         discovery_stop(mesh);
3903                 }
3904         }
3905
3906         mesh->discovery = enable;
3907
3908 end:
3909         pthread_mutex_unlock(&mesh->mutex);
3910 #else
3911         (void)mesh;
3912         (void)enable;
3913         meshlink_errno = MESHLINK_ENOTSUP;
3914 #endif
3915 }
3916
3917 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3918         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3919                 meshlink_errno = EINVAL;
3920                 return;
3921         }
3922
3923         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3924                 meshlink_errno = EINVAL;
3925                 return;
3926         }
3927
3928         pthread_mutex_lock(&mesh->mutex);
3929         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3930         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3931         pthread_mutex_unlock(&mesh->mutex);
3932 }
3933
3934 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3935         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3936                 meshlink_errno = EINVAL;
3937                 return;
3938         }
3939
3940         if(fast_retry_period < 0) {
3941                 meshlink_errno = EINVAL;
3942                 return;
3943         }
3944
3945         pthread_mutex_lock(&mesh->mutex);
3946         mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3947         pthread_mutex_unlock(&mesh->mutex);
3948 }
3949
3950 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3951         if(!mesh) {
3952                 meshlink_errno = EINVAL;
3953                 return;
3954         }
3955
3956         pthread_mutex_lock(&mesh->mutex);
3957         mesh->inviter_commits_first = inviter_commits_first;
3958         pthread_mutex_unlock(&mesh->mutex);
3959 }
3960
3961 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3962         (void)online;
3963
3964         if(!mesh->connections || !mesh->loop.running) {
3965                 return;
3966         }
3967
3968         retry(mesh);
3969 }
3970
3971 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3972         // We should only call the callback function if we are in the background thread.
3973         if(!mesh->error_cb) {
3974                 return;
3975         }
3976
3977         if(!mesh->threadstarted) {
3978                 return;
3979         }
3980
3981         if(mesh->thread == pthread_self()) {
3982                 mesh->error_cb(mesh, meshlink_errno);
3983         }
3984 }
3985
3986 static void __attribute__((constructor)) meshlink_init(void) {
3987         crypto_init();
3988 }
3989
3990 static void __attribute__((destructor)) meshlink_exit(void) {
3991         crypto_exit();
3992 }