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