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