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