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