]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Replace rand() by xoshiro256** with per-mesh state.
[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
893         if(!write_main_config_files(mesh)) {
894                 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
895                 meshlink_errno = MESHLINK_ESTORAGE;
896                 return false;
897         }
898
899         /* Ensure the configuration directory metadata is on disk */
900         if(!config_sync(mesh, "current")) {
901                 return false;
902         }
903
904         if(!main_config_lock(mesh)) {
905                 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
906                 meshlink_errno = MESHLINK_ESTORAGE;
907                 return false;
908         }
909
910         return true;
911 }
912
913 static bool meshlink_read_config(meshlink_handle_t *mesh) {
914         // Open the configuration file and lock it
915         if(!main_config_lock(mesh)) {
916                 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
917                 meshlink_errno = MESHLINK_ESTORAGE;
918                 return false;
919         }
920
921         config_t config;
922
923         if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
924                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
925                 return false;
926         }
927
928         packmsg_input_t in = {config.buf, config.len};
929         const void *private_key;
930         const void *invitation_key;
931
932         uint32_t version = packmsg_get_uint32(&in);
933         char *name = packmsg_get_str_dup(&in);
934         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
935         uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
936         uint16_t myport = packmsg_get_uint16(&in);
937
938         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
939                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
940                 free(name);
941                 config_free(&config);
942                 return false;
943         }
944
945 #if 0
946
947         // TODO: check this?
948         if(mesh->name && strcmp(mesh->name, name)) {
949                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
950                 meshlink_errno = MESHLINK_ESTORAGE;
951                 free(name);
952                 config_free(&config);
953                 return false;
954         }
955
956 #endif
957
958         free(mesh->name);
959         mesh->name = name;
960         xasprintf(&mesh->myport, "%u", myport);
961         mesh->private_key = ecdsa_set_private_key(private_key);
962         mesh->invitation_key = ecdsa_set_private_key(invitation_key);
963         config_free(&config);
964
965         /* Create a node for ourself and read our host configuration file */
966
967         mesh->self = new_node();
968         mesh->self->name = xstrdup(name);
969         mesh->self->devclass = mesh->devclass;
970
971         if(!node_read_public_key(mesh, mesh->self)) {
972                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
973                 meshlink_errno = MESHLINK_ESTORAGE;
974                 free_node(mesh->self);
975                 mesh->self = NULL;
976                 return false;
977         }
978
979         return true;
980 }
981
982 #ifdef HAVE_SETNS
983 static void *setup_network_in_netns_thread(void *arg) {
984         meshlink_handle_t *mesh = arg;
985
986         if(setns(mesh->netns, CLONE_NEWNET) != 0) {
987                 return NULL;
988         }
989
990         bool success = setup_network(mesh);
991         add_local_addresses(mesh);
992         return success ? arg : NULL;
993 }
994 #endif // HAVE_SETNS
995
996 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
997         if(!confbase || !*confbase) {
998                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
999                 meshlink_errno = MESHLINK_EINVAL;
1000                 return NULL;
1001         }
1002
1003         if(!appname || !*appname) {
1004                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1005                 meshlink_errno = MESHLINK_EINVAL;
1006                 return NULL;
1007         }
1008
1009         if(strchr(appname, ' ')) {
1010                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1011                 meshlink_errno = MESHLINK_EINVAL;
1012                 return NULL;
1013         }
1014
1015         if(!name || !*name) {
1016                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1017                 meshlink_errno = MESHLINK_EINVAL;
1018                 return NULL;
1019         };
1020
1021         if(!check_id(name)) {
1022                 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1023                 meshlink_errno = MESHLINK_EINVAL;
1024                 return NULL;
1025         }
1026
1027         if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1028                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1029                 meshlink_errno = MESHLINK_EINVAL;
1030                 return NULL;
1031         }
1032
1033         meshlink_open_params_t *params = xzalloc(sizeof * params);
1034
1035         params->confbase = xstrdup(confbase);
1036         params->name = xstrdup(name);
1037         params->appname = xstrdup(appname);
1038         params->devclass = devclass;
1039         params->netns = -1;
1040
1041         return params;
1042 }
1043
1044 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1045         if(!params) {
1046                 meshlink_errno = MESHLINK_EINVAL;
1047                 return false;
1048         }
1049
1050         params->netns = netns;
1051
1052         return true;
1053 }
1054
1055 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1056         if(!params) {
1057                 meshlink_errno = MESHLINK_EINVAL;
1058                 return false;
1059         }
1060
1061         if((!key && keylen) || (key && !keylen)) {
1062                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1063                 meshlink_errno = MESHLINK_EINVAL;
1064                 return false;
1065         }
1066
1067         params->key = key;
1068         params->keylen = keylen;
1069
1070         return true;
1071 }
1072
1073 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1074         if(!mesh || !new_key || !new_keylen) {
1075                 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1076                 meshlink_errno = MESHLINK_EINVAL;
1077                 return false;
1078         }
1079
1080         pthread_mutex_lock(&(mesh->mesh_mutex));
1081
1082         // Create hash for the new key
1083         void *new_config_key;
1084         new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1085
1086         if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1087                 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1088                 meshlink_errno = MESHLINK_EINTERNAL;
1089                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1090                 return false;
1091         }
1092
1093         // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1094
1095         if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1096                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1097                 meshlink_errno = MESHLINK_ESTORAGE;
1098                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1099                 return false;
1100         }
1101
1102         devtool_keyrotate_probe(1);
1103
1104         main_config_unlock(mesh);
1105
1106         // Rename confbase/current/ to confbase/old
1107
1108         if(!config_rename(mesh, "current", "old")) {
1109                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1110                 meshlink_errno = MESHLINK_ESTORAGE;
1111                 main_config_lock(mesh);
1112                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1113                 return false;
1114         }
1115
1116         devtool_keyrotate_probe(2);
1117
1118         // Rename confbase/new/ to confbase/current
1119
1120         if(!config_rename(mesh, "new", "current")) {
1121                 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1122                 meshlink_errno = MESHLINK_ESTORAGE;
1123                 main_config_lock(mesh);
1124                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1125                 return false;
1126         }
1127
1128         devtool_keyrotate_probe(3);
1129
1130         if(!main_config_lock(mesh)) {
1131                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1132                 return false;
1133         }
1134
1135         // Cleanup the "old" confbase sub-directory
1136
1137         if(!config_destroy(mesh->confbase, "old")) {
1138                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1139                 return false;
1140         }
1141
1142         // Change the mesh handle key with new key
1143
1144         free(mesh->config_key);
1145         mesh->config_key = new_config_key;
1146
1147         pthread_mutex_unlock(&(mesh->mesh_mutex));
1148
1149         return true;
1150 }
1151
1152 void meshlink_open_params_free(meshlink_open_params_t *params) {
1153         if(!params) {
1154                 meshlink_errno = MESHLINK_EINVAL;
1155                 return;
1156         }
1157
1158         free(params->confbase);
1159         free(params->name);
1160         free(params->appname);
1161
1162         free(params);
1163 }
1164
1165 /// Device class traits
1166 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1167         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1168         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
1169         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 },     // DEV_CLASS_PORTABLE
1170         { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 },     // DEV_CLASS_UNKNOWN
1171 };
1172
1173 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1174         if(!confbase || !*confbase) {
1175                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1176                 meshlink_errno = MESHLINK_EINVAL;
1177                 return NULL;
1178         }
1179
1180         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1181         meshlink_open_params_t params;
1182         memset(&params, 0, sizeof(params));
1183
1184         params.confbase = (char *)confbase;
1185         params.name = (char *)name;
1186         params.appname = (char *)appname;
1187         params.devclass = devclass;
1188         params.netns = -1;
1189
1190         return meshlink_open_ex(&params);
1191 }
1192
1193 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) {
1194         if(!confbase || !*confbase) {
1195                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1196                 meshlink_errno = MESHLINK_EINVAL;
1197                 return NULL;
1198         }
1199
1200         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1201         meshlink_open_params_t params;
1202         memset(&params, 0, sizeof(params));
1203
1204         params.confbase = (char *)confbase;
1205         params.name = (char *)name;
1206         params.appname = (char *)appname;
1207         params.devclass = devclass;
1208         params.netns = -1;
1209
1210         if(!meshlink_open_params_set_storage_key(&params, key, keylen)) {
1211                 return false;
1212         }
1213
1214         return meshlink_open_ex(&params);
1215 }
1216
1217 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1218         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1219         meshlink_open_params_t params;
1220         memset(&params, 0, sizeof(params));
1221
1222         params.name = (char *)name;
1223         params.appname = (char *)appname;
1224         params.devclass = devclass;
1225         params.netns = -1;
1226
1227         return meshlink_open_ex(&params);
1228 }
1229
1230 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1231         // Validate arguments provided by the application
1232         bool usingname = false;
1233
1234         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1235
1236         if(!params->appname || !*params->appname) {
1237                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1238                 meshlink_errno = MESHLINK_EINVAL;
1239                 return NULL;
1240         }
1241
1242         if(strchr(params->appname, ' ')) {
1243                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1244                 meshlink_errno = MESHLINK_EINVAL;
1245                 return NULL;
1246         }
1247
1248         if(!params->name || !*params->name) {
1249                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1250                 //return NULL;
1251         } else { //check name only if there is a name != NULL
1252
1253                 if(!check_id(params->name)) {
1254                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1255                         meshlink_errno = MESHLINK_EINVAL;
1256                         return NULL;
1257                 } else {
1258                         usingname = true;
1259                 }
1260         }
1261
1262         if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1263                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1264                 meshlink_errno = MESHLINK_EINVAL;
1265                 return NULL;
1266         }
1267
1268         if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1269                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1270                 meshlink_errno = MESHLINK_EINVAL;
1271                 return NULL;
1272         }
1273
1274         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1275
1276         if(params->confbase) {
1277                 mesh->confbase = xstrdup(params->confbase);
1278         }
1279
1280         mesh->appname = xstrdup(params->appname);
1281         mesh->devclass = params->devclass;
1282         mesh->discovery = true;
1283         mesh->invitation_timeout = 604800; // 1 week
1284         mesh->netns = params->netns;
1285         mesh->submeshes = NULL;
1286         mesh->log_cb = global_log_cb;
1287         mesh->log_level = global_log_level;
1288
1289         randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1290
1291         memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1292
1293         if(usingname) {
1294                 mesh->name = xstrdup(params->name);
1295         }
1296
1297         // Hash the key
1298         if(params->key) {
1299                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1300
1301                 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1302                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1303                         meshlink_close(mesh);
1304                         meshlink_errno = MESHLINK_EINTERNAL;
1305                         return NULL;
1306                 }
1307         }
1308
1309         // initialize mutex
1310         pthread_mutexattr_t attr;
1311         pthread_mutexattr_init(&attr);
1312         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1313         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1314
1315         mesh->threadstarted = false;
1316         event_loop_init(&mesh->loop);
1317         mesh->loop.data = mesh;
1318
1319         meshlink_queue_init(&mesh->outpacketqueue);
1320
1321         // If no configuration exists yet, create it.
1322
1323         if(!meshlink_confbase_exists(mesh)) {
1324                 if(!meshlink_setup(mesh)) {
1325                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1326                         meshlink_close(mesh);
1327                         return NULL;
1328                 }
1329         } else {
1330                 if(!meshlink_read_config(mesh)) {
1331                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1332                         meshlink_close(mesh);
1333                         return NULL;
1334                 }
1335         }
1336
1337 #ifdef HAVE_MINGW
1338         struct WSAData wsa_state;
1339         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1340 #endif
1341
1342         // Setup up everything
1343         // TODO: we should not open listening sockets yet
1344
1345         bool success = false;
1346
1347         if(mesh->netns != -1) {
1348 #ifdef HAVE_SETNS
1349                 pthread_t thr;
1350
1351                 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1352                         void *retval = NULL;
1353                         success = pthread_join(thr, &retval) == 0 && retval;
1354                 }
1355
1356 #else
1357                 meshlink_errno = MESHLINK_EINTERNAL;
1358                 return NULL;
1359
1360 #endif // HAVE_SETNS
1361         } else {
1362                 success = setup_network(mesh);
1363                 add_local_addresses(mesh);
1364         }
1365
1366         if(!success) {
1367                 meshlink_close(mesh);
1368                 meshlink_errno = MESHLINK_ENETWORK;
1369                 return NULL;
1370         }
1371
1372         add_local_addresses(mesh);
1373         node_write_config(mesh, mesh->self);
1374
1375         idle_set(&mesh->loop, idle, mesh);
1376
1377         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1378         return mesh;
1379 }
1380
1381 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t  *mesh, const char *submesh) {
1382         meshlink_submesh_t *s = NULL;
1383
1384         if(!mesh) {
1385                 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1386                 meshlink_errno = MESHLINK_EINVAL;
1387                 return NULL;
1388         }
1389
1390         if(!submesh || !*submesh) {
1391                 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1392                 meshlink_errno = MESHLINK_EINVAL;
1393                 return NULL;
1394         }
1395
1396         //lock mesh->nodes
1397         pthread_mutex_lock(&(mesh->mesh_mutex));
1398
1399         s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1400
1401         pthread_mutex_unlock(&(mesh->mesh_mutex));
1402
1403         return s;
1404 }
1405
1406 static void *meshlink_main_loop(void *arg) {
1407         meshlink_handle_t *mesh = arg;
1408
1409         if(mesh->netns != -1) {
1410 #ifdef HAVE_SETNS
1411
1412                 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1413                         pthread_cond_signal(&mesh->cond);
1414                         return NULL;
1415                 }
1416
1417 #else
1418                 pthread_cond_signal(&mesh->cond);
1419                 return NULL;
1420 #endif // HAVE_SETNS
1421         }
1422
1423 #if HAVE_CATTA
1424
1425         if(mesh->discovery) {
1426                 discovery_start(mesh);
1427         }
1428
1429 #endif
1430
1431         pthread_mutex_lock(&(mesh->mesh_mutex));
1432
1433         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1434         pthread_cond_broadcast(&mesh->cond);
1435         main_loop(mesh);
1436         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1437
1438         pthread_mutex_unlock(&(mesh->mesh_mutex));
1439
1440 #if HAVE_CATTA
1441
1442         // Stop discovery
1443         if(mesh->discovery) {
1444                 discovery_stop(mesh);
1445         }
1446
1447 #endif
1448
1449         return NULL;
1450 }
1451
1452 bool meshlink_start(meshlink_handle_t *mesh) {
1453         assert(mesh->self);
1454         assert(mesh->private_key);
1455
1456         if(!mesh) {
1457                 meshlink_errno = MESHLINK_EINVAL;
1458                 return false;
1459         }
1460
1461         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1462
1463         pthread_mutex_lock(&(mesh->mesh_mutex));
1464
1465         assert(mesh->self->ecdsa);
1466         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1467
1468         if(mesh->threadstarted) {
1469                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1470                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1471                 return true;
1472         }
1473
1474         if(mesh->listen_socket[0].tcp.fd < 0) {
1475                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1476                 meshlink_errno = MESHLINK_ENETWORK;
1477                 return false;
1478         }
1479
1480         mesh->thedatalen = 0;
1481
1482         // TODO: open listening sockets first
1483
1484         //Check that a valid name is set
1485         if(!mesh->name) {
1486                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1487                 meshlink_errno = MESHLINK_EINVAL;
1488                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1489                 return false;
1490         }
1491
1492         init_outgoings(mesh);
1493
1494         // Start the main thread
1495
1496         event_loop_start(&mesh->loop);
1497
1498         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1499                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1500                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1501                 meshlink_errno = MESHLINK_EINTERNAL;
1502                 event_loop_stop(&mesh->loop);
1503                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1504                 return false;
1505         }
1506
1507         pthread_cond_wait(&mesh->cond, &mesh->mesh_mutex);
1508         mesh->threadstarted = true;
1509
1510         pthread_mutex_unlock(&(mesh->mesh_mutex));
1511         return true;
1512 }
1513
1514 void meshlink_stop(meshlink_handle_t *mesh) {
1515         if(!mesh) {
1516                 meshlink_errno = MESHLINK_EINVAL;
1517                 return;
1518         }
1519
1520         pthread_mutex_lock(&(mesh->mesh_mutex));
1521         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1522
1523         // Shut down the main thread
1524         event_loop_stop(&mesh->loop);
1525
1526         // Send ourselves a UDP packet to kick the event loop
1527         for(int i = 0; i < mesh->listen_sockets; i++) {
1528                 sockaddr_t sa;
1529                 socklen_t salen = sizeof(sa.sa);
1530
1531                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1532                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1533                         continue;
1534                 }
1535
1536                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1537                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1538                 }
1539         }
1540
1541         if(mesh->threadstarted) {
1542                 // Wait for the main thread to finish
1543                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1544                 pthread_join(mesh->thread, NULL);
1545                 pthread_mutex_lock(&(mesh->mesh_mutex));
1546
1547                 mesh->threadstarted = false;
1548         }
1549
1550         // Close all metaconnections
1551         if(mesh->connections) {
1552                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1553                         next = node->next;
1554                         connection_t *c = node->data;
1555                         c->outgoing = NULL;
1556                         terminate_connection(mesh, c, false);
1557                 }
1558         }
1559
1560         exit_outgoings(mesh);
1561
1562         // Write out any changed node config files
1563         if(mesh->nodes) {
1564                 for splay_each(node_t, n, mesh->nodes) {
1565                         if(n->status.dirty) {
1566                                 node_write_config(mesh, n);
1567                                 n->status.dirty = false;
1568                         }
1569                 }
1570         }
1571
1572         pthread_mutex_unlock(&(mesh->mesh_mutex));
1573 }
1574
1575 void meshlink_close(meshlink_handle_t *mesh) {
1576         if(!mesh) {
1577                 meshlink_errno = MESHLINK_EINVAL;
1578                 return;
1579         }
1580
1581         // stop can be called even if mesh has not been started
1582         meshlink_stop(mesh);
1583
1584         // lock is not released after this
1585         pthread_mutex_lock(&(mesh->mesh_mutex));
1586
1587         // Close and free all resources used.
1588
1589         close_network_connections(mesh);
1590
1591         logger(mesh, MESHLINK_INFO, "Terminating");
1592
1593         event_loop_exit(&mesh->loop);
1594
1595 #ifdef HAVE_MINGW
1596
1597         if(mesh->confbase) {
1598                 WSACleanup();
1599         }
1600
1601 #endif
1602
1603         ecdsa_free(mesh->invitation_key);
1604
1605         if(mesh->netns != -1) {
1606                 close(mesh->netns);
1607         }
1608
1609         for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1610                 free(packet);
1611         }
1612
1613         meshlink_queue_exit(&mesh->outpacketqueue);
1614
1615         free(mesh->name);
1616         free(mesh->appname);
1617         free(mesh->confbase);
1618         free(mesh->config_key);
1619         ecdsa_free(mesh->private_key);
1620         pthread_mutex_destroy(&(mesh->mesh_mutex));
1621
1622         main_config_unlock(mesh);
1623
1624         memset(mesh, 0, sizeof(*mesh));
1625
1626         free(mesh);
1627 }
1628
1629 bool meshlink_destroy(const char *confbase) {
1630         if(!confbase) {
1631                 meshlink_errno = MESHLINK_EINVAL;
1632                 return false;
1633         }
1634
1635         if(!config_destroy(confbase, "current")) {
1636                 logger(NULL, MESHLINK_ERROR, "Cannot remove confbase sub-directories %s: %s\n", confbase, strerror(errno));
1637                 return false;
1638         }
1639
1640         config_destroy(confbase, "new");
1641         config_destroy(confbase, "old");
1642
1643         if(rmdir(confbase) && errno != ENOENT) {
1644                 logger(NULL, MESHLINK_ERROR, "Cannot remove directory %s: %s\n", confbase, strerror(errno));
1645                 meshlink_errno = MESHLINK_ESTORAGE;
1646                 return false;
1647         }
1648
1649         return true;
1650 }
1651
1652 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1653         if(!mesh) {
1654                 meshlink_errno = MESHLINK_EINVAL;
1655                 return;
1656         }
1657
1658         pthread_mutex_lock(&(mesh->mesh_mutex));
1659         mesh->receive_cb = cb;
1660         pthread_mutex_unlock(&(mesh->mesh_mutex));
1661 }
1662
1663 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1664         if(!mesh) {
1665                 meshlink_errno = MESHLINK_EINVAL;
1666                 return;
1667         }
1668
1669         pthread_mutex_lock(&(mesh->mesh_mutex));
1670         mesh->connection_try_cb = cb;
1671         pthread_mutex_unlock(&(mesh->mesh_mutex));
1672 }
1673
1674 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1675         if(!mesh) {
1676                 meshlink_errno = MESHLINK_EINVAL;
1677                 return;
1678         }
1679
1680         pthread_mutex_lock(&(mesh->mesh_mutex));
1681         mesh->node_status_cb = cb;
1682         pthread_mutex_unlock(&(mesh->mesh_mutex));
1683 }
1684
1685 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1686         if(!mesh) {
1687                 meshlink_errno = MESHLINK_EINVAL;
1688                 return;
1689         }
1690
1691         pthread_mutex_lock(&(mesh->mesh_mutex));
1692         mesh->node_pmtu_cb = cb;
1693         pthread_mutex_unlock(&(mesh->mesh_mutex));
1694 }
1695
1696 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1697         if(!mesh) {
1698                 meshlink_errno = MESHLINK_EINVAL;
1699                 return;
1700         }
1701
1702         pthread_mutex_lock(&(mesh->mesh_mutex));
1703         mesh->node_duplicate_cb = cb;
1704         pthread_mutex_unlock(&(mesh->mesh_mutex));
1705 }
1706
1707 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1708         if(mesh) {
1709                 pthread_mutex_lock(&(mesh->mesh_mutex));
1710                 mesh->log_cb = cb;
1711                 mesh->log_level = cb ? level : 0;
1712                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1713         } else {
1714                 global_log_cb = cb;
1715                 global_log_level = cb ? level : 0;
1716         }
1717 }
1718
1719 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1720         meshlink_packethdr_t *hdr;
1721
1722         // Validate arguments
1723         if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1724                 meshlink_errno = MESHLINK_EINVAL;
1725                 return false;
1726         }
1727
1728         if(!len) {
1729                 return true;
1730         }
1731
1732         if(!data) {
1733                 meshlink_errno = MESHLINK_EINVAL;
1734                 return false;
1735         }
1736
1737         node_t *n = (node_t *)destination;
1738
1739         if(n->status.blacklisted) {
1740                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1741                 return false;
1742         }
1743
1744         // Prepare the packet
1745         vpn_packet_t *packet = malloc(sizeof(*packet));
1746
1747         if(!packet) {
1748                 meshlink_errno = MESHLINK_ENOMEM;
1749                 return false;
1750         }
1751
1752         packet->probe = false;
1753         packet->tcp = false;
1754         packet->len = len + sizeof(*hdr);
1755
1756         hdr = (meshlink_packethdr_t *)packet->data;
1757         memset(hdr, 0, sizeof(*hdr));
1758         // leave the last byte as 0 to make sure strings are always
1759         // null-terminated if they are longer than the buffer
1760         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1761         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1762
1763         memcpy(packet->data + sizeof(*hdr), data, len);
1764
1765         // Queue it
1766         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1767                 free(packet);
1768                 meshlink_errno = MESHLINK_ENOMEM;
1769                 return false;
1770         }
1771
1772         // Notify event loop
1773         signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1774
1775         return true;
1776 }
1777
1778 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1779         (void)loop;
1780         meshlink_handle_t *mesh = data;
1781         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1782
1783         if(!packet) {
1784                 return;
1785         }
1786
1787         mesh->self->in_packets++;
1788         mesh->self->in_bytes += packet->len;
1789         route(mesh, mesh->self, packet);
1790
1791         free(packet);
1792 }
1793
1794 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1795         if(!mesh || !destination) {
1796                 meshlink_errno = MESHLINK_EINVAL;
1797                 return -1;
1798         }
1799
1800         pthread_mutex_lock(&(mesh->mesh_mutex));
1801
1802         node_t *n = (node_t *)destination;
1803
1804         if(!n->status.reachable) {
1805                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1806                 return 0;
1807
1808         } else if(n->mtuprobes > 30 && n->minmtu) {
1809                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1810                 return n->minmtu;
1811         } else {
1812                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1813                 return MTU;
1814         }
1815 }
1816
1817 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1818         if(!mesh || !node) {
1819                 meshlink_errno = MESHLINK_EINVAL;
1820                 return NULL;
1821         }
1822
1823         pthread_mutex_lock(&(mesh->mesh_mutex));
1824
1825         node_t *n = (node_t *)node;
1826
1827         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1828                 meshlink_errno = MESHLINK_EINTERNAL;
1829                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1830                 return false;
1831         }
1832
1833         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1834
1835         if(!fingerprint) {
1836                 meshlink_errno = MESHLINK_EINTERNAL;
1837         }
1838
1839         pthread_mutex_unlock(&(mesh->mesh_mutex));
1840         return fingerprint;
1841 }
1842
1843 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1844         if(!mesh) {
1845                 meshlink_errno = MESHLINK_EINVAL;
1846                 return NULL;
1847         }
1848
1849         return (meshlink_node_t *)mesh->self;
1850 }
1851
1852 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1853         if(!mesh || !name) {
1854                 meshlink_errno = MESHLINK_EINVAL;
1855                 return NULL;
1856         }
1857
1858         meshlink_node_t *node = NULL;
1859
1860         pthread_mutex_lock(&(mesh->mesh_mutex));
1861         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1862         pthread_mutex_unlock(&(mesh->mesh_mutex));
1863
1864         if(!node) {
1865                 meshlink_errno = MESHLINK_ENOENT;
1866         }
1867
1868         return node;
1869 }
1870
1871 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1872         if(!mesh || !name) {
1873                 meshlink_errno = MESHLINK_EINVAL;
1874                 return NULL;
1875         }
1876
1877         meshlink_submesh_t *submesh = NULL;
1878
1879         pthread_mutex_lock(&(mesh->mesh_mutex));
1880         submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1881         pthread_mutex_unlock(&(mesh->mesh_mutex));
1882
1883         if(!submesh) {
1884                 meshlink_errno = MESHLINK_ENOENT;
1885         }
1886
1887         return submesh;
1888 }
1889
1890 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1891         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1892                 meshlink_errno = MESHLINK_EINVAL;
1893                 return NULL;
1894         }
1895
1896         meshlink_node_t **result;
1897
1898         //lock mesh->nodes
1899         pthread_mutex_lock(&(mesh->mesh_mutex));
1900
1901         *nmemb = mesh->nodes->count;
1902         result = realloc(nodes, *nmemb * sizeof(*nodes));
1903
1904         if(result) {
1905                 meshlink_node_t **p = result;
1906
1907                 for splay_each(node_t, n, mesh->nodes) {
1908                         *p++ = (meshlink_node_t *)n;
1909                 }
1910         } else {
1911                 *nmemb = 0;
1912                 free(nodes);
1913                 meshlink_errno = MESHLINK_ENOMEM;
1914         }
1915
1916         pthread_mutex_unlock(&(mesh->mesh_mutex));
1917
1918         return result;
1919 }
1920
1921 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) {
1922         meshlink_node_t **result;
1923
1924         pthread_mutex_lock(&(mesh->mesh_mutex));
1925
1926         *nmemb = 0;
1927
1928         for splay_each(node_t, n, mesh->nodes) {
1929                 if(true == search_node(n, condition)) {
1930                         *nmemb = *nmemb + 1;
1931                 }
1932         }
1933
1934         if(*nmemb == 0) {
1935                 free(nodes);
1936                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1937                 return NULL;
1938         }
1939
1940         result = realloc(nodes, *nmemb * sizeof(*nodes));
1941
1942         if(result) {
1943                 meshlink_node_t **p = result;
1944
1945                 for splay_each(node_t, n, mesh->nodes) {
1946                         if(true == search_node(n, condition)) {
1947                                 *p++ = (meshlink_node_t *)n;
1948                         }
1949                 }
1950         } else {
1951                 *nmemb = 0;
1952                 free(nodes);
1953                 meshlink_errno = MESHLINK_ENOMEM;
1954         }
1955
1956         pthread_mutex_unlock(&(mesh->mesh_mutex));
1957
1958         return result;
1959 }
1960
1961 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1962         dev_class_t *devclass = (dev_class_t *)condition;
1963
1964         if(*devclass == (dev_class_t)node->devclass) {
1965                 return true;
1966         }
1967
1968         return false;
1969 }
1970
1971 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1972         if(condition == node->submesh) {
1973                 return true;
1974         }
1975
1976         return false;
1977 }
1978
1979 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) {
1980         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
1981                 meshlink_errno = MESHLINK_EINVAL;
1982                 return NULL;
1983         }
1984
1985         return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1986 }
1987
1988 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1989         if(!mesh || !submesh || !nmemb) {
1990                 meshlink_errno = MESHLINK_EINVAL;
1991                 return NULL;
1992         }
1993
1994         return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1995 }
1996
1997 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1998         if(!mesh || !node) {
1999                 meshlink_errno = MESHLINK_EINVAL;
2000                 return -1;
2001         }
2002
2003         dev_class_t devclass;
2004
2005         pthread_mutex_lock(&(mesh->mesh_mutex));
2006
2007         devclass = ((node_t *)node)->devclass;
2008
2009         pthread_mutex_unlock(&(mesh->mesh_mutex));
2010
2011         return devclass;
2012 }
2013
2014 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2015         if(!mesh || !node) {
2016                 meshlink_errno = MESHLINK_EINVAL;
2017                 return NULL;
2018         }
2019
2020         node_t *n = (node_t *)node;
2021
2022         meshlink_submesh_t *s;
2023
2024         s = (meshlink_submesh_t *)n->submesh;
2025
2026         return s;
2027 }
2028
2029 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2030         if(!mesh || !data || !len || !signature || !siglen) {
2031                 meshlink_errno = MESHLINK_EINVAL;
2032                 return false;
2033         }
2034
2035         if(*siglen < MESHLINK_SIGLEN) {
2036                 meshlink_errno = MESHLINK_EINVAL;
2037                 return false;
2038         }
2039
2040         pthread_mutex_lock(&(mesh->mesh_mutex));
2041
2042         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2043                 meshlink_errno = MESHLINK_EINTERNAL;
2044                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2045                 return false;
2046         }
2047
2048         *siglen = MESHLINK_SIGLEN;
2049         pthread_mutex_unlock(&(mesh->mesh_mutex));
2050         return true;
2051 }
2052
2053 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2054         if(!mesh || !data || !len || !signature) {
2055                 meshlink_errno = MESHLINK_EINVAL;
2056                 return false;
2057         }
2058
2059         if(siglen != MESHLINK_SIGLEN) {
2060                 meshlink_errno = MESHLINK_EINVAL;
2061                 return false;
2062         }
2063
2064         pthread_mutex_lock(&(mesh->mesh_mutex));
2065
2066         bool rval = false;
2067
2068         struct node_t *n = (struct node_t *)source;
2069
2070         if(!node_read_public_key(mesh, n)) {
2071                 meshlink_errno = MESHLINK_EINTERNAL;
2072                 rval = false;
2073         } else {
2074                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2075         }
2076
2077         pthread_mutex_unlock(&(mesh->mesh_mutex));
2078         return rval;
2079 }
2080
2081 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2082         pthread_mutex_lock(&(mesh->mesh_mutex));
2083
2084         size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2085
2086         if(!count) {
2087                 // TODO: Update invitation key if necessary?
2088         }
2089
2090         pthread_mutex_unlock(&(mesh->mesh_mutex));
2091
2092         return mesh->invitation_key;
2093 }
2094
2095 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2096         if(!mesh || !node || !address) {
2097                 meshlink_errno = MESHLINK_EINVAL;
2098                 return false;
2099         }
2100
2101         if(!is_valid_hostname(address)) {
2102                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2103                 meshlink_errno = MESHLINK_EINVAL;
2104                 return false;
2105         }
2106
2107         if(port && !is_valid_port(port)) {
2108                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2109                 meshlink_errno = MESHLINK_EINVAL;
2110                 return false;
2111         }
2112
2113         char *canonical_address;
2114
2115         if(port) {
2116                 xasprintf(&canonical_address, "%s %s", address, port);
2117         } else {
2118                 canonical_address = xstrdup(address);
2119         }
2120
2121         pthread_mutex_lock(&(mesh->mesh_mutex));
2122
2123         node_t *n = (node_t *)node;
2124         free(n->canonical_address);
2125         n->canonical_address = canonical_address;
2126         node_write_config(mesh, n);
2127
2128         pthread_mutex_unlock(&(mesh->mesh_mutex));
2129
2130         return true;
2131 }
2132
2133 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2134         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2135 }
2136
2137 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2138         if(!mesh) {
2139                 meshlink_errno = MESHLINK_EINVAL;
2140                 return false;
2141         }
2142
2143         char *address = meshlink_get_external_address(mesh);
2144
2145         if(!address) {
2146                 return false;
2147         }
2148
2149         bool rval = meshlink_add_address(mesh, address);
2150         free(address);
2151
2152         return rval;
2153 }
2154
2155 int meshlink_get_port(meshlink_handle_t *mesh) {
2156         if(!mesh) {
2157                 meshlink_errno = MESHLINK_EINVAL;
2158                 return -1;
2159         }
2160
2161         if(!mesh->myport) {
2162                 meshlink_errno = MESHLINK_EINTERNAL;
2163                 return -1;
2164         }
2165
2166         int port;
2167
2168         pthread_mutex_lock(&(mesh->mesh_mutex));
2169         port = atoi(mesh->myport);
2170         pthread_mutex_unlock(&(mesh->mesh_mutex));
2171
2172         return port;
2173 }
2174
2175 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2176         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2177                 meshlink_errno = MESHLINK_EINVAL;
2178                 return false;
2179         }
2180
2181         if(mesh->myport && port == atoi(mesh->myport)) {
2182                 return true;
2183         }
2184
2185         if(!try_bind(port)) {
2186                 meshlink_errno = MESHLINK_ENETWORK;
2187                 return false;
2188         }
2189
2190         devtool_trybind_probe();
2191
2192         bool rval = false;
2193
2194         pthread_mutex_lock(&(mesh->mesh_mutex));
2195
2196         if(mesh->threadstarted) {
2197                 meshlink_errno = MESHLINK_EINVAL;
2198                 goto done;
2199         }
2200
2201         free(mesh->myport);
2202         xasprintf(&mesh->myport, "%d", port);
2203
2204         /* Close down the network. This also deletes mesh->self. */
2205         close_network_connections(mesh);
2206
2207         /* Recreate mesh->self. */
2208         mesh->self = new_node();
2209         mesh->self->name = xstrdup(mesh->name);
2210         mesh->self->devclass = mesh->devclass;
2211         xasprintf(&mesh->myport, "%d", port);
2212
2213         if(!node_read_public_key(mesh, mesh->self)) {
2214                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2215                 meshlink_errno = MESHLINK_ESTORAGE;
2216                 free_node(mesh->self);
2217                 mesh->self = NULL;
2218                 goto done;
2219         } else if(!setup_network(mesh)) {
2220                 meshlink_errno = MESHLINK_ENETWORK;
2221                 goto done;
2222         }
2223
2224         /* Rebuild our own list of recent addresses */
2225         memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2226         add_local_addresses(mesh);
2227
2228         /* Write meshlink.conf with the updated port number */
2229         write_main_config_files(mesh);
2230
2231         rval = config_sync(mesh, "current");
2232
2233 done:
2234         pthread_mutex_unlock(&(mesh->mesh_mutex));
2235
2236         return rval && meshlink_get_port(mesh) == port;
2237 }
2238
2239 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2240         mesh->invitation_timeout = timeout;
2241 }
2242
2243 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2244         meshlink_submesh_t *s = NULL;
2245
2246         if(!mesh) {
2247                 meshlink_errno = MESHLINK_EINVAL;
2248                 return NULL;
2249         }
2250
2251         if(submesh) {
2252                 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2253
2254                 if(s != submesh) {
2255                         logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2256                         meshlink_errno = MESHLINK_EINVAL;
2257                         return NULL;
2258                 }
2259         } else {
2260                 s = (meshlink_submesh_t *)mesh->self->submesh;
2261         }
2262
2263         pthread_mutex_lock(&(mesh->mesh_mutex));
2264
2265         // Check validity of the new node's name
2266         if(!check_id(name)) {
2267                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2268                 meshlink_errno = MESHLINK_EINVAL;
2269                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2270                 return NULL;
2271         }
2272
2273         // Ensure no host configuration file with that name exists
2274         if(config_exists(mesh, "current", name)) {
2275                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2276                 meshlink_errno = MESHLINK_EEXIST;
2277                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2278                 return NULL;
2279         }
2280
2281         // Ensure no other nodes know about this name
2282         if(meshlink_get_node(mesh, name)) {
2283                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2284                 meshlink_errno = MESHLINK_EEXIST;
2285                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2286                 return NULL;
2287         }
2288
2289         // Get the local address
2290         char *address = get_my_hostname(mesh, flags);
2291
2292         if(!address) {
2293                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2294                 meshlink_errno = MESHLINK_ERESOLV;
2295                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2296                 return NULL;
2297         }
2298
2299         if(!refresh_invitation_key(mesh)) {
2300                 meshlink_errno = MESHLINK_EINTERNAL;
2301                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2302                 return NULL;
2303         }
2304
2305         char hash[64];
2306
2307         // Create a hash of the key.
2308         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2309         sha512(fingerprint, strlen(fingerprint), hash);
2310         b64encode_urlsafe(hash, hash, 18);
2311
2312         // Create a random cookie for this invitation.
2313         char cookie[25];
2314         randomize(cookie, 18);
2315
2316         // Create a filename that doesn't reveal the cookie itself
2317         char buf[18 + strlen(fingerprint)];
2318         char cookiehash[64];
2319         memcpy(buf, cookie, 18);
2320         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2321         sha512(buf, sizeof(buf), cookiehash);
2322         b64encode_urlsafe(cookiehash, cookiehash, 18);
2323
2324         b64encode_urlsafe(cookie, cookie, 18);
2325
2326         free(fingerprint);
2327
2328         /* Construct the invitation file */
2329         uint8_t outbuf[4096];
2330         packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2331
2332         packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2333         packmsg_add_str(&inv, name);
2334         packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2335         packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2336
2337         /* TODO: Add several host config files to bootstrap connections.
2338          * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2339          * and are not blacklisted.
2340          */
2341         config_t configs[5];
2342         memset(configs, 0, sizeof(configs));
2343         int count = 0;
2344
2345         if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2346                 count++;
2347         }
2348
2349         /* Append host config files to the invitation file */
2350         packmsg_add_array(&inv, count);
2351
2352         for(int i = 0; i < count; i++) {
2353                 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2354                 config_free(&configs[i]);
2355         }
2356
2357         config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2358
2359         if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2360                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2361                 meshlink_errno = MESHLINK_ESTORAGE;
2362                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2363                 return NULL;
2364         }
2365
2366         // Create an URL from the local address, key hash and cookie
2367         char *url;
2368         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2369         free(address);
2370
2371         pthread_mutex_unlock(&(mesh->mesh_mutex));
2372         return url;
2373 }
2374
2375 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2376         return meshlink_invite_ex(mesh, submesh, name, 0);
2377 }
2378
2379 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2380         if(!mesh || !invitation) {
2381                 meshlink_errno = MESHLINK_EINVAL;
2382                 return false;
2383         }
2384
2385         pthread_mutex_lock(&(mesh->mesh_mutex));
2386
2387         //Before doing meshlink_join make sure we are not connected to another mesh
2388         if(mesh->threadstarted) {
2389                 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2390                 meshlink_errno = MESHLINK_EINVAL;
2391                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2392                 return false;
2393         }
2394
2395         // 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.
2396         if(mesh->nodes->count > 1) {
2397                 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2398                 meshlink_errno = MESHLINK_EINVAL;
2399                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2400                 return false;
2401         }
2402
2403         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2404         char copy[strlen(invitation) + 1];
2405         strcpy(copy, invitation);
2406
2407         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2408
2409         char *slash = strchr(copy, '/');
2410
2411         if(!slash) {
2412                 goto invalid;
2413         }
2414
2415         *slash++ = 0;
2416
2417         if(strlen(slash) != 48) {
2418                 goto invalid;
2419         }
2420
2421         char *address = copy;
2422         char *port = NULL;
2423
2424         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2425                 goto invalid;
2426         }
2427
2428         // Generate a throw-away key for the invitation.
2429         ecdsa_t *key = ecdsa_generate();
2430
2431         if(!key) {
2432                 meshlink_errno = MESHLINK_EINTERNAL;
2433                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2434                 return false;
2435         }
2436
2437         char *b64key = ecdsa_get_base64_public_key(key);
2438         char *comma;
2439         mesh->sock = -1;
2440
2441         while(address && *address) {
2442                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2443                 comma = strchr(address, ',');
2444
2445                 if(comma) {
2446                         *comma++ = 0;
2447                 }
2448
2449                 // Split of the port
2450                 port = strrchr(address, ':');
2451
2452                 if(!port) {
2453                         goto invalid;
2454                 }
2455
2456                 *port++ = 0;
2457
2458                 // IPv6 address are enclosed in brackets, per RFC 3986
2459                 if(*address == '[') {
2460                         address++;
2461                         char *bracket = strchr(address, ']');
2462
2463                         if(!bracket) {
2464                                 goto invalid;
2465                         }
2466
2467                         *bracket++ = 0;
2468
2469                         if(*bracket) {
2470                                 goto invalid;
2471                         }
2472                 }
2473
2474                 // Connect to the meshlink daemon mentioned in the URL.
2475                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2476
2477                 if(ai) {
2478                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2479                                 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2480
2481                                 if(mesh->sock == -1) {
2482                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2483                                         meshlink_errno = MESHLINK_ENETWORK;
2484                                         continue;
2485                                 }
2486
2487                                 set_timeout(mesh->sock, 5000);
2488
2489                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2490                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2491                                         meshlink_errno = MESHLINK_ENETWORK;
2492                                         closesocket(mesh->sock);
2493                                         mesh->sock = -1;
2494                                         continue;
2495                                 }
2496                         }
2497
2498                         freeaddrinfo(ai);
2499                 } else {
2500                         meshlink_errno = MESHLINK_ERESOLV;
2501                 }
2502
2503                 if(mesh->sock != -1 || !comma) {
2504                         break;
2505                 }
2506
2507                 address = comma;
2508         }
2509
2510         if(mesh->sock == -1) {
2511                 pthread_mutex_unlock(&mesh->mesh_mutex);
2512                 return false;
2513         }
2514
2515         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2516
2517         // Tell him we have an invitation, and give him our throw-away key.
2518
2519         mesh->blen = 0;
2520
2521         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2522                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2523                 closesocket(mesh->sock);
2524                 meshlink_errno = MESHLINK_ENETWORK;
2525                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2526                 return false;
2527         }
2528
2529         free(b64key);
2530
2531         char hisname[4096] = "";
2532         int code, hismajor, hisminor = 0;
2533
2534         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) {
2535                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2536                 closesocket(mesh->sock);
2537                 meshlink_errno = MESHLINK_ENETWORK;
2538                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2539                 return false;
2540         }
2541
2542         // Check if the hash of the key he gave us matches the hash in the URL.
2543         char *fingerprint = mesh->line + 2;
2544         char hishash[64];
2545
2546         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2547                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2548                 meshlink_errno = MESHLINK_EINTERNAL;
2549                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2550                 return false;
2551         }
2552
2553         if(memcmp(hishash, mesh->hash, 18)) {
2554                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2555                 meshlink_errno = MESHLINK_EPEER;
2556                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2557                 return false;
2558
2559         }
2560
2561         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2562
2563         if(!hiskey) {
2564                 meshlink_errno = MESHLINK_EINTERNAL;
2565                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2566                 return false;
2567         }
2568
2569         // Start an SPTPS session
2570         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2571                 meshlink_errno = MESHLINK_EINTERNAL;
2572                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2573                 return false;
2574         }
2575
2576         // Feed rest of input buffer to SPTPS
2577         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2578                 meshlink_errno = MESHLINK_EPEER;
2579                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2580                 return false;
2581         }
2582
2583         int len;
2584
2585         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2586                 if(len < 0) {
2587                         if(errno == EINTR) {
2588                                 continue;
2589                         }
2590
2591                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2592                         meshlink_errno = MESHLINK_ENETWORK;
2593                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2594                         return false;
2595                 }
2596
2597                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2598                         meshlink_errno = MESHLINK_EPEER;
2599                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2600                         return false;
2601                 }
2602         }
2603
2604         sptps_stop(&mesh->sptps);
2605         ecdsa_free(hiskey);
2606         ecdsa_free(key);
2607         closesocket(mesh->sock);
2608
2609         if(!mesh->success) {
2610                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2611                 meshlink_errno = MESHLINK_EPEER;
2612                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2613                 return false;
2614         }
2615
2616         pthread_mutex_unlock(&(mesh->mesh_mutex));
2617         return true;
2618
2619 invalid:
2620         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2621         meshlink_errno = MESHLINK_EINVAL;
2622         pthread_mutex_unlock(&(mesh->mesh_mutex));
2623         return false;
2624 }
2625
2626 char *meshlink_export(meshlink_handle_t *mesh) {
2627         if(!mesh) {
2628                 meshlink_errno = MESHLINK_EINVAL;
2629                 return NULL;
2630         }
2631
2632         // Create a config file on the fly.
2633
2634         uint8_t buf[4096];
2635         packmsg_output_t out = {buf, sizeof(buf)};
2636         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2637         packmsg_add_str(&out, mesh->name);
2638         packmsg_add_str(&out, CORE_MESH);
2639
2640         pthread_mutex_lock(&(mesh->mesh_mutex));
2641
2642         packmsg_add_int32(&out, mesh->self->devclass);
2643         packmsg_add_bool(&out, mesh->self->status.blacklisted);
2644         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2645         packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2646
2647         uint32_t count = 0;
2648
2649         for(uint32_t i = 0; i < 5; i++) {
2650                 if(mesh->self->recent[i].sa.sa_family) {
2651                         count++;
2652                 } else {
2653                         break;
2654                 }
2655         }
2656
2657         packmsg_add_array(&out, count);
2658
2659         for(uint32_t i = 0; i < count; i++) {
2660                 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2661         }
2662
2663         pthread_mutex_unlock(&(mesh->mesh_mutex));
2664
2665         if(!packmsg_output_ok(&out)) {
2666                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2667                 meshlink_errno = MESHLINK_EINTERNAL;
2668                 return NULL;
2669         }
2670
2671         // Prepare a base64-encoded packmsg array containing our config file
2672
2673         uint32_t len = packmsg_output_size(&out, buf);
2674         uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2675         uint8_t *buf2 = xmalloc(len2);
2676         packmsg_output_t out2 = {buf2, len2};
2677         packmsg_add_array(&out2, 1);
2678         packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2679
2680         if(!packmsg_output_ok(&out2)) {
2681                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2682                 meshlink_errno = MESHLINK_EINTERNAL;
2683                 free(buf2);
2684                 return NULL;
2685         }
2686
2687         b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2688
2689         return (char *)buf2;
2690 }
2691
2692 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2693         if(!mesh || !data) {
2694                 meshlink_errno = MESHLINK_EINVAL;
2695                 return false;
2696         }
2697
2698         size_t datalen = strlen(data);
2699         uint8_t *buf = xmalloc(datalen);
2700         int buflen = b64decode(data, buf, datalen);
2701
2702         if(!buflen) {
2703                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2704                 meshlink_errno = MESHLINK_EPEER;
2705                 return false;
2706         }
2707
2708         packmsg_input_t in = {buf, buflen};
2709         uint32_t count = packmsg_get_array(&in);
2710
2711         if(!count) {
2712                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2713                 meshlink_errno = MESHLINK_EPEER;
2714                 return false;
2715         }
2716
2717         pthread_mutex_lock(&(mesh->mesh_mutex));
2718
2719         while(count--) {
2720                 const void *data;
2721                 uint32_t len = packmsg_get_bin_raw(&in, &data);
2722
2723                 if(!len) {
2724                         break;
2725                 }
2726
2727                 packmsg_input_t in2 = {data, len};
2728                 uint32_t version = packmsg_get_uint32(&in2);
2729                 char *name = packmsg_get_str_dup(&in2);
2730
2731                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2732                         free(name);
2733                         packmsg_input_invalidate(&in);
2734                         break;
2735                 }
2736
2737                 if(!check_id(name)) {
2738                         free(name);
2739                         break;
2740                 }
2741
2742                 node_t *n = lookup_node(mesh, name);
2743
2744                 if(n) {
2745                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2746                         free(name);
2747                         continue;
2748                 }
2749
2750                 n = new_node();
2751                 n->name = name;
2752
2753                 config_t config = {data, len};
2754
2755                 if(!node_read_from_config(mesh, n, &config)) {
2756                         free_node(n);
2757                         packmsg_input_invalidate(&in);
2758                         break;
2759                 }
2760
2761                 config_write(mesh, "current", n->name, &config, mesh->config_key);
2762                 node_add(mesh, n);
2763         }
2764
2765         pthread_mutex_unlock(&(mesh->mesh_mutex));
2766
2767         free(buf);
2768
2769         if(!packmsg_done(&in)) {
2770                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2771                 meshlink_errno = MESHLINK_EPEER;
2772                 return false;
2773         }
2774
2775         if(!config_sync(mesh, "current")) {
2776                 return false;
2777         }
2778
2779         return true;
2780 }
2781
2782 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2783         if(!mesh || !node) {
2784                 meshlink_errno = MESHLINK_EINVAL;
2785                 return;
2786         }
2787
2788         pthread_mutex_lock(&(mesh->mesh_mutex));
2789
2790         node_t *n;
2791         n = (node_t *)node;
2792
2793         if(n == mesh->self) {
2794                 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2795                 meshlink_errno = MESHLINK_EINVAL;
2796                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2797                 return;
2798         }
2799
2800         if(n->status.blacklisted) {
2801                 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2802                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2803                 return;
2804         }
2805
2806         n->status.blacklisted = true;
2807         node_write_config(mesh, n);
2808         config_sync(mesh, "current");
2809
2810         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2811
2812         //Immediately terminate any connections we have with the blacklisted node
2813         for list_each(connection_t, c, mesh->connections) {
2814                 if(c->node == n) {
2815                         terminate_connection(mesh, c, c->status.active);
2816                 }
2817         }
2818
2819         utcp_abort_all_connections(n->utcp);
2820
2821         n->mtu = 0;
2822         n->minmtu = 0;
2823         n->maxmtu = MTU;
2824         n->mtuprobes = 0;
2825         n->status.udp_confirmed = false;
2826
2827         if(n->status.reachable) {
2828                 update_node_status(mesh, n);
2829         }
2830
2831         pthread_mutex_unlock(&(mesh->mesh_mutex));
2832 }
2833
2834 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2835         if(!mesh || !node) {
2836                 meshlink_errno = MESHLINK_EINVAL;
2837                 return;
2838         }
2839
2840         pthread_mutex_lock(&(mesh->mesh_mutex));
2841
2842         node_t *n = (node_t *)node;
2843
2844         if(!n->status.blacklisted) {
2845                 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2846                 meshlink_errno = MESHLINK_EINVAL;
2847                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2848                 return;
2849         }
2850
2851         n->status.blacklisted = false;
2852         node_write_config(mesh, n);
2853         config_sync(mesh, "current");
2854
2855         if(n->status.reachable) {
2856                 update_node_status(mesh, n);
2857         }
2858
2859         pthread_mutex_unlock(&(mesh->mesh_mutex));
2860         return;
2861 }
2862
2863 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2864         mesh->default_blacklist = blacklist;
2865 }
2866
2867 /* Hint that a hostname may be found at an address
2868  * See header file for detailed comment.
2869  */
2870 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2871         if(!mesh || !node || !addr) {
2872                 meshlink_errno = EINVAL;
2873                 return;
2874         }
2875
2876         pthread_mutex_lock(&(mesh->mesh_mutex));
2877
2878         node_t *n = (node_t *)node;
2879         memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2880         memcpy(n->recent, addr, SALEN(*addr));
2881         node_write_config(mesh, n);
2882
2883         pthread_mutex_unlock(&(mesh->mesh_mutex));
2884         // @TODO do we want to fire off a connection attempt right away?
2885 }
2886
2887 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2888         (void)port;
2889         node_t *n = utcp->priv;
2890         meshlink_handle_t *mesh = n->mesh;
2891         return mesh->channel_accept_cb;
2892 }
2893
2894 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
2895         if(aio->data) {
2896                 if(aio->cb.buffer) {
2897                         aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
2898                 }
2899         } else {
2900                 if(aio->cb.fd) {
2901                         aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2902                 }
2903         }
2904 }
2905
2906 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2907         meshlink_channel_t *channel = connection->priv;
2908
2909         if(!channel) {
2910                 abort();
2911         }
2912
2913         node_t *n = channel->node;
2914         meshlink_handle_t *mesh = n->mesh;
2915
2916         if(n->status.destroyed) {
2917                 meshlink_channel_close(mesh, channel);
2918                 return len;
2919         }
2920
2921         const char *p = data;
2922         size_t left = len;
2923
2924         while(channel->aio_receive) {
2925                 meshlink_aio_buffer_t *aio = channel->aio_receive;
2926                 size_t todo = aio->len - aio->done;
2927
2928                 if(todo > left) {
2929                         todo = left;
2930                 }
2931
2932                 if(aio->data) {
2933                         memcpy((char *)aio->data + aio->done, p, todo);
2934                 } else {
2935                         ssize_t result = write(aio->fd, p, todo);
2936
2937                         if(result > 0) {
2938                                 todo = result;
2939                         }
2940                 }
2941
2942                 aio->done += todo;
2943
2944                 if(aio->done == aio->len) {
2945                         channel->aio_receive = aio->next;
2946                         aio_signal(mesh, channel, aio);
2947                         free(aio);
2948                 }
2949
2950                 p += todo;
2951                 left -= todo;
2952
2953                 if(!left && len) {
2954                         return len;
2955                 }
2956         }
2957
2958         if(channel->receive_cb) {
2959                 channel->receive_cb(mesh, channel, p, left);
2960         }
2961
2962         return len;
2963 }
2964
2965 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2966         node_t *n = utcp_connection->utcp->priv;
2967
2968         if(!n) {
2969                 abort();
2970         }
2971
2972         meshlink_handle_t *mesh = n->mesh;
2973
2974         if(!mesh->channel_accept_cb) {
2975                 return;
2976         }
2977
2978         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2979         channel->node = n;
2980         channel->c = utcp_connection;
2981
2982         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2983                 utcp_accept(utcp_connection, channel_recv, channel);
2984         } else {
2985                 free(channel);
2986         }
2987 }
2988
2989 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2990         node_t *n = utcp->priv;
2991
2992         if(n->status.destroyed) {
2993                 return -1;
2994         }
2995
2996         meshlink_handle_t *mesh = n->mesh;
2997         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2998 }
2999
3000 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3001         if(!mesh || !channel) {
3002                 meshlink_errno = MESHLINK_EINVAL;
3003                 return;
3004         }
3005
3006         channel->receive_cb = cb;
3007 }
3008
3009 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3010         (void)mesh;
3011         node_t *n = (node_t *)source;
3012
3013         if(!n->utcp) {
3014                 abort();
3015         }
3016
3017         utcp_recv(n->utcp, data, len);
3018 }
3019
3020 static void channel_poll(struct utcp_connection *connection, size_t len) {
3021         meshlink_channel_t *channel = connection->priv;
3022
3023         if(!channel) {
3024                 abort();
3025         }
3026
3027         node_t *n = channel->node;
3028         meshlink_handle_t *mesh = n->mesh;
3029         meshlink_aio_buffer_t *aio = channel->aio_send;
3030
3031         if(aio) {
3032                 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3033                 size_t left = aio->len - aio->done;
3034                 ssize_t sent;
3035
3036                 if(len > left) {
3037                         len = left;
3038                 }
3039
3040                 if(aio->data) {
3041                         sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3042                 } else {
3043                         char buf[65536];
3044                         size_t todo = utcp_get_sndbuf_free(connection);
3045
3046                         if(todo > left) {
3047                                 todo = left;
3048                         }
3049
3050                         if(todo > sizeof(buf)) {
3051                                 todo = sizeof(buf);
3052                         }
3053
3054                         ssize_t result = read(aio->fd, buf, todo);
3055
3056                         if(result > 0) {
3057                                 sent = utcp_send(connection, buf, result);
3058                         } else {
3059                                 sent = result;
3060                         }
3061                 }
3062
3063                 if(sent >= 0) {
3064                         aio->done += sent;
3065                 }
3066
3067                 /* If the buffer is now completely sent, call the callback and dispose of it. */
3068                 if(aio->done >= aio->len) {
3069                         channel->aio_send = aio->next;
3070                         aio_signal(mesh, channel, aio);
3071                         free(aio);
3072                 }
3073         } else {
3074                 if(channel->poll_cb) {
3075                         channel->poll_cb(mesh, channel, len);
3076                 } else {
3077                         utcp_set_poll_cb(connection, NULL);
3078                 }
3079         }
3080 }
3081
3082 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3083         if(!mesh || !channel) {
3084                 meshlink_errno = MESHLINK_EINVAL;
3085                 return;
3086         }
3087
3088         pthread_mutex_lock(&mesh->mesh_mutex);
3089         channel->poll_cb = cb;
3090         utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3091         pthread_mutex_unlock(&mesh->mesh_mutex);
3092 }
3093
3094 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3095         if(!mesh) {
3096                 meshlink_errno = MESHLINK_EINVAL;
3097                 return;
3098         }
3099
3100         pthread_mutex_lock(&mesh->mesh_mutex);
3101         mesh->channel_accept_cb = cb;
3102         mesh->receive_cb = channel_receive;
3103
3104         for splay_each(node_t, n, mesh->nodes) {
3105                 if(!n->utcp && n != mesh->self) {
3106                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3107                 }
3108         }
3109
3110         pthread_mutex_unlock(&mesh->mesh_mutex);
3111 }
3112
3113 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3114         (void)mesh;
3115
3116         if(!channel) {
3117                 meshlink_errno = MESHLINK_EINVAL;
3118                 return;
3119         }
3120
3121         pthread_mutex_lock(&mesh->mesh_mutex);
3122         utcp_set_sndbuf(channel->c, size);
3123         pthread_mutex_unlock(&mesh->mesh_mutex);
3124 }
3125
3126 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3127         (void)mesh;
3128
3129         if(!channel) {
3130                 meshlink_errno = MESHLINK_EINVAL;
3131                 return;
3132         }
3133
3134         pthread_mutex_lock(&mesh->mesh_mutex);
3135         utcp_set_rcvbuf(channel->c, size);
3136         pthread_mutex_unlock(&mesh->mesh_mutex);
3137 }
3138
3139 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) {
3140         if(data || len) {
3141                 abort();        // TODO: handle non-NULL data
3142         }
3143
3144         if(!mesh || !node) {
3145                 meshlink_errno = MESHLINK_EINVAL;
3146                 return NULL;
3147         }
3148
3149         pthread_mutex_lock(&mesh->mesh_mutex);
3150
3151         node_t *n = (node_t *)node;
3152
3153         if(!n->utcp) {
3154                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3155                 mesh->receive_cb = channel_receive;
3156
3157                 if(!n->utcp) {
3158                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3159                         pthread_mutex_unlock(&mesh->mesh_mutex);
3160                         return NULL;
3161                 }
3162         }
3163
3164         if(n->status.blacklisted) {
3165                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3166                 pthread_mutex_unlock(&mesh->mesh_mutex);
3167                 return NULL;
3168         }
3169
3170         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3171         channel->node = n;
3172         channel->receive_cb = cb;
3173         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3174
3175         pthread_mutex_unlock(&mesh->mesh_mutex);
3176
3177         if(!channel->c) {
3178                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3179                 free(channel);
3180                 return NULL;
3181         }
3182
3183         return channel;
3184 }
3185
3186 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) {
3187         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3188 }
3189
3190 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3191         if(!mesh || !channel) {
3192                 meshlink_errno = MESHLINK_EINVAL;
3193                 return;
3194         }
3195
3196         pthread_mutex_lock(&mesh->mesh_mutex);
3197         utcp_shutdown(channel->c, direction);
3198         pthread_mutex_unlock(&mesh->mesh_mutex);
3199 }
3200
3201 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3202         if(!mesh || !channel) {
3203                 meshlink_errno = MESHLINK_EINVAL;
3204                 return;
3205         }
3206
3207         pthread_mutex_lock(&mesh->mesh_mutex);
3208
3209         utcp_close(channel->c);
3210
3211         /* Clean up any outstanding AIO buffers. */
3212         for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3213                 next = aio->next;
3214                 aio_signal(mesh, channel, aio);
3215                 free(aio);
3216         }
3217
3218         for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3219                 next = aio->next;
3220                 aio_signal(mesh, channel, aio);
3221                 free(aio);
3222         }
3223
3224         pthread_mutex_unlock(&mesh->mesh_mutex);
3225
3226         free(channel);
3227 }
3228
3229 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3230         if(!mesh || !channel) {
3231                 meshlink_errno = MESHLINK_EINVAL;
3232                 return -1;
3233         }
3234
3235         if(!len) {
3236                 return 0;
3237         }
3238
3239         if(!data) {
3240                 meshlink_errno = MESHLINK_EINVAL;
3241                 return -1;
3242         }
3243
3244         // TODO: more finegrained locking.
3245         // Ideally we want to put the data into the UTCP connection's send buffer.
3246         // Then, preferably only if there is room in the receiver window,
3247         // kick the meshlink thread to go send packets.
3248
3249         ssize_t retval;
3250
3251         pthread_mutex_lock(&mesh->mesh_mutex);
3252
3253         /* Disallow direct calls to utcp_send() while we still have AIO active. */
3254         if(channel->aio_send) {
3255                 retval = 0;
3256         } else {
3257                 retval = utcp_send(channel->c, data, len);
3258         }
3259
3260         pthread_mutex_unlock(&mesh->mesh_mutex);
3261
3262         if(retval < 0) {
3263                 meshlink_errno = MESHLINK_ENETWORK;
3264         }
3265
3266         return retval;
3267 }
3268
3269 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) {
3270         if(!mesh || !channel) {
3271                 meshlink_errno = MESHLINK_EINVAL;
3272                 return false;
3273         }
3274
3275         if(!len || !data) {
3276                 meshlink_errno = MESHLINK_EINVAL;
3277                 return false;
3278         }
3279
3280         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3281         aio->data = data;
3282         aio->len = len;
3283         aio->cb.buffer = cb;
3284         aio->priv = priv;
3285
3286         pthread_mutex_lock(&mesh->mesh_mutex);
3287
3288         /* Append the AIO buffer descriptor to the end of the chain */
3289         meshlink_aio_buffer_t **p = &channel->aio_send;
3290
3291         while(*p) {
3292                 p = &(*p)->next;
3293         }
3294
3295         *p = aio;
3296
3297         /* Ensure the poll callback is set, and call it right now to push data if possible */
3298         utcp_set_poll_cb(channel->c, channel_poll);
3299         channel_poll(channel->c, len);
3300
3301         pthread_mutex_unlock(&mesh->mesh_mutex);
3302
3303         return true;
3304 }
3305
3306 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) {
3307         if(!mesh || !channel) {
3308                 meshlink_errno = MESHLINK_EINVAL;
3309                 return false;
3310         }
3311
3312         if(!len || fd == -1) {
3313                 meshlink_errno = MESHLINK_EINVAL;
3314                 return false;
3315         }
3316
3317         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3318         aio->fd = fd;
3319         aio->len = len;
3320         aio->cb.fd = cb;
3321         aio->priv = priv;
3322
3323         pthread_mutex_lock(&mesh->mesh_mutex);
3324
3325         /* Append the AIO buffer descriptor to the end of the chain */
3326         meshlink_aio_buffer_t **p = &channel->aio_send;
3327
3328         while(*p) {
3329                 p = &(*p)->next;
3330         }
3331
3332         *p = aio;
3333
3334         /* Ensure the poll callback is set, and call it right now to push data if possible */
3335         utcp_set_poll_cb(channel->c, channel_poll);
3336         channel_poll(channel->c, len);
3337
3338         pthread_mutex_unlock(&mesh->mesh_mutex);
3339
3340         return true;
3341 }
3342
3343 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) {
3344         if(!mesh || !channel) {
3345                 meshlink_errno = MESHLINK_EINVAL;
3346                 return false;
3347         }
3348
3349         if(!len || !data) {
3350                 meshlink_errno = MESHLINK_EINVAL;
3351                 return false;
3352         }
3353
3354         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3355         aio->data = data;
3356         aio->len = len;
3357         aio->cb.buffer = cb;
3358         aio->priv = priv;
3359
3360         pthread_mutex_lock(&mesh->mesh_mutex);
3361
3362         /* Append the AIO buffer descriptor to the end of the chain */
3363         meshlink_aio_buffer_t **p = &channel->aio_receive;
3364
3365         while(*p) {
3366                 p = &(*p)->next;
3367         }
3368
3369         *p = aio;
3370
3371         pthread_mutex_unlock(&mesh->mesh_mutex);
3372
3373         return true;
3374 }
3375
3376 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) {
3377         if(!mesh || !channel) {
3378                 meshlink_errno = MESHLINK_EINVAL;
3379                 return false;
3380         }
3381
3382         if(!len || fd == -1) {
3383                 meshlink_errno = MESHLINK_EINVAL;
3384                 return false;
3385         }
3386
3387         meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3388         aio->fd = fd;
3389         aio->len = len;
3390         aio->cb.fd = cb;
3391         aio->priv = priv;
3392
3393         pthread_mutex_lock(&mesh->mesh_mutex);
3394
3395         /* Append the AIO buffer descriptor to the end of the chain */
3396         meshlink_aio_buffer_t **p = &channel->aio_receive;
3397
3398         while(*p) {
3399                 p = &(*p)->next;
3400         }
3401
3402         *p = aio;
3403
3404         pthread_mutex_unlock(&mesh->mesh_mutex);
3405
3406         return true;
3407 }
3408
3409 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3410         if(!mesh || !channel) {
3411                 meshlink_errno = MESHLINK_EINVAL;
3412                 return -1;
3413         }
3414
3415         return channel->c->flags;
3416 }
3417
3418 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3419         if(!mesh || !channel) {
3420                 meshlink_errno = MESHLINK_EINVAL;
3421                 return -1;
3422         }
3423
3424         return utcp_get_sendq(channel->c);
3425 }
3426
3427 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3428         if(!mesh || !channel) {
3429                 meshlink_errno = MESHLINK_EINVAL;
3430                 return -1;
3431         }
3432
3433         return utcp_get_recvq(channel->c);
3434 }
3435
3436 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3437         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3438                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3439         }
3440
3441         if(mesh->node_status_cb) {
3442                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3443         }
3444
3445         if(mesh->node_pmtu_cb) {
3446                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3447         }
3448 }
3449
3450 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3451         if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3452                 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3453         }
3454 }
3455
3456 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3457         if(!mesh->node_duplicate_cb || n->status.duplicate) {
3458                 return;
3459         }
3460
3461         n->status.duplicate = true;
3462         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3463 }
3464
3465 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3466 #if HAVE_CATTA
3467
3468         if(!mesh) {
3469                 meshlink_errno = MESHLINK_EINVAL;
3470                 return;
3471         }
3472
3473         pthread_mutex_lock(&mesh->mesh_mutex);
3474
3475         if(mesh->discovery == enable) {
3476                 goto end;
3477         }
3478
3479         if(mesh->threadstarted) {
3480                 if(enable) {
3481                         discovery_start(mesh);
3482                 } else {
3483                         discovery_stop(mesh);
3484                 }
3485         }
3486
3487         mesh->discovery = enable;
3488
3489 end:
3490         pthread_mutex_unlock(&mesh->mesh_mutex);
3491 #else
3492         (void)mesh;
3493         (void)enable;
3494         meshlink_errno = MESHLINK_ENOTSUP;
3495 #endif
3496 }
3497
3498 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3499         if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3500                 meshlink_errno = EINVAL;
3501                 return;
3502         }
3503
3504         if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3505                 meshlink_errno = EINVAL;
3506                 return;
3507         }
3508
3509         pthread_mutex_lock(&mesh->mesh_mutex);
3510         mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3511         mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3512         pthread_mutex_unlock(&mesh->mesh_mutex);
3513 }
3514
3515 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3516         (void)online;
3517
3518         if(!mesh->connections || !mesh->loop.running) {
3519                 return;
3520         }
3521
3522         retry(mesh);
3523 }
3524
3525 static void __attribute__((constructor)) meshlink_init(void) {
3526         crypto_init();
3527 }
3528
3529 static void __attribute__((destructor)) meshlink_exit(void) {
3530         crypto_exit();
3531 }