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