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