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