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