]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Add support for encrypted storage.
[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
40 #ifndef MSG_NOSIGNAL
41 #define MSG_NOSIGNAL 0
42 #endif
43
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 static void *socket_in_netns_thread(void *arg) {
129         struct socket_in_netns_params *params = arg;
130
131         if(setns(params->netns, CLONE_NEWNET) == -1) {
132                 meshlink_errno = MESHLINK_EINVAL;
133         } else {
134                 params->fd = socket(params->domain, params->type, params->protocol);
135         }
136
137         return NULL;
138 }
139
140 static int socket_in_netns(int domain, int type, int protocol, int netns) {
141         if(netns == -1) {
142                 return socket(domain, type, protocol);
143         }
144
145         struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
146
147         pthread_t thr;
148
149         if(pthread_create(&thr, NULL, socket_in_netns_thread, &params) == 0) {
150                 pthread_join(thr, NULL);
151         }
152
153         return params.fd;
154 }
155
156 // Find out what local address a socket would use if we connect to the given address.
157 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
158 // of both endpoints, but this will actually not send any UDP packet.
159 static bool getlocaladdr(char *destaddr, struct sockaddr *sn, socklen_t *sl, int netns) {
160         struct addrinfo *rai = NULL;
161         const struct addrinfo hint = {
162                 .ai_family = AF_UNSPEC,
163                 .ai_socktype = SOCK_DGRAM,
164                 .ai_protocol = IPPROTO_UDP,
165         };
166
167         if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
168                 return false;
169         }
170
171         int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
172
173         if(sock == -1) {
174                 freeaddrinfo(rai);
175                 return false;
176         }
177
178         if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
179                 closesocket(sock);
180                 freeaddrinfo(rai);
181                 return false;
182         }
183
184         freeaddrinfo(rai);
185
186         if(getsockname(sock, sn, sl)) {
187                 closesocket(sock);
188                 return false;
189         }
190
191         closesocket(sock);
192         return true;
193 }
194
195 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
196         struct sockaddr_storage sn;
197         socklen_t sl = sizeof(sn);
198
199         if(!getlocaladdr(destaddr, (struct sockaddr *)&sn, &sl, netns)) {
200                 return false;
201         }
202
203         if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
204                 return false;
205         }
206
207         return true;
208 }
209
210 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
211         return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
212 }
213
214 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
215         char *hostname = NULL;
216
217         logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
218         struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
219         static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
220         char line[256];
221
222         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
223                 if(family != AF_UNSPEC && aip->ai_family != family) {
224                         continue;
225                 }
226
227                 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
228
229                 if(s >= 0) {
230                         set_timeout(s, 5000);
231
232                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
233                                 closesocket(s);
234                                 s = -1;
235                         }
236                 }
237
238                 if(s >= 0) {
239                         send(s, request, sizeof(request) - 1, 0);
240                         int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
241
242                         if(len > 0) {
243                                 line[len] = 0;
244
245                                 if(line[len - 1] == '\n') {
246                                         line[--len] = 0;
247                                 }
248
249                                 char *p = strrchr(line, '\n');
250
251                                 if(p && p[1]) {
252                                         hostname = xstrdup(p + 1);
253                                 }
254                         }
255
256                         closesocket(s);
257
258                         if(hostname) {
259                                 break;
260                         }
261                 }
262         }
263
264         if(ai) {
265                 freeaddrinfo(ai);
266         }
267
268         // Check that the hostname is reasonable
269         if(hostname && !is_valid_hostname(hostname)) {
270                 free(hostname);
271                 hostname = NULL;
272         }
273
274         if(!hostname) {
275                 meshlink_errno = MESHLINK_ERESOLV;
276         }
277
278         return hostname;
279 }
280
281 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
282         (void)mesh;
283
284         // Determine address of the local interface used for outgoing connections.
285         char localaddr[NI_MAXHOST];
286         bool success = false;
287
288         if(family == AF_INET) {
289                 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
290         } else if(family == AF_INET6) {
291                 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
292         }
293
294         if(!success) {
295                 meshlink_errno = MESHLINK_ENETWORK;
296                 return NULL;
297         }
298
299         return xstrdup(localaddr);
300 }
301
302 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
303         for(int i = 0; i < n; i++) {
304                 if(!host[i]) {
305                         continue;
306                 }
307
308                 // Ignore duplicate hostnames
309                 bool found = false;
310
311                 for(int j = 0; j < i; j++) {
312                         if(!host[j]) {
313                                 continue;
314                         }
315
316                         if(strcmp(host[i], host[j])) {
317                                 continue;
318                         }
319
320                         if(strcmp(port[i], port[j])) {
321                                 continue;
322                         }
323
324                         found = true;
325                         break;
326                 }
327
328                 if(found) {
329                         free(host[i]);
330                         free(port[i]);
331                         host[i] = NULL;
332                         port[i] = NULL;
333                         continue;
334                 }
335         }
336 }
337
338 // This gets the hostname part for use in invitation URLs
339 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
340         char *hostname[4] = {NULL};
341         char *port[4] = {NULL};
342         char *hostport = NULL;
343
344         if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
345                 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
346         }
347
348         if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
349                 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
350         }
351
352         // Add local addresses if requested
353         if(flags & MESHLINK_INVITE_LOCAL) {
354                 if(flags & MESHLINK_INVITE_IPV4) {
355                         hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
356                 }
357
358                 if(flags & MESHLINK_INVITE_IPV6) {
359                         hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
360                 }
361         }
362
363         // Add public/canonical addresses if requested
364         if(flags & MESHLINK_INVITE_PUBLIC) {
365                 // Try the CanonicalAddress first
366                 get_canonical_address(mesh->self, &hostname[2], &port[2]);
367
368                 if(!hostname[2]) {
369                         if(flags & MESHLINK_INVITE_IPV4) {
370                                 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
371                         }
372
373                         if(flags & MESHLINK_INVITE_IPV6) {
374                                 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
375                         }
376                 }
377         }
378
379         for(int i = 0; i < 4; i++) {
380                 // Ensure we always have a port number
381                 if(hostname[i] && !port[i]) {
382                         port[i] = xstrdup(mesh->myport);
383                 }
384         }
385
386         remove_duplicate_hostnames(hostname, port, 4);
387
388         if(!(flags & MESHLINK_INVITE_NUMERIC)) {
389                 for(int i = 0; i < 4; i++) {
390                         if(!hostname[i]) {
391                                 continue;
392                         }
393
394                         // Convert what we have to a sockaddr
395                         struct addrinfo *ai_in, *ai_out;
396                         struct addrinfo hint = {
397                                 .ai_family = AF_UNSPEC,
398                                 .ai_flags = AI_NUMERICSERV,
399                                 .ai_socktype = SOCK_STREAM,
400                         };
401                         int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
402
403                         if(err || !ai_in) {
404                                 continue;
405                         }
406
407                         // Convert it to a hostname
408                         char resolved_host[NI_MAXHOST];
409                         char resolved_port[NI_MAXSERV];
410                         err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
411
412                         if(err) {
413                                 freeaddrinfo(ai_in);
414                                 continue;
415                         }
416
417                         // Convert the hostname back to a sockaddr
418                         hint.ai_family = ai_in->ai_family;
419                         err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
420
421                         if(err || !ai_out) {
422                                 freeaddrinfo(ai_in);
423                                 continue;
424                         }
425
426                         // Check if it's still the same sockaddr
427                         if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
428                                 freeaddrinfo(ai_in);
429                                 freeaddrinfo(ai_out);
430                                 continue;
431                         }
432
433                         // Yes: replace the hostname with the resolved one
434                         free(hostname[i]);
435                         hostname[i] = xstrdup(resolved_host);
436
437                         freeaddrinfo(ai_in);
438                         freeaddrinfo(ai_out);
439                 }
440         }
441
442         // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
443         remove_duplicate_hostnames(hostname, port, 4);
444
445         // Concatenate all unique address to the hostport string
446         for(int i = 0; i < 4; i++) {
447                 if(!hostname[i]) {
448                         continue;
449                 }
450
451                 // Ensure we have the same addresses in our own host config file.
452                 char *tmphostport;
453                 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
454                 /// TODO: FIX
455                 //config_add_string(&mesh->config, "Address", tmphostport);
456                 free(tmphostport);
457
458                 // Append the address to the hostport string
459                 char *newhostport;
460                 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
461                 free(hostport);
462                 hostport = newhostport;
463
464                 free(hostname[i]);
465                 free(port[i]);
466         }
467
468         return hostport;
469 }
470
471 static bool try_bind(int port) {
472         struct addrinfo *ai = NULL;
473         struct addrinfo hint = {
474                 .ai_flags = AI_PASSIVE,
475                 .ai_family = AF_UNSPEC,
476                 .ai_socktype = SOCK_STREAM,
477                 .ai_protocol = IPPROTO_TCP,
478         };
479
480         char portstr[16];
481         snprintf(portstr, sizeof(portstr), "%d", port);
482
483         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
484                 return false;
485         }
486
487         //while(ai) {
488         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
489                 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
490
491                 if(!fd) {
492                         freeaddrinfo(ai);
493                         return false;
494                 }
495
496                 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
497                 closesocket(fd);
498
499                 if(result) {
500                         freeaddrinfo(ai);
501                         return false;
502                 }
503         }
504
505         freeaddrinfo(ai);
506         return true;
507 }
508
509 int check_port(meshlink_handle_t *mesh) {
510         for(int i = 0; i < 1000; i++) {
511                 int port = 0x1000 + (rand() & 0x7fff);
512
513                 if(try_bind(port)) {
514                         free(mesh->myport);
515                         xasprintf(&mesh->myport, "%d", port);
516                         return port;
517                 }
518         }
519
520         meshlink_errno = MESHLINK_ENETWORK;
521         logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
522         return 0;
523 }
524
525 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
526         packmsg_input_t in = {buf, len};
527         uint32_t version = packmsg_get_uint32(&in);
528
529         if(version != MESHLINK_INVITATION_VERSION) {
530                 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
531                 return false;
532         }
533
534         char *name = packmsg_get_str_dup(&in);
535         packmsg_skip_element(&in); /* submesh */
536         int32_t devclass = packmsg_get_int32(&in);
537         uint32_t count = packmsg_get_array(&in);
538
539         if(!name) {
540                 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
541                 return false;
542         }
543
544         if(!check_id(name)) {
545                 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
546                 return false;
547         }
548
549         if(!count) {
550                 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
551                 return false;
552         }
553
554         // Initialize configuration directory
555         if(!config_init(mesh)) {
556                 return false;
557         }
558
559         // Write main config file
560         uint8_t outbuf[4096];
561         packmsg_output_t out = {outbuf, sizeof(outbuf)};
562         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
563         packmsg_add_str(&out, name);
564         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
565         packmsg_add_uint16(&out, atoi(mesh->myport));
566
567         config_t config = {outbuf, packmsg_output_size(&out, outbuf)};
568
569         if(!main_config_write(mesh, &config)) {
570                 return false;
571         }
572
573         // Write our own host config file
574         out.ptr = outbuf;
575         out.len = sizeof(outbuf);
576         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
577         packmsg_add_str(&out, name);
578         packmsg_add_str(&out, CORE_MESH);
579         packmsg_add_int32(&out, devclass);
580         packmsg_add_bool(&out, false);
581         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
582         packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
583         packmsg_add_array(&out, 0);
584
585         config.len = packmsg_output_size(&out, outbuf);
586
587         if(!config_write(mesh, name, &config)) {
588                 return false;
589         }
590
591         // Write host config files
592         while(count--) {
593                 const void *data;
594                 uint32_t len = packmsg_get_bin_raw(&in, &data);
595
596                 if(!len) {
597                         logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
598                         return false;
599                 }
600
601                 packmsg_input_t in2 = {data, len};
602                 uint32_t version = packmsg_get_uint32(&in2);
603
604                 if(version != MESHLINK_CONFIG_VERSION) {
605                         logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
606                         return false;
607                 }
608
609                 char *host = packmsg_get_str_dup(&in2);
610
611                 if(!check_id(host)) {
612                         logger(mesh, MESHLINK_ERROR, "Invalid node name in invitation file!\n");
613                         free(host);
614                         return false;
615                 }
616
617                 if(!strcmp(host, name)) {
618                         logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
619                         free(host);
620                         return false;
621                 }
622
623                 config_t config = {data, len};
624                 config_write(mesh, host, &config);
625
626                 node_t *n = new_node();
627                 n->name = host;
628                 node_read_full(mesh, n);
629                 n->devclass = mesh->devclass;
630                 node_add(mesh, n);
631         }
632
633         sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
634
635         free(mesh->name);
636         free(mesh->self->name);
637         mesh->name = xstrdup(name);
638         mesh->self->name = xstrdup(name);
639
640         logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
641
642         load_all_nodes(mesh);
643
644         return true;
645 }
646
647 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
648         (void)type;
649         meshlink_handle_t *mesh = handle;
650         const char *ptr = data;
651
652         while(len) {
653                 int result = send(mesh->sock, ptr, len, 0);
654
655                 if(result == -1 && errno == EINTR) {
656                         continue;
657                 } else if(result <= 0) {
658                         return false;
659                 }
660
661                 ptr += result;
662                 len -= result;
663         }
664
665         return true;
666 }
667
668 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
669         meshlink_handle_t *mesh = handle;
670
671         switch(type) {
672         case SPTPS_HANDSHAKE:
673                 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
674
675         case 0:
676                 return finalize_join(mesh, msg, len);
677
678         case 1:
679                 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
680                 shutdown(mesh->sock, SHUT_RDWR);
681                 mesh->success = true;
682                 break;
683
684         default:
685                 return false;
686         }
687
688         return true;
689 }
690
691 static bool recvline(meshlink_handle_t *mesh, size_t len) {
692         char *newline = NULL;
693
694         if(!mesh->sock) {
695                 abort();
696         }
697
698         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
699                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
700
701                 if(result == -1 && errno == EINTR) {
702                         continue;
703                 } else if(result <= 0) {
704                         return false;
705                 }
706
707                 mesh->blen += result;
708         }
709
710         if((size_t)(newline - mesh->buffer) >= len) {
711                 return false;
712         }
713
714         len = newline - mesh->buffer;
715
716         memcpy(mesh->line, mesh->buffer, len);
717         mesh->line[len] = 0;
718         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
719         mesh->blen -= len + 1;
720
721         return true;
722 }
723 static bool sendline(int fd, char *format, ...) {
724         static char buffer[4096];
725         char *p = buffer;
726         int blen = 0;
727         va_list ap;
728
729         va_start(ap, format);
730         blen = vsnprintf(buffer, sizeof(buffer), format, ap);
731         va_end(ap);
732
733         if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
734                 return false;
735         }
736
737         buffer[blen] = '\n';
738         blen++;
739
740         while(blen) {
741                 int result = send(fd, p, blen, MSG_NOSIGNAL);
742
743                 if(result == -1 && errno == EINTR) {
744                         continue;
745                 } else if(result <= 0) {
746                         return false;
747                 }
748
749                 p += result;
750                 blen -= result;
751         }
752
753         return true;
754 }
755
756 static const char *errstr[] = {
757         [MESHLINK_OK] = "No error",
758         [MESHLINK_EINVAL] = "Invalid argument",
759         [MESHLINK_ENOMEM] = "Out of memory",
760         [MESHLINK_ENOENT] = "No such node",
761         [MESHLINK_EEXIST] = "Node already exists",
762         [MESHLINK_EINTERNAL] = "Internal error",
763         [MESHLINK_ERESOLV] = "Could not resolve hostname",
764         [MESHLINK_ESTORAGE] = "Storage error",
765         [MESHLINK_ENETWORK] = "Network error",
766         [MESHLINK_EPEER] = "Error communicating with peer",
767         [MESHLINK_ENOTSUP] = "Operation not supported",
768         [MESHLINK_EBUSY] = "MeshLink instance already in use",
769 };
770
771 const char *meshlink_strerror(meshlink_errno_t err) {
772         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
773                 return "Invalid error code";
774         }
775
776         return errstr[err];
777 }
778
779 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
780         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
781
782         mesh->private_key = ecdsa_generate();
783         mesh->invitation_key = ecdsa_generate();
784
785         if(!mesh->private_key || !mesh->invitation_key) {
786                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
787                 meshlink_errno = MESHLINK_EINTERNAL;
788                 return false;
789         }
790
791         logger(mesh, MESHLINK_DEBUG, "Done.\n");
792
793         return true;
794 }
795
796 static struct timeval idle(event_loop_t *loop, void *data) {
797         (void)loop;
798         meshlink_handle_t *mesh = data;
799         struct timeval t, tmin = {3600, 0};
800
801         for splay_each(node_t, n, mesh->nodes) {
802                 if(!n->utcp) {
803                         continue;
804                 }
805
806                 t = utcp_timeout(n->utcp);
807
808                 if(timercmp(&t, &tmin, <)) {
809                         tmin = t;
810                 }
811         }
812
813         return tmin;
814 }
815
816 // Get our local address(es) by simulating connecting to an Internet host.
817 static void add_local_addresses(meshlink_handle_t *mesh) {
818         struct sockaddr_storage sn;
819         socklen_t sl = sizeof(sn);
820
821         // IPv4 example.org
822
823         if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl, mesh->netns)) {
824                 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
825                 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
826         }
827
828         // IPv6 example.org
829
830         sl = sizeof(sn);
831
832         if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl, mesh->netns)) {
833                 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
834                 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
835         }
836 }
837
838 #if 0
839 static bool meshlink_write_config(meshlink_handle_t *mesh) {
840         uint8_t buf[1024];
841         packmsg_output_t out = {buf, sizeof buf};
842         packmsg_add_str(&out, mesh->name);
843         packmsg_add_uint32(&out, mesh->devclass);
844         packmsg_add_uint16(&out, mesh->port);
845         packmsg_add_bin(&out, ecdsa, sizeof(ecdsa));
846         uint32_t len = packmsg_output_size(&out, buf);
847
848         if(!len) {
849                 logger(mesh, MESHLINK_DEBUG, "Could not create configuration data\n",);
850                 meshlink_errno = MESHLINK_EINTERNAL;
851                 return false;
852         }
853 }
854 #endif
855
856 static bool meshlink_setup(meshlink_handle_t *mesh) {
857         if(!config_init(mesh)) {
858                 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s: %s\n", mesh->confbase, strerror(errno));
859                 meshlink_errno = MESHLINK_ESTORAGE;
860                 return false;
861         }
862
863         if(!ecdsa_keygen(mesh)) {
864                 meshlink_errno = MESHLINK_EINTERNAL;
865                 return false;
866         }
867
868         if(check_port(mesh) == 0) {
869                 meshlink_errno = MESHLINK_ENETWORK;
870                 return false;
871         }
872
873         /* Create a node for ourself */
874
875         mesh->self = new_node();
876         mesh->self->name = xstrdup(mesh->name);
877         mesh->self->devclass = mesh->devclass;
878         mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
879
880         // Write the main config file
881         uint8_t buf[4096];
882         packmsg_output_t out = {buf, sizeof(buf)};
883
884         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
885         packmsg_add_str(&out, mesh->name);
886         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
887         packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
888         packmsg_add_uint16(&out, atoi(mesh->myport));
889
890         config_t config = {buf, packmsg_output_size(&out, buf)};
891
892         if(!main_config_write(mesh, &config)) {
893                 return false;
894         }
895
896         // Write our own host config file
897         out.ptr = buf;
898         out.len = sizeof(buf);
899         packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
900         packmsg_add_str(&out, mesh->name);
901         packmsg_add_int32(&out, mesh->devclass);
902         packmsg_add_bool(&out, false);
903         packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
904         packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
905         packmsg_add_array(&out, 0);
906
907         config.len = packmsg_output_size(&out, buf);
908
909         if(!config_write(mesh, mesh->name, &config)) {
910                 return false;
911         }
912
913         return true;
914 }
915
916 static bool meshlink_read_config(meshlink_handle_t *mesh) {
917         // Open the configuration file and lock it
918         if(!main_config_lock(mesh)) {
919                 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
920                 meshlink_errno = MESHLINK_ESTORAGE;
921                 return false;
922         }
923
924         config_t config;
925
926         if(!main_config_read(mesh, &config)) {
927                 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
928                 return false;
929         }
930
931         packmsg_input_t in = {config.buf, config.len};
932         const void *private_key;
933         const void *invitation_key;
934
935         uint32_t version = packmsg_get_uint32(&in);
936         char *name = packmsg_get_str_dup(&in);
937         uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
938         uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
939         uint16_t myport = packmsg_get_uint16(&in);
940
941         if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
942                 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
943                 free(name);
944                 config_free(&config);
945                 return false;
946         }
947
948 #if 0
949
950         // TODO: check this?
951         if(mesh->name && strcmp(mesh->name, name)) {
952                 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
953                 meshlink_errno = MESHLINK_ESTORAGE;
954                 free(name);
955                 config_free(&config);
956                 return false;
957         }
958
959 #endif
960
961         free(mesh->name);
962         mesh->name = name;
963         xasprintf(&mesh->myport, "%u", myport);
964         mesh->private_key = ecdsa_set_private_key(private_key);
965         mesh->invitation_key = ecdsa_set_private_key(invitation_key);
966         config_free(&config);
967
968         /* Create a node for ourself and read our host configuration file */
969
970         mesh->self = new_node();
971         mesh->self->name = xstrdup(name);
972         mesh->self->devclass = mesh->devclass;
973
974         if(!node_read_public_key(mesh, mesh->self)) {
975                 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
976                 free_node(mesh->self);
977                 mesh->self = NULL;
978                 return false;
979         }
980
981         return true;
982 }
983
984 static void *setup_network_in_netns_thread(void *arg) {
985         meshlink_handle_t *mesh = arg;
986
987         if(setns(mesh->netns, CLONE_NEWNET) != 0) {
988                 return NULL;
989         }
990
991         bool success = setup_network(mesh);
992         add_local_addresses(mesh);
993         return success ? arg : NULL;
994 }
995
996 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
997         if(!confbase || !*confbase) {
998                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
999                 meshlink_errno = MESHLINK_EINVAL;
1000                 return NULL;
1001         }
1002
1003         if(!appname || !*appname) {
1004                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1005                 meshlink_errno = MESHLINK_EINVAL;
1006                 return NULL;
1007         }
1008
1009         if(strchr(appname, ' ')) {
1010                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1011                 meshlink_errno = MESHLINK_EINVAL;
1012                 return NULL;
1013         }
1014
1015         if(!name || !*name) {
1016                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1017                 //return NULL;
1018         } else { //check name only if there is a name != NULL
1019                 if(!check_id(name)) {
1020                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1021                         meshlink_errno = MESHLINK_EINVAL;
1022                         return NULL;
1023                 }
1024         }
1025
1026         if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1027                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1028                 meshlink_errno = MESHLINK_EINVAL;
1029                 return NULL;
1030         }
1031
1032         meshlink_open_params_t *params = xzalloc(sizeof * params);
1033
1034         params->confbase = xstrdup(confbase);
1035         params->name = xstrdup(name);
1036         params->appname = xstrdup(appname);
1037         params->devclass = devclass;
1038         params->netns = -1;
1039
1040         return params;
1041 }
1042
1043 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1044         if(!params) {
1045                 meshlink_errno = MESHLINK_EINVAL;
1046                 return false;
1047         }
1048
1049         params->netns = netns;
1050
1051         return true;
1052 }
1053
1054 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1055         if(!params) {
1056                 meshlink_errno = MESHLINK_EINVAL;
1057                 return false;
1058         }
1059
1060         if((!key && keylen) || (key && !keylen)) {
1061                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1062                 meshlink_errno = MESHLINK_EINVAL;
1063                 return false;
1064         }
1065
1066         params->key = key;
1067         params->keylen = keylen;
1068
1069         return true;
1070 }
1071
1072 void meshlink_open_params_free(meshlink_open_params_t *params) {
1073         if(!params) {
1074                 meshlink_errno = MESHLINK_EINVAL;
1075                 return;
1076         }
1077
1078         free(params->confbase);
1079         free(params->name);
1080         free(params->appname);
1081
1082         free(params);
1083 }
1084
1085 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1086         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1087         meshlink_open_params_t params = {NULL};
1088
1089         params.confbase = (char *)confbase;
1090         params.name = (char *)name;
1091         params.appname = (char *)appname;
1092         params.devclass = devclass;
1093         params.netns = -1;
1094
1095         return meshlink_open_ex(&params);
1096 }
1097
1098 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) {
1099         /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1100         meshlink_open_params_t params = {NULL};
1101
1102         params.confbase = (char *)confbase;
1103         params.name = (char *)name;
1104         params.appname = (char *)appname;
1105         params.devclass = devclass;
1106         params.netns = -1;
1107
1108         if(!meshlink_open_params_set_storage_key(&params, key, keylen)) {
1109                 return false;
1110         }
1111
1112         return meshlink_open_ex(&params);
1113 }
1114
1115 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1116         // Validate arguments provided by the application
1117         bool usingname = false;
1118
1119         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1120
1121         if(!params->confbase || !*params->confbase) {
1122                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1123                 meshlink_errno = MESHLINK_EINVAL;
1124                 return NULL;
1125         }
1126
1127         if(!params->appname || !*params->appname) {
1128                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1129                 meshlink_errno = MESHLINK_EINVAL;
1130                 return NULL;
1131         }
1132
1133         if(strchr(params->appname, ' ')) {
1134                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1135                 meshlink_errno = MESHLINK_EINVAL;
1136                 return NULL;
1137         }
1138
1139         if(!params->name || !*params->name) {
1140                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1141                 //return NULL;
1142         } else { //check name only if there is a name != NULL
1143
1144                 if(!check_id(params->name)) {
1145                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1146                         meshlink_errno = MESHLINK_EINVAL;
1147                         return NULL;
1148                 } else {
1149                         usingname = true;
1150                 }
1151         }
1152
1153         if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1154                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1155                 meshlink_errno = MESHLINK_EINVAL;
1156                 return NULL;
1157         }
1158
1159         if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1160                 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1161                 meshlink_errno = MESHLINK_EINVAL;
1162                 return NULL;
1163         }
1164
1165         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1166         mesh->confbase = xstrdup(params->confbase);
1167         mesh->appname = xstrdup(params->appname);
1168         mesh->devclass = params->devclass;
1169         mesh->discovery = true;
1170         mesh->invitation_timeout = 604800; // 1 week
1171         mesh->netns = params->netns;
1172         mesh->submeshes = NULL;
1173
1174         if(usingname) {
1175                 mesh->name = xstrdup(params->name);
1176         }
1177
1178         // Hash the key
1179         if(params->key) {
1180                 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1181
1182                 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1183                         logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1184                         meshlink_errno = MESHLINK_EINTERNAL;
1185                         return NULL;
1186                 }
1187         }
1188
1189         // initialize mutex
1190         pthread_mutexattr_t attr;
1191         pthread_mutexattr_init(&attr);
1192         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1193         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1194
1195         mesh->threadstarted = false;
1196         event_loop_init(&mesh->loop);
1197         mesh->loop.data = mesh;
1198
1199         meshlink_queue_init(&mesh->outpacketqueue);
1200
1201         // If no configuration exists yet, create it.
1202
1203         if(!main_config_exists(mesh)) {
1204                 if(!meshlink_setup(mesh)) {
1205                         logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1206                         meshlink_close(mesh);
1207                         return NULL;
1208                 }
1209         } else {
1210                 if(!meshlink_read_config(mesh)) {
1211                         logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1212                         meshlink_close(mesh);
1213                         return NULL;
1214                 }
1215         }
1216
1217 #ifdef HAVE_MINGW
1218         struct WSAData wsa_state;
1219         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1220 #endif
1221
1222         // Setup up everything
1223         // TODO: we should not open listening sockets yet
1224
1225         bool success = false;
1226
1227         if(mesh->netns != -1) {
1228                 pthread_t thr;
1229
1230                 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1231                         void *retval = NULL;
1232                         success = pthread_join(thr, &retval) == 0 && retval;
1233                 }
1234         } else {
1235                 success = setup_network(mesh);
1236                 add_local_addresses(mesh);
1237         }
1238
1239         if(!success) {
1240                 meshlink_close(mesh);
1241                 meshlink_errno = MESHLINK_ENETWORK;
1242                 return NULL;
1243         }
1244
1245         add_local_addresses(mesh);
1246         node_write_config(mesh, mesh->self);
1247
1248         idle_set(&mesh->loop, idle, mesh);
1249
1250         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1251         return mesh;
1252 }
1253
1254 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t  *mesh, const char *submesh) {
1255         meshlink_submesh_t *s = NULL;
1256
1257         if(!mesh) {
1258                 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1259                 meshlink_errno = MESHLINK_EINVAL;
1260                 return NULL;
1261         }
1262
1263         if(!submesh || !*submesh) {
1264                 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1265                 meshlink_errno = MESHLINK_EINVAL;
1266                 return NULL;
1267         }
1268
1269         //lock mesh->nodes
1270         pthread_mutex_lock(&(mesh->mesh_mutex));
1271
1272         s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1273
1274         pthread_mutex_unlock(&(mesh->mesh_mutex));
1275
1276         return s;
1277 }
1278
1279 static void *meshlink_main_loop(void *arg) {
1280         meshlink_handle_t *mesh = arg;
1281
1282         if(mesh->netns != -1) {
1283                 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1284                         return NULL;
1285                 }
1286         }
1287
1288         pthread_mutex_lock(&(mesh->mesh_mutex));
1289
1290         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1291         main_loop(mesh);
1292         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1293
1294         pthread_mutex_unlock(&(mesh->mesh_mutex));
1295         return NULL;
1296 }
1297
1298 bool meshlink_start(meshlink_handle_t *mesh) {
1299         assert(mesh->self);
1300         assert(mesh->private_key);
1301
1302         if(!mesh) {
1303                 meshlink_errno = MESHLINK_EINVAL;
1304                 return false;
1305         }
1306
1307         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1308
1309         pthread_mutex_lock(&(mesh->mesh_mutex));
1310
1311         if(mesh->threadstarted) {
1312                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1313                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1314                 return true;
1315         }
1316
1317         if(mesh->listen_socket[0].tcp.fd < 0) {
1318                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1319                 meshlink_errno = MESHLINK_ENETWORK;
1320                 return false;
1321         }
1322
1323         mesh->thedatalen = 0;
1324
1325         // TODO: open listening sockets first
1326
1327         //Check that a valid name is set
1328         if(!mesh->name) {
1329                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1330                 meshlink_errno = MESHLINK_EINVAL;
1331                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1332                 return false;
1333         }
1334
1335         init_outgoings(mesh);
1336
1337         // Start the main thread
1338
1339         event_loop_start(&mesh->loop);
1340
1341         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1342                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1343                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1344                 meshlink_errno = MESHLINK_EINTERNAL;
1345                 event_loop_stop(&mesh->loop);
1346                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1347                 return false;
1348         }
1349
1350         mesh->threadstarted = true;
1351
1352 #if HAVE_CATTA
1353
1354         if(mesh->discovery) {
1355                 discovery_start(mesh);
1356         }
1357
1358 #endif
1359
1360         assert(mesh->self->ecdsa);
1361         assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1362
1363
1364         pthread_mutex_unlock(&(mesh->mesh_mutex));
1365         return true;
1366 }
1367
1368 void meshlink_stop(meshlink_handle_t *mesh) {
1369         if(!mesh) {
1370                 meshlink_errno = MESHLINK_EINVAL;
1371                 return;
1372         }
1373
1374         pthread_mutex_lock(&(mesh->mesh_mutex));
1375         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1376
1377 #if HAVE_CATTA
1378
1379         // Stop discovery
1380         if(mesh->discovery) {
1381                 discovery_stop(mesh);
1382         }
1383
1384 #endif
1385
1386         // Shut down the main thread
1387         event_loop_stop(&mesh->loop);
1388
1389         // Send ourselves a UDP packet to kick the event loop
1390         for(int i = 0; i < mesh->listen_sockets; i++) {
1391                 sockaddr_t sa;
1392                 socklen_t salen = sizeof(sa.sa);
1393
1394                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1395                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1396                         continue;
1397                 }
1398
1399                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1400                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1401                 }
1402         }
1403
1404         if(mesh->threadstarted) {
1405                 // Wait for the main thread to finish
1406                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1407                 pthread_join(mesh->thread, NULL);
1408                 pthread_mutex_lock(&(mesh->mesh_mutex));
1409
1410                 mesh->threadstarted = false;
1411         }
1412
1413         // Close all metaconnections
1414         if(mesh->connections) {
1415                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1416                         next = node->next;
1417                         connection_t *c = node->data;
1418                         c->outgoing = NULL;
1419                         terminate_connection(mesh, c, false);
1420                 }
1421         }
1422
1423         exit_outgoings(mesh);
1424
1425         pthread_mutex_unlock(&(mesh->mesh_mutex));
1426 }
1427
1428 void meshlink_close(meshlink_handle_t *mesh) {
1429         if(!mesh || !mesh->confbase) {
1430                 meshlink_errno = MESHLINK_EINVAL;
1431                 return;
1432         }
1433
1434         // stop can be called even if mesh has not been started
1435         meshlink_stop(mesh);
1436
1437         // lock is not released after this
1438         pthread_mutex_lock(&(mesh->mesh_mutex));
1439
1440         // Close and free all resources used.
1441
1442         close_network_connections(mesh);
1443
1444         logger(mesh, MESHLINK_INFO, "Terminating");
1445
1446         event_loop_exit(&mesh->loop);
1447
1448 #ifdef HAVE_MINGW
1449
1450         if(mesh->confbase) {
1451                 WSACleanup();
1452         }
1453
1454 #endif
1455
1456         ecdsa_free(mesh->invitation_key);
1457
1458         if(mesh->netns != -1) {
1459                 close(mesh->netns);
1460         }
1461
1462         free(mesh->name);
1463         free(mesh->appname);
1464         free(mesh->confbase);
1465         pthread_mutex_destroy(&(mesh->mesh_mutex));
1466
1467         main_config_unlock(mesh);
1468
1469         memset(mesh, 0, sizeof(*mesh));
1470
1471         free(mesh);
1472 }
1473
1474 bool meshlink_destroy(const char *confbase) {
1475         if(!confbase) {
1476                 meshlink_errno = MESHLINK_EINVAL;
1477                 return false;
1478         }
1479
1480         return config_destroy(confbase);
1481 }
1482
1483 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1484         if(!mesh) {
1485                 meshlink_errno = MESHLINK_EINVAL;
1486                 return;
1487         }
1488
1489         pthread_mutex_lock(&(mesh->mesh_mutex));
1490         mesh->receive_cb = cb;
1491         pthread_mutex_unlock(&(mesh->mesh_mutex));
1492 }
1493
1494 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1495         if(!mesh) {
1496                 meshlink_errno = MESHLINK_EINVAL;
1497                 return;
1498         }
1499
1500         pthread_mutex_lock(&(mesh->mesh_mutex));
1501         mesh->node_status_cb = cb;
1502         pthread_mutex_unlock(&(mesh->mesh_mutex));
1503 }
1504
1505 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1506         if(!mesh) {
1507                 meshlink_errno = MESHLINK_EINVAL;
1508                 return;
1509         }
1510
1511         pthread_mutex_lock(&(mesh->mesh_mutex));
1512         mesh->node_duplicate_cb = cb;
1513         pthread_mutex_unlock(&(mesh->mesh_mutex));
1514 }
1515
1516 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1517         if(mesh) {
1518                 pthread_mutex_lock(&(mesh->mesh_mutex));
1519                 mesh->log_cb = cb;
1520                 mesh->log_level = cb ? level : 0;
1521                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1522         } else {
1523                 global_log_cb = cb;
1524                 global_log_level = cb ? level : 0;
1525         }
1526 }
1527
1528 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1529         meshlink_packethdr_t *hdr;
1530
1531         // Validate arguments
1532         if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1533                 meshlink_errno = MESHLINK_EINVAL;
1534                 return false;
1535         }
1536
1537         if(!len) {
1538                 return true;
1539         }
1540
1541         if(!data) {
1542                 meshlink_errno = MESHLINK_EINVAL;
1543                 return false;
1544         }
1545
1546         node_t *n = (node_t *)destination;
1547
1548         if(n->status.blacklisted) {
1549                 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1550                 return false;
1551         }
1552
1553         // Prepare the packet
1554         vpn_packet_t *packet = malloc(sizeof(*packet));
1555
1556         if(!packet) {
1557                 meshlink_errno = MESHLINK_ENOMEM;
1558                 return false;
1559         }
1560
1561         packet->probe = false;
1562         packet->tcp = false;
1563         packet->len = len + sizeof(*hdr);
1564
1565         hdr = (meshlink_packethdr_t *)packet->data;
1566         memset(hdr, 0, sizeof(*hdr));
1567         // leave the last byte as 0 to make sure strings are always
1568         // null-terminated if they are longer than the buffer
1569         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1570         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1571
1572         memcpy(packet->data + sizeof(*hdr), data, len);
1573
1574         // Queue it
1575         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1576                 free(packet);
1577                 meshlink_errno = MESHLINK_ENOMEM;
1578                 return false;
1579         }
1580
1581         // Notify event loop
1582         signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1583
1584         return true;
1585 }
1586
1587 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1588         (void)loop;
1589         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1590
1591         if(!packet) {
1592                 return;
1593         }
1594
1595         mesh->self->in_packets++;
1596         mesh->self->in_bytes += packet->len;
1597         route(mesh, mesh->self, packet);
1598 }
1599
1600 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1601         if(!mesh || !destination) {
1602                 meshlink_errno = MESHLINK_EINVAL;
1603                 return -1;
1604         }
1605
1606         pthread_mutex_lock(&(mesh->mesh_mutex));
1607
1608         node_t *n = (node_t *)destination;
1609
1610         if(!n->status.reachable) {
1611                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1612                 return 0;
1613
1614         } else if(n->mtuprobes > 30 && n->minmtu) {
1615                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1616                 return n->minmtu;
1617         } else {
1618                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1619                 return MTU;
1620         }
1621 }
1622
1623 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1624         if(!mesh || !node) {
1625                 meshlink_errno = MESHLINK_EINVAL;
1626                 return NULL;
1627         }
1628
1629         pthread_mutex_lock(&(mesh->mesh_mutex));
1630
1631         node_t *n = (node_t *)node;
1632
1633         if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1634                 meshlink_errno = MESHLINK_EINTERNAL;
1635                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1636                 return false;
1637         }
1638
1639         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1640
1641         if(!fingerprint) {
1642                 meshlink_errno = MESHLINK_EINTERNAL;
1643         }
1644
1645         pthread_mutex_unlock(&(mesh->mesh_mutex));
1646         return fingerprint;
1647 }
1648
1649 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1650         if(!mesh) {
1651                 meshlink_errno = MESHLINK_EINVAL;
1652                 return NULL;
1653         }
1654
1655         return (meshlink_node_t *)mesh->self;
1656 }
1657
1658 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1659         if(!mesh || !name) {
1660                 meshlink_errno = MESHLINK_EINVAL;
1661                 return NULL;
1662         }
1663
1664         meshlink_node_t *node = NULL;
1665
1666         pthread_mutex_lock(&(mesh->mesh_mutex));
1667         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1668         pthread_mutex_unlock(&(mesh->mesh_mutex));
1669         return node;
1670 }
1671
1672 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1673         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1674                 meshlink_errno = MESHLINK_EINVAL;
1675                 return NULL;
1676         }
1677
1678         meshlink_node_t **result;
1679
1680         //lock mesh->nodes
1681         pthread_mutex_lock(&(mesh->mesh_mutex));
1682
1683         *nmemb = mesh->nodes->count;
1684         result = realloc(nodes, *nmemb * sizeof(*nodes));
1685
1686         if(result) {
1687                 meshlink_node_t **p = result;
1688
1689                 for splay_each(node_t, n, mesh->nodes) {
1690                         *p++ = (meshlink_node_t *)n;
1691                 }
1692         } else {
1693                 *nmemb = 0;
1694                 free(nodes);
1695                 meshlink_errno = MESHLINK_ENOMEM;
1696         }
1697
1698         pthread_mutex_unlock(&(mesh->mesh_mutex));
1699
1700         return result;
1701 }
1702
1703 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) {
1704         meshlink_node_t **result;
1705
1706         pthread_mutex_lock(&(mesh->mesh_mutex));
1707
1708         *nmemb = 0;
1709
1710         for splay_each(node_t, n, mesh->nodes) {
1711                 if(true == search_node(n, condition)) {
1712                         *nmemb = *nmemb + 1;
1713                 }
1714         }
1715
1716         if(*nmemb == 0) {
1717                 free(nodes);
1718                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1719                 return NULL;
1720         }
1721
1722         result = realloc(nodes, *nmemb * sizeof(*nodes));
1723
1724         if(result) {
1725                 meshlink_node_t **p = result;
1726
1727                 for splay_each(node_t, n, mesh->nodes) {
1728                         if(true == search_node(n, condition)) {
1729                                 *p++ = (meshlink_node_t *)n;
1730                         }
1731                 }
1732         } else {
1733                 *nmemb = 0;
1734                 free(nodes);
1735                 meshlink_errno = MESHLINK_ENOMEM;
1736         }
1737
1738         pthread_mutex_unlock(&(mesh->mesh_mutex));
1739
1740         return result;
1741 }
1742
1743 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1744         dev_class_t *devclass = (dev_class_t *)condition;
1745
1746         if(*devclass == node->devclass) {
1747                 return true;
1748         }
1749
1750         return false;
1751 }
1752
1753 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1754         if(condition == node->submesh) {
1755                 return true;
1756         }
1757
1758         return false;
1759 }
1760
1761 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) {
1762         if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1763                 meshlink_errno = MESHLINK_EINVAL;
1764                 return NULL;
1765         }
1766
1767         return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1768 }
1769
1770 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1771         if(!mesh || !submesh || !nmemb) {
1772                 meshlink_errno = MESHLINK_EINVAL;
1773                 return NULL;
1774         }
1775
1776         return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1777 }
1778
1779 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1780         if(!mesh || !node) {
1781                 meshlink_errno = MESHLINK_EINVAL;
1782                 return -1;
1783         }
1784
1785         dev_class_t devclass;
1786
1787         pthread_mutex_lock(&(mesh->mesh_mutex));
1788
1789         devclass = ((node_t *)node)->devclass;
1790
1791         pthread_mutex_unlock(&(mesh->mesh_mutex));
1792
1793         return devclass;
1794 }
1795
1796 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1797         if(!mesh || !node) {
1798                 meshlink_errno = MESHLINK_EINVAL;
1799                 return NULL;
1800         }
1801
1802         node_t *n = (node_t *)node;
1803
1804         meshlink_submesh_t *s;
1805
1806         s = (meshlink_submesh_t *)n->submesh;
1807
1808         return s;
1809 }
1810
1811 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1812         if(!mesh || !data || !len || !signature || !siglen) {
1813                 meshlink_errno = MESHLINK_EINVAL;
1814                 return false;
1815         }
1816
1817         if(*siglen < MESHLINK_SIGLEN) {
1818                 meshlink_errno = MESHLINK_EINVAL;
1819                 return false;
1820         }
1821
1822         pthread_mutex_lock(&(mesh->mesh_mutex));
1823
1824         if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1825                 meshlink_errno = MESHLINK_EINTERNAL;
1826                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1827                 return false;
1828         }
1829
1830         *siglen = MESHLINK_SIGLEN;
1831         pthread_mutex_unlock(&(mesh->mesh_mutex));
1832         return true;
1833 }
1834
1835 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1836         if(!mesh || !data || !len || !signature) {
1837                 meshlink_errno = MESHLINK_EINVAL;
1838                 return false;
1839         }
1840
1841         if(siglen != MESHLINK_SIGLEN) {
1842                 meshlink_errno = MESHLINK_EINVAL;
1843                 return false;
1844         }
1845
1846         pthread_mutex_lock(&(mesh->mesh_mutex));
1847
1848         bool rval = false;
1849
1850         struct node_t *n = (struct node_t *)source;
1851
1852         if(!node_read_public_key(mesh, n)) {
1853                 meshlink_errno = MESHLINK_EINTERNAL;
1854                 rval = false;
1855         } else {
1856                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1857         }
1858
1859         pthread_mutex_unlock(&(mesh->mesh_mutex));
1860         return rval;
1861 }
1862
1863 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1864         pthread_mutex_lock(&(mesh->mesh_mutex));
1865
1866         size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
1867
1868         if(!count) {
1869                 // TODO: Update invitation key if necessary?
1870         }
1871
1872         pthread_mutex_unlock(&(mesh->mesh_mutex));
1873
1874         return mesh->invitation_key;
1875 }
1876
1877 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1878         if(!mesh || !node || !address) {
1879                 meshlink_errno = MESHLINK_EINVAL;
1880                 return false;
1881         }
1882
1883         if(!is_valid_hostname(address)) {
1884                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1885                 meshlink_errno = MESHLINK_EINVAL;
1886                 return false;
1887         }
1888
1889         if(port && !is_valid_port(port)) {
1890                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1891                 meshlink_errno = MESHLINK_EINVAL;
1892                 return false;
1893         }
1894
1895         char *canonical_address;
1896
1897         if(port) {
1898                 xasprintf(&canonical_address, "%s %s", address, port);
1899         } else {
1900                 canonical_address = xstrdup(address);
1901         }
1902
1903         pthread_mutex_lock(&(mesh->mesh_mutex));
1904
1905         node_t *n = (node_t *)node;
1906         free(n->canonical_address);
1907         n->canonical_address = canonical_address;
1908         n->status.dirty = true;
1909
1910         pthread_mutex_unlock(&(mesh->mesh_mutex));
1911
1912         return true;
1913 }
1914
1915 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1916         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1917 }
1918
1919 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1920         if(!mesh) {
1921                 meshlink_errno = MESHLINK_EINVAL;
1922                 return false;
1923         }
1924
1925         char *address = meshlink_get_external_address(mesh);
1926
1927         if(!address) {
1928                 return false;
1929         }
1930
1931         bool rval = meshlink_add_address(mesh, address);
1932         free(address);
1933
1934         return rval;
1935 }
1936
1937 int meshlink_get_port(meshlink_handle_t *mesh) {
1938         if(!mesh) {
1939                 meshlink_errno = MESHLINK_EINVAL;
1940                 return -1;
1941         }
1942
1943         if(!mesh->myport) {
1944                 meshlink_errno = MESHLINK_EINTERNAL;
1945                 return -1;
1946         }
1947
1948         return atoi(mesh->myport);
1949 }
1950
1951 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1952         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1953                 meshlink_errno = MESHLINK_EINVAL;
1954                 return false;
1955         }
1956
1957         if(mesh->myport && port == atoi(mesh->myport)) {
1958                 return true;
1959         }
1960
1961         if(!try_bind(port)) {
1962                 meshlink_errno = MESHLINK_ENETWORK;
1963                 return false;
1964         }
1965
1966         bool rval = false;
1967
1968         pthread_mutex_lock(&(mesh->mesh_mutex));
1969
1970         if(mesh->threadstarted) {
1971                 meshlink_errno = MESHLINK_EINVAL;
1972                 goto done;
1973         }
1974
1975         close_network_connections(mesh);
1976
1977         // TODO: write meshlink.conf again
1978
1979         if(!setup_network(mesh)) {
1980                 meshlink_errno = MESHLINK_ENETWORK;
1981         } else {
1982                 rval = true;
1983         }
1984
1985 done:
1986         pthread_mutex_unlock(&(mesh->mesh_mutex));
1987
1988         return rval;
1989 }
1990
1991 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1992         mesh->invitation_timeout = timeout;
1993 }
1994
1995 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
1996         meshlink_submesh_t *s = NULL;
1997
1998         if(!mesh) {
1999                 meshlink_errno = MESHLINK_EINVAL;
2000                 return NULL;
2001         }
2002
2003         if(submesh) {
2004                 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2005
2006                 if(s != submesh) {
2007                         logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2008                         meshlink_errno = MESHLINK_EINVAL;
2009                         return NULL;
2010                 }
2011         } else {
2012                 s = (meshlink_submesh_t *)mesh->self->submesh;
2013         }
2014
2015         pthread_mutex_lock(&(mesh->mesh_mutex));
2016
2017         // Check validity of the new node's name
2018         if(!check_id(name)) {
2019                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2020                 meshlink_errno = MESHLINK_EINVAL;
2021                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2022                 return NULL;
2023         }
2024
2025         // Ensure no host configuration file with that name exists
2026         if(config_exists(mesh, name)) {
2027                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2028                 meshlink_errno = MESHLINK_EEXIST;
2029                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2030                 return NULL;
2031         }
2032
2033         // Ensure no other nodes know about this name
2034         if(meshlink_get_node(mesh, name)) {
2035                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2036                 meshlink_errno = MESHLINK_EEXIST;
2037                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2038                 return NULL;
2039         }
2040
2041         // Get the local address
2042         char *address = get_my_hostname(mesh, flags);
2043
2044         if(!address) {
2045                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2046                 meshlink_errno = MESHLINK_ERESOLV;
2047                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2048                 return NULL;
2049         }
2050
2051         if(!refresh_invitation_key(mesh)) {
2052                 meshlink_errno = MESHLINK_EINTERNAL;
2053                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2054                 return NULL;
2055         }
2056
2057         char hash[64];
2058
2059         // Create a hash of the key.
2060         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2061         sha512(fingerprint, strlen(fingerprint), hash);
2062         b64encode_urlsafe(hash, hash, 18);
2063
2064         // Create a random cookie for this invitation.
2065         char cookie[25];
2066         randomize(cookie, 18);
2067
2068         // Create a filename that doesn't reveal the cookie itself
2069         char buf[18 + strlen(fingerprint)];
2070         char cookiehash[64];
2071         memcpy(buf, cookie, 18);
2072         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2073         sha512(buf, sizeof(buf), cookiehash);
2074         b64encode_urlsafe(cookiehash, cookiehash, 18);
2075
2076         b64encode_urlsafe(cookie, cookie, 18);
2077
2078         free(fingerprint);
2079
2080         /* Construct the invitation file */
2081         uint8_t outbuf[4096];
2082         packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2083
2084         packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2085         packmsg_add_str(&inv, name);
2086         packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2087         packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2088
2089         /* TODO: Add several host config files to bootstrap connections */
2090         config_t configs[5] = {NULL};
2091         int count = 0;
2092
2093         if(config_read(mesh, mesh->self->name, &configs[count])) {
2094                 count++;
2095         }
2096
2097         /* Append host config files to the invitation file */
2098         packmsg_add_array(&inv, count);
2099
2100         for(int i = 0; i < count; i++) {
2101                 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2102                 config_free(&configs[i]);
2103         }
2104
2105         config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2106
2107         if(!invitation_write(mesh, cookiehash, &config)) {
2108                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2109                 meshlink_errno = MESHLINK_ESTORAGE;
2110                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2111                 return NULL;
2112         }
2113
2114         // Create an URL from the local address, key hash and cookie
2115         char *url;
2116         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2117         free(address);
2118
2119         pthread_mutex_unlock(&(mesh->mesh_mutex));
2120         return url;
2121 }
2122
2123 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2124         return meshlink_invite_ex(mesh, submesh, name, 0);
2125 }
2126
2127 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2128         if(!mesh || !invitation) {
2129                 meshlink_errno = MESHLINK_EINVAL;
2130                 return false;
2131         }
2132
2133         pthread_mutex_lock(&(mesh->mesh_mutex));
2134
2135         //Before doing meshlink_join make sure we are not connected to another mesh
2136         if(mesh->threadstarted) {
2137                 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2138                 meshlink_errno = MESHLINK_EINVAL;
2139                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2140                 return false;
2141         }
2142
2143         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2144         char copy[strlen(invitation) + 1];
2145         strcpy(copy, invitation);
2146
2147         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2148
2149         char *slash = strchr(copy, '/');
2150
2151         if(!slash) {
2152                 goto invalid;
2153         }
2154
2155         *slash++ = 0;
2156
2157         if(strlen(slash) != 48) {
2158                 goto invalid;
2159         }
2160
2161         char *address = copy;
2162         char *port = NULL;
2163
2164         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2165                 goto invalid;
2166         }
2167
2168         // Generate a throw-away key for the invitation.
2169         ecdsa_t *key = ecdsa_generate();
2170
2171         if(!key) {
2172                 meshlink_errno = MESHLINK_EINTERNAL;
2173                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2174                 return false;
2175         }
2176
2177         char *b64key = ecdsa_get_base64_public_key(key);
2178         char *comma;
2179         mesh->sock = -1;
2180
2181         while(address && *address) {
2182                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2183                 comma = strchr(address, ',');
2184
2185                 if(comma) {
2186                         *comma++ = 0;
2187                 }
2188
2189                 // Split of the port
2190                 port = strrchr(address, ':');
2191
2192                 if(!port) {
2193                         goto invalid;
2194                 }
2195
2196                 *port++ = 0;
2197
2198                 // IPv6 address are enclosed in brackets, per RFC 3986
2199                 if(*address == '[') {
2200                         address++;
2201                         char *bracket = strchr(address, ']');
2202
2203                         if(!bracket) {
2204                                 goto invalid;
2205                         }
2206
2207                         *bracket++ = 0;
2208
2209                         if(*bracket) {
2210                                 goto invalid;
2211                         }
2212                 }
2213
2214                 // Connect to the meshlink daemon mentioned in the URL.
2215                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2216
2217                 if(ai) {
2218                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2219                                 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2220
2221                                 if(mesh->sock == -1) {
2222                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2223                                         meshlink_errno = MESHLINK_ENETWORK;
2224                                         continue;
2225                                 }
2226
2227                                 set_timeout(mesh->sock, 5000);
2228
2229                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2230                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2231                                         meshlink_errno = MESHLINK_ENETWORK;
2232                                         closesocket(mesh->sock);
2233                                         mesh->sock = -1;
2234                                         continue;
2235                                 }
2236                         }
2237
2238                         freeaddrinfo(ai);
2239                 } else {
2240                         meshlink_errno = MESHLINK_ERESOLV;
2241                 }
2242
2243                 if(mesh->sock != -1 || !comma) {
2244                         break;
2245                 }
2246
2247                 address = comma;
2248         }
2249
2250         if(mesh->sock == -1) {
2251                 pthread_mutex_unlock(&mesh->mesh_mutex);
2252                 return false;
2253         }
2254
2255         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2256
2257         // Tell him we have an invitation, and give him our throw-away key.
2258
2259         mesh->blen = 0;
2260
2261         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2262                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2263                 closesocket(mesh->sock);
2264                 meshlink_errno = MESHLINK_ENETWORK;
2265                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2266                 return false;
2267         }
2268
2269         free(b64key);
2270
2271         char hisname[4096] = "";
2272         int code, hismajor, hisminor = 0;
2273
2274         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) {
2275                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2276                 closesocket(mesh->sock);
2277                 meshlink_errno = MESHLINK_ENETWORK;
2278                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2279                 return false;
2280         }
2281
2282         // Check if the hash of the key he gave us matches the hash in the URL.
2283         char *fingerprint = mesh->line + 2;
2284         char hishash[64];
2285
2286         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2287                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2288                 meshlink_errno = MESHLINK_EINTERNAL;
2289                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2290                 return false;
2291         }
2292
2293         if(memcmp(hishash, mesh->hash, 18)) {
2294                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2295                 meshlink_errno = MESHLINK_EPEER;
2296                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2297                 return false;
2298
2299         }
2300
2301         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2302
2303         if(!hiskey) {
2304                 meshlink_errno = MESHLINK_EINTERNAL;
2305                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2306                 return false;
2307         }
2308
2309         // Start an SPTPS session
2310         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2311                 meshlink_errno = MESHLINK_EINTERNAL;
2312                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2313                 return false;
2314         }
2315
2316         // Feed rest of input buffer to SPTPS
2317         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2318                 meshlink_errno = MESHLINK_EPEER;
2319                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2320                 return false;
2321         }
2322
2323         int len;
2324
2325         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2326                 if(len < 0) {
2327                         if(errno == EINTR) {
2328                                 continue;
2329                         }
2330
2331                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2332                         meshlink_errno = MESHLINK_ENETWORK;
2333                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2334                         return false;
2335                 }
2336
2337                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2338                         meshlink_errno = MESHLINK_EPEER;
2339                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2340                         return false;
2341                 }
2342         }
2343
2344         sptps_stop(&mesh->sptps);
2345         ecdsa_free(hiskey);
2346         ecdsa_free(key);
2347         closesocket(mesh->sock);
2348
2349         if(!mesh->success) {
2350                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2351                 meshlink_errno = MESHLINK_EPEER;
2352                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2353                 return false;
2354         }
2355
2356         pthread_mutex_unlock(&(mesh->mesh_mutex));
2357         return true;
2358
2359 invalid:
2360         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2361         meshlink_errno = MESHLINK_EINVAL;
2362         pthread_mutex_unlock(&(mesh->mesh_mutex));
2363         return false;
2364 }
2365
2366 char *meshlink_export(meshlink_handle_t *mesh) {
2367         if(!mesh) {
2368                 meshlink_errno = MESHLINK_EINVAL;
2369                 return NULL;
2370         }
2371
2372         config_t config;
2373
2374         // Get our config file
2375
2376         pthread_mutex_lock(&(mesh->mesh_mutex));
2377
2378         if(!config_read(mesh, mesh->self->name, &config)) {
2379                 meshlink_errno = MESHLINK_ESTORAGE;
2380                 pthread_mutex_unlock(&mesh->mesh_mutex);
2381                 return NULL;
2382         }
2383
2384         pthread_mutex_unlock(&(mesh->mesh_mutex));
2385
2386         // Prepare a base64-encoded packmsg array containing our config file
2387
2388         uint8_t *buf = xmalloc(((config.len + 4) * 4) / 3 + 4);
2389         packmsg_output_t out = {buf, config.len + 4};
2390         packmsg_add_array(&out, 1);
2391         packmsg_add_bin(&out, config.buf, config.len);
2392         config_free(&config);
2393
2394         if(!packmsg_output_ok(&out)) {
2395                 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2396                 meshlink_errno = MESHLINK_EINTERNAL;
2397                 free(buf);
2398                 return NULL;
2399         }
2400
2401         b64encode_urlsafe(buf, (char *)buf, packmsg_output_size(&out, buf));
2402
2403         return (char *)buf;
2404 }
2405
2406 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2407         if(!mesh || !data) {
2408                 meshlink_errno = MESHLINK_EINVAL;
2409                 return false;
2410         }
2411
2412         size_t datalen = strlen(data);
2413         uint8_t *buf = xmalloc(datalen);
2414         int buflen = b64decode(data, buf, datalen);
2415
2416         if(!buflen) {
2417                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2418                 meshlink_errno = MESHLINK_EPEER;
2419                 return false;
2420         }
2421
2422         packmsg_input_t in = {buf, buflen};
2423         uint32_t count = packmsg_get_array(&in);
2424
2425         if(!count) {
2426                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2427                 meshlink_errno = MESHLINK_EPEER;
2428                 return false;
2429         }
2430
2431         pthread_mutex_lock(&(mesh->mesh_mutex));
2432
2433         while(count--) {
2434                 const void *data;
2435                 uint32_t len = packmsg_get_bin_raw(&in, &data);
2436
2437                 if(!len) {
2438                         break;
2439                 }
2440
2441                 packmsg_input_t in2 = {data, len};
2442                 uint32_t version = packmsg_get_uint32(&in2);
2443                 char *name = packmsg_get_str_dup(&in2);
2444
2445                 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2446                         free(name);
2447                         packmsg_input_invalidate(&in2);
2448                         break;
2449                 }
2450
2451                 if(!check_id(name)) {
2452                         free(name);
2453                         break;
2454                 }
2455
2456                 node_t *n = lookup_node(mesh, name);
2457
2458                 if(n) {
2459                         free(name);
2460                         logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2461                         continue;
2462                 }
2463
2464                 n = new_node();
2465                 n->name = name;
2466                 char *submesh_name = packmsg_get_str_dup(&in2);
2467
2468                 if(submesh_name) {
2469                         if(!strcmp(submesh_name, CORE_MESH)) {
2470                                 n->submesh = NULL;
2471                         } else {
2472                                 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
2473
2474                                 if(!n->submesh) {
2475                                         packmsg_input_invalidate(&in2);
2476                                 }
2477                         }
2478
2479                         free(submesh_name);
2480                 }
2481
2482                 n->devclass = packmsg_get_int32(&in2);
2483                 n->status.blacklisted = packmsg_get_bool(&in2);
2484                 const void *key;
2485                 uint32_t keylen = packmsg_get_bin_raw(&in2, &key);
2486
2487                 if(keylen == 32) {
2488                         n->ecdsa = ecdsa_set_public_key(key);
2489                 }
2490
2491                 n->canonical_address = packmsg_get_str_dup(&in2);
2492                 uint32_t count = packmsg_get_array(&in2);
2493
2494                 if(count > 5) {
2495                         count = 5;
2496                 }
2497
2498                 for(uint32_t i = 0; i < count; i++) {
2499                         n->recent[i] = packmsg_get_sockaddr(&in2);
2500                 }
2501
2502                 if(!packmsg_done(&in2) || keylen != 32) {
2503                         packmsg_input_invalidate(&in2);
2504                         free_node(n);
2505                 } else {
2506                         config_t config = {data, len};
2507                         config_write(mesh, n->name, &config);
2508                         node_add(mesh, n);
2509                 }
2510         }
2511
2512         pthread_mutex_unlock(&(mesh->mesh_mutex));
2513
2514         if(!packmsg_done(&in)) {
2515                 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2516                 meshlink_errno = MESHLINK_EPEER;
2517                 return false;
2518         }
2519
2520         return true;
2521 }
2522
2523 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2524         if(!mesh || !node) {
2525                 meshlink_errno = MESHLINK_EINVAL;
2526                 return;
2527         }
2528
2529         pthread_mutex_lock(&(mesh->mesh_mutex));
2530
2531         node_t *n;
2532         n = (node_t *)node;
2533
2534         if(n == mesh->self) {
2535                 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2536                 meshlink_errno = MESHLINK_EINVAL;
2537                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2538                 return;
2539         }
2540
2541         if(n->status.blacklisted) {
2542                 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2543                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2544                 return;
2545         }
2546
2547         n->status.blacklisted = true;
2548         n->status.dirty = true;
2549         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2550
2551         //Immediately terminate any connections we have with the blacklisted node
2552         for list_each(connection_t, c, mesh->connections) {
2553                 if(c->node == n) {
2554                         terminate_connection(mesh, c, c->status.active);
2555                 }
2556         }
2557
2558         utcp_abort_all_connections(n->utcp);
2559
2560         n->mtu = 0;
2561         n->minmtu = 0;
2562         n->maxmtu = MTU;
2563         n->mtuprobes = 0;
2564         n->status.udp_confirmed = false;
2565
2566         if(n->status.reachable) {
2567                 update_node_status(mesh, n);
2568         }
2569
2570         pthread_mutex_unlock(&(mesh->mesh_mutex));
2571 }
2572
2573 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2574         if(!mesh || !node) {
2575                 meshlink_errno = MESHLINK_EINVAL;
2576                 return;
2577         }
2578
2579         pthread_mutex_lock(&(mesh->mesh_mutex));
2580
2581         node_t *n = (node_t *)node;
2582
2583         if(!n->status.blacklisted) {
2584                 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2585                 meshlink_errno = MESHLINK_EINVAL;
2586                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2587                 return;
2588         }
2589
2590         n->status.blacklisted = false;
2591         n->status.dirty = true;
2592
2593         pthread_mutex_unlock(&(mesh->mesh_mutex));
2594         return;
2595 }
2596
2597 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2598         mesh->default_blacklist = blacklist;
2599 }
2600
2601 /* Hint that a hostname may be found at an address
2602  * See header file for detailed comment.
2603  */
2604 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2605         if(!mesh || !node || !addr) {
2606                 meshlink_errno = EINVAL;
2607                 return;
2608         }
2609
2610         pthread_mutex_lock(&(mesh->mesh_mutex));
2611
2612         node_t *n = (node_t *)node;
2613         memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2614         memcpy(n->recent, addr, SALEN(*addr));
2615         n->status.dirty = true;
2616
2617         pthread_mutex_unlock(&(mesh->mesh_mutex));
2618         // @TODO do we want to fire off a connection attempt right away?
2619 }
2620
2621 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2622         (void)port;
2623         node_t *n = utcp->priv;
2624         meshlink_handle_t *mesh = n->mesh;
2625         return mesh->channel_accept_cb;
2626 }
2627
2628 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2629         meshlink_channel_t *channel = connection->priv;
2630
2631         if(!channel) {
2632                 abort();
2633         }
2634
2635         node_t *n = channel->node;
2636         meshlink_handle_t *mesh = n->mesh;
2637
2638         if(n->status.destroyed) {
2639                 meshlink_channel_close(mesh, channel);
2640         } else if(channel->receive_cb) {
2641                 channel->receive_cb(mesh, channel, data, len);
2642         }
2643
2644         return len;
2645 }
2646
2647 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2648         node_t *n = utcp_connection->utcp->priv;
2649
2650         if(!n) {
2651                 abort();
2652         }
2653
2654         meshlink_handle_t *mesh = n->mesh;
2655
2656         if(!mesh->channel_accept_cb) {
2657                 return;
2658         }
2659
2660         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2661         channel->node = n;
2662         channel->c = utcp_connection;
2663
2664         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2665                 utcp_accept(utcp_connection, channel_recv, channel);
2666         } else {
2667                 free(channel);
2668         }
2669 }
2670
2671 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2672         node_t *n = utcp->priv;
2673
2674         if(n->status.destroyed) {
2675                 return -1;
2676         }
2677
2678         meshlink_handle_t *mesh = n->mesh;
2679         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2680 }
2681
2682 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2683         if(!mesh || !channel) {
2684                 meshlink_errno = MESHLINK_EINVAL;
2685                 return;
2686         }
2687
2688         channel->receive_cb = cb;
2689 }
2690
2691 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2692         (void)mesh;
2693         node_t *n = (node_t *)source;
2694
2695         if(!n->utcp) {
2696                 abort();
2697         }
2698
2699         utcp_recv(n->utcp, data, len);
2700 }
2701
2702 static void channel_poll(struct utcp_connection *connection, size_t len) {
2703         meshlink_channel_t *channel = connection->priv;
2704
2705         if(!channel) {
2706                 abort();
2707         }
2708
2709         node_t *n = channel->node;
2710         meshlink_handle_t *mesh = n->mesh;
2711
2712         if(channel->poll_cb) {
2713                 channel->poll_cb(mesh, channel, len);
2714         }
2715 }
2716
2717 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2718         (void)mesh;
2719         channel->poll_cb = cb;
2720         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2721 }
2722
2723 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2724         if(!mesh) {
2725                 meshlink_errno = MESHLINK_EINVAL;
2726                 return;
2727         }
2728
2729         pthread_mutex_lock(&mesh->mesh_mutex);
2730         mesh->channel_accept_cb = cb;
2731         mesh->receive_cb = channel_receive;
2732
2733         for splay_each(node_t, n, mesh->nodes) {
2734                 if(!n->utcp && n != mesh->self) {
2735                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2736                 }
2737         }
2738
2739         pthread_mutex_unlock(&mesh->mesh_mutex);
2740 }
2741
2742 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) {
2743         if(data || len) {
2744                 abort();        // TODO: handle non-NULL data
2745         }
2746
2747         if(!mesh || !node) {
2748                 meshlink_errno = MESHLINK_EINVAL;
2749                 return NULL;
2750         }
2751
2752         node_t *n = (node_t *)node;
2753
2754         if(!n->utcp) {
2755                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2756                 mesh->receive_cb = channel_receive;
2757
2758                 if(!n->utcp) {
2759                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2760                         return NULL;
2761                 }
2762         }
2763
2764         if(n->status.blacklisted) {
2765                 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2766                 return NULL;
2767         }
2768
2769         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2770         channel->node = n;
2771         channel->receive_cb = cb;
2772         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2773
2774         if(!channel->c) {
2775                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2776                 free(channel);
2777                 return NULL;
2778         }
2779
2780         return channel;
2781 }
2782
2783 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) {
2784         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2785 }
2786
2787 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2788         if(!mesh || !channel) {
2789                 meshlink_errno = MESHLINK_EINVAL;
2790                 return;
2791         }
2792
2793         utcp_shutdown(channel->c, direction);
2794 }
2795
2796 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2797         if(!mesh || !channel) {
2798                 meshlink_errno = MESHLINK_EINVAL;
2799                 return;
2800         }
2801
2802         utcp_close(channel->c);
2803         free(channel);
2804 }
2805
2806 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2807         if(!mesh || !channel) {
2808                 meshlink_errno = MESHLINK_EINVAL;
2809                 return -1;
2810         }
2811
2812         if(!len) {
2813                 return 0;
2814         }
2815
2816         if(!data) {
2817                 meshlink_errno = MESHLINK_EINVAL;
2818                 return -1;
2819         }
2820
2821         // TODO: more finegrained locking.
2822         // Ideally we want to put the data into the UTCP connection's send buffer.
2823         // Then, preferably only if there is room in the receiver window,
2824         // kick the meshlink thread to go send packets.
2825
2826         pthread_mutex_lock(&mesh->mesh_mutex);
2827         ssize_t retval = utcp_send(channel->c, data, len);
2828         pthread_mutex_unlock(&mesh->mesh_mutex);
2829
2830         if(retval < 0) {
2831                 meshlink_errno = MESHLINK_ENETWORK;
2832         }
2833
2834         return retval;
2835 }
2836
2837 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2838         if(!mesh || !channel) {
2839                 meshlink_errno = MESHLINK_EINVAL;
2840                 return -1;
2841         }
2842
2843         return channel->c->flags;
2844 }
2845
2846 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2847         if(!mesh || !channel) {
2848                 meshlink_errno = MESHLINK_EINVAL;
2849                 return -1;
2850         }
2851
2852         return utcp_get_sendq(channel->c);
2853 }
2854
2855 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2856         if(!mesh || !channel) {
2857                 meshlink_errno = MESHLINK_EINVAL;
2858                 return -1;
2859         }
2860
2861         return utcp_get_recvq(channel->c);
2862 }
2863
2864 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2865         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2866                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2867         }
2868
2869         if(mesh->node_status_cb) {
2870                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2871         }
2872 }
2873
2874 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2875         if(!mesh->node_duplicate_cb || n->status.duplicate) {
2876                 return;
2877         }
2878
2879         n->status.duplicate = true;
2880         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2881 }
2882
2883 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2884 #if HAVE_CATTA
2885
2886         if(!mesh) {
2887                 meshlink_errno = MESHLINK_EINVAL;
2888                 return;
2889         }
2890
2891         pthread_mutex_lock(&mesh->mesh_mutex);
2892
2893         if(mesh->discovery == enable) {
2894                 goto end;
2895         }
2896
2897         if(mesh->threadstarted) {
2898                 if(enable) {
2899                         discovery_start(mesh);
2900                 } else {
2901                         discovery_stop(mesh);
2902                 }
2903         }
2904
2905         mesh->discovery = enable;
2906
2907 end:
2908         pthread_mutex_unlock(&mesh->mesh_mutex);
2909 #else
2910         (void)mesh;
2911         (void)enable;
2912         meshlink_errno = MESHLINK_ENOTSUP;
2913 #endif
2914 }
2915
2916 static void __attribute__((constructor)) meshlink_init(void) {
2917         crypto_init();
2918         unsigned int seed;
2919         randomize(&seed, sizeof(seed));
2920         srand(seed);
2921 }
2922
2923 static void __attribute__((destructor)) meshlink_exit(void) {
2924         crypto_exit();
2925 }
2926
2927 /// Device class traits
2928 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2929         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2930         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2931         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2932         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2933 };