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