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