]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Modified meshlink_invite to generate invites for submesh
[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         // Prepare the packet
1736         vpn_packet_t *packet = malloc(sizeof(*packet));
1737
1738         if(!packet) {
1739                 meshlink_errno = MESHLINK_ENOMEM;
1740                 return false;
1741         }
1742
1743         packet->probe = false;
1744         packet->tcp = false;
1745         packet->len = len + sizeof(*hdr);
1746
1747         hdr = (meshlink_packethdr_t *)packet->data;
1748         memset(hdr, 0, sizeof(*hdr));
1749         // leave the last byte as 0 to make sure strings are always
1750         // null-terminated if they are longer than the buffer
1751         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1752         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1753
1754         memcpy(packet->data + sizeof(*hdr), data, len);
1755
1756         // Queue it
1757         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1758                 free(packet);
1759                 meshlink_errno = MESHLINK_ENOMEM;
1760                 return false;
1761         }
1762
1763         // Notify event loop
1764         signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1765
1766         return true;
1767 }
1768
1769 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1770         (void)loop;
1771         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1772
1773         if(!packet) {
1774                 return;
1775         }
1776
1777         mesh->self->in_packets++;
1778         mesh->self->in_bytes += packet->len;
1779         route(mesh, mesh->self, packet);
1780 }
1781
1782 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1783         if(!mesh || !destination) {
1784                 meshlink_errno = MESHLINK_EINVAL;
1785                 return -1;
1786         }
1787
1788         pthread_mutex_lock(&(mesh->mesh_mutex));
1789
1790         node_t *n = (node_t *)destination;
1791
1792         if(!n->status.reachable) {
1793                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1794                 return 0;
1795
1796         } else if(n->mtuprobes > 30 && n->minmtu) {
1797                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1798                 return n->minmtu;
1799         } else {
1800                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1801                 return MTU;
1802         }
1803 }
1804
1805 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1806         if(!mesh || !node) {
1807                 meshlink_errno = MESHLINK_EINVAL;
1808                 return NULL;
1809         }
1810
1811         pthread_mutex_lock(&(mesh->mesh_mutex));
1812
1813         node_t *n = (node_t *)node;
1814
1815         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1816                 meshlink_errno = MESHLINK_EINTERNAL;
1817                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1818                 return false;
1819         }
1820
1821         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1822
1823         if(!fingerprint) {
1824                 meshlink_errno = MESHLINK_EINTERNAL;
1825         }
1826
1827         pthread_mutex_unlock(&(mesh->mesh_mutex));
1828         return fingerprint;
1829 }
1830
1831 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1832         if(!mesh) {
1833                 meshlink_errno = MESHLINK_EINVAL;
1834                 return NULL;
1835         }
1836
1837         return (meshlink_node_t *)mesh->self;
1838 }
1839
1840 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1841         if(!mesh || !name) {
1842                 meshlink_errno = MESHLINK_EINVAL;
1843                 return NULL;
1844         }
1845
1846         meshlink_node_t *node = NULL;
1847
1848         pthread_mutex_lock(&(mesh->mesh_mutex));
1849         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1850         pthread_mutex_unlock(&(mesh->mesh_mutex));
1851         return node;
1852 }
1853
1854 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1855         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1856                 meshlink_errno = MESHLINK_EINVAL;
1857                 return NULL;
1858         }
1859
1860         meshlink_node_t **result;
1861
1862         //lock mesh->nodes
1863         pthread_mutex_lock(&(mesh->mesh_mutex));
1864
1865         *nmemb = mesh->nodes->count;
1866         result = realloc(nodes, *nmemb * sizeof(*nodes));
1867
1868         if(result) {
1869                 meshlink_node_t **p = result;
1870
1871                 for splay_each(node_t, n, mesh->nodes) {
1872                         *p++ = (meshlink_node_t *)n;
1873                 }
1874         } else {
1875                 *nmemb = 0;
1876                 free(nodes);
1877                 meshlink_errno = MESHLINK_ENOMEM;
1878         }
1879
1880         pthread_mutex_unlock(&(mesh->mesh_mutex));
1881
1882         return result;
1883 }
1884
1885 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) {
1886         if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1887                 meshlink_errno = MESHLINK_EINVAL;
1888                 return NULL;
1889         }
1890
1891         meshlink_node_t **result;
1892
1893         pthread_mutex_lock(&(mesh->mesh_mutex));
1894
1895         *nmemb = 0;
1896
1897         for splay_each(node_t, n, mesh->nodes) {
1898                 if(n->devclass == devclass) {
1899                         *nmemb = *nmemb + 1;
1900                 }
1901         }
1902
1903         if(*nmemb == 0) {
1904                 free(nodes);
1905                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1906                 return NULL;
1907         }
1908
1909         result = realloc(nodes, *nmemb * sizeof(*nodes));
1910
1911         if(result) {
1912                 meshlink_node_t **p = result;
1913
1914                 for splay_each(node_t, n, mesh->nodes) {
1915                         if(n->devclass == devclass) {
1916                                 *p++ = (meshlink_node_t *)n;
1917                         }
1918                 }
1919         } else {
1920                 *nmemb = 0;
1921                 free(nodes);
1922                 meshlink_errno = MESHLINK_ENOMEM;
1923         }
1924
1925         pthread_mutex_unlock(&(mesh->mesh_mutex));
1926
1927         return result;
1928 }
1929
1930 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1931         if(!mesh || !node) {
1932                 meshlink_errno = MESHLINK_EINVAL;
1933                 return -1;
1934         }
1935
1936         dev_class_t devclass;
1937
1938         pthread_mutex_lock(&(mesh->mesh_mutex));
1939
1940         devclass = ((node_t *)node)->devclass;
1941
1942         pthread_mutex_unlock(&(mesh->mesh_mutex));
1943
1944         return devclass;
1945 }
1946
1947 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1948         if(!mesh || !data || !len || !signature || !siglen) {
1949                 meshlink_errno = MESHLINK_EINVAL;
1950                 return false;
1951         }
1952
1953         if(*siglen < MESHLINK_SIGLEN) {
1954                 meshlink_errno = MESHLINK_EINVAL;
1955                 return false;
1956         }
1957
1958         pthread_mutex_lock(&(mesh->mesh_mutex));
1959
1960         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1961                 meshlink_errno = MESHLINK_EINTERNAL;
1962                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1963                 return false;
1964         }
1965
1966         *siglen = MESHLINK_SIGLEN;
1967         pthread_mutex_unlock(&(mesh->mesh_mutex));
1968         return true;
1969 }
1970
1971 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1972         if(!mesh || !data || !len || !signature) {
1973                 meshlink_errno = MESHLINK_EINVAL;
1974                 return false;
1975         }
1976
1977         if(siglen != MESHLINK_SIGLEN) {
1978                 meshlink_errno = MESHLINK_EINVAL;
1979                 return false;
1980         }
1981
1982         pthread_mutex_lock(&(mesh->mesh_mutex));
1983
1984         bool rval = false;
1985
1986         struct node_t *n = (struct node_t *)source;
1987         node_read_ecdsa_public_key(mesh, n);
1988
1989         if(!n->ecdsa) {
1990                 meshlink_errno = MESHLINK_EINTERNAL;
1991                 rval = false;
1992         } else {
1993                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1994         }
1995
1996         pthread_mutex_unlock(&(mesh->mesh_mutex));
1997         return rval;
1998 }
1999
2000 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2001         char filename[PATH_MAX];
2002
2003         pthread_mutex_lock(&(mesh->mesh_mutex));
2004
2005         snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
2006
2007         if(mkdir(filename, 0700) && errno != EEXIST) {
2008                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
2009                 meshlink_errno = MESHLINK_ESTORAGE;
2010                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2011                 return false;
2012         }
2013
2014         // Count the number of valid invitations, clean up old ones
2015         DIR *dir = opendir(filename);
2016
2017         if(!dir) {
2018                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
2019                 meshlink_errno = MESHLINK_ESTORAGE;
2020                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2021                 return false;
2022         }
2023
2024         errno = 0;
2025         int count = 0;
2026         struct dirent *ent;
2027         time_t deadline = time(NULL) - 604800; // 1 week in the past
2028
2029         while((ent = readdir(dir))) {
2030                 if(strlen(ent->d_name) != 24) {
2031                         continue;
2032                 }
2033
2034                 char invname[PATH_MAX];
2035                 struct stat st;
2036
2037                 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
2038                         logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
2039                         continue;
2040                 }
2041
2042                 if(!stat(invname, &st)) {
2043                         if(mesh->invitation_key && deadline < st.st_mtime) {
2044                                 count++;
2045                         } else {
2046                                 unlink(invname);
2047                         }
2048                 } else {
2049                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
2050                         errno = 0;
2051                 }
2052         }
2053
2054         if(errno) {
2055                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
2056                 closedir(dir);
2057                 meshlink_errno = MESHLINK_ESTORAGE;
2058                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2059                 return false;
2060         }
2061
2062         closedir(dir);
2063
2064         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
2065
2066         // Remove the key if there are no outstanding invitations.
2067         if(!count) {
2068                 unlink(filename);
2069
2070                 if(mesh->invitation_key) {
2071                         ecdsa_free(mesh->invitation_key);
2072                         mesh->invitation_key = NULL;
2073                 }
2074         }
2075
2076         if(mesh->invitation_key) {
2077                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2078                 return true;
2079         }
2080
2081         // Create a new key if necessary.
2082         FILE *f = fopen(filename, "rb");
2083
2084         if(!f) {
2085                 if(errno != ENOENT) {
2086                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
2087                         meshlink_errno = MESHLINK_ESTORAGE;
2088                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2089                         return false;
2090                 }
2091
2092                 mesh->invitation_key = ecdsa_generate();
2093
2094                 if(!mesh->invitation_key) {
2095                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
2096                         meshlink_errno = MESHLINK_EINTERNAL;
2097                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2098                         return false;
2099                 }
2100
2101                 f = fopen(filename, "wb");
2102
2103                 if(!f) {
2104                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
2105                         meshlink_errno = MESHLINK_ESTORAGE;
2106                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2107                         return false;
2108                 }
2109
2110                 chmod(filename, 0600);
2111                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
2112                 fclose(f);
2113         } else {
2114                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
2115                 fclose(f);
2116
2117                 if(!mesh->invitation_key) {
2118                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
2119                         meshlink_errno = MESHLINK_ESTORAGE;
2120                 }
2121         }
2122
2123         pthread_mutex_unlock(&(mesh->mesh_mutex));
2124         return mesh->invitation_key;
2125 }
2126
2127 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2128         if(!mesh || !node || !address) {
2129                 meshlink_errno = MESHLINK_EINVAL;
2130                 return false;
2131         }
2132
2133         if(!is_valid_hostname(address)) {
2134                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2135                 meshlink_errno = MESHLINK_EINVAL;
2136                 return false;
2137         }
2138
2139         if(port && !is_valid_port(port)) {
2140                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2141                 meshlink_errno = MESHLINK_EINVAL;
2142                 return false;
2143         }
2144
2145         char *canonical_address;
2146
2147         if(port) {
2148                 xasprintf(&canonical_address, "%s %s", address, port);
2149         } else {
2150                 canonical_address = xstrdup(address);
2151         }
2152
2153         pthread_mutex_lock(&(mesh->mesh_mutex));
2154         bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
2155         pthread_mutex_unlock(&(mesh->mesh_mutex));
2156
2157         free(canonical_address);
2158         return rval;
2159 }
2160
2161 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2162         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2163 }
2164
2165 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2166         if(!mesh) {
2167                 meshlink_errno = MESHLINK_EINVAL;
2168                 return false;
2169         }
2170
2171         char *address = meshlink_get_external_address(mesh);
2172
2173         if(!address) {
2174                 return false;
2175         }
2176
2177         bool rval = false;
2178
2179         pthread_mutex_lock(&(mesh->mesh_mutex));
2180         rval = append_config_file(mesh, mesh->self->name, "Address", address);
2181         pthread_mutex_unlock(&(mesh->mesh_mutex));
2182
2183         free(address);
2184         return rval;
2185 }
2186
2187 int meshlink_get_port(meshlink_handle_t *mesh) {
2188         if(!mesh) {
2189                 meshlink_errno = MESHLINK_EINVAL;
2190                 return -1;
2191         }
2192
2193         if(!mesh->myport) {
2194                 meshlink_errno = MESHLINK_EINTERNAL;
2195                 return -1;
2196         }
2197
2198         return atoi(mesh->myport);
2199 }
2200
2201 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2202         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2203                 meshlink_errno = MESHLINK_EINVAL;
2204                 return false;
2205         }
2206
2207         if(mesh->myport && port == atoi(mesh->myport)) {
2208                 return true;
2209         }
2210
2211         if(!try_bind(port)) {
2212                 meshlink_errno = MESHLINK_ENETWORK;
2213                 return false;
2214         }
2215
2216         bool rval = false;
2217
2218         pthread_mutex_lock(&(mesh->mesh_mutex));
2219
2220         if(mesh->threadstarted) {
2221                 meshlink_errno = MESHLINK_EINVAL;
2222                 goto done;
2223         }
2224
2225         close_network_connections(mesh);
2226         exit_configuration(&mesh->config);
2227
2228         char portstr[10];
2229         snprintf(portstr, sizeof(portstr), "%d", port);
2230         portstr[sizeof(portstr) - 1] = 0;
2231
2232         modify_config_file(mesh, mesh->name, "Port", portstr, true);
2233
2234         init_configuration(&mesh->config);
2235
2236         if(!read_server_config(mesh)) {
2237                 meshlink_errno = MESHLINK_ESTORAGE;
2238         } else if(!setup_network(mesh)) {
2239                 meshlink_errno = MESHLINK_ENETWORK;
2240         } else {
2241                 rval = true;
2242         }
2243
2244 done:
2245         pthread_mutex_unlock(&(mesh->mesh_mutex));
2246
2247         return rval;
2248 }
2249
2250 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2251         mesh->invitation_timeout = timeout;
2252 }
2253
2254 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2255         meshlink_submesh_t *s = NULL;
2256
2257         if(!mesh) {
2258                 meshlink_errno = MESHLINK_EINVAL;
2259                 return NULL;
2260         }
2261
2262         if(submesh) {
2263                 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2264
2265                 if(s != submesh) {
2266                         logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2267                         meshlink_errno = MESHLINK_EINVAL;
2268                         return NULL;
2269                 }
2270         }
2271
2272         pthread_mutex_lock(&(mesh->mesh_mutex));
2273
2274         // Check validity of the new node's name
2275         if(!check_id(name)) {
2276                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2277                 meshlink_errno = MESHLINK_EINVAL;
2278                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2279                 return NULL;
2280         }
2281
2282         // Ensure no host configuration file with that name exists
2283         char filename[PATH_MAX];
2284         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2285
2286         if(!access(filename, F_OK)) {
2287                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2288                 meshlink_errno = MESHLINK_EEXIST;
2289                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2290                 return NULL;
2291         }
2292
2293         // Ensure no other nodes know about this name
2294         if(meshlink_get_node(mesh, name)) {
2295                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2296                 meshlink_errno = MESHLINK_EEXIST;
2297                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2298                 return NULL;
2299         }
2300
2301         // Get the local address
2302         char *address = get_my_hostname(mesh, flags);
2303
2304         if(!address) {
2305                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2306                 meshlink_errno = MESHLINK_ERESOLV;
2307                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2308                 return NULL;
2309         }
2310
2311         if(!refresh_invitation_key(mesh)) {
2312                 meshlink_errno = MESHLINK_EINTERNAL;
2313                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2314                 return NULL;
2315         }
2316
2317         char hash[64];
2318
2319         // Create a hash of the key.
2320         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2321         sha512(fingerprint, strlen(fingerprint), hash);
2322         b64encode_urlsafe(hash, hash, 18);
2323
2324         // Create a random cookie for this invitation.
2325         char cookie[25];
2326         randomize(cookie, 18);
2327
2328         // Create a filename that doesn't reveal the cookie itself
2329         char buf[18 + strlen(fingerprint)];
2330         char cookiehash[64];
2331         memcpy(buf, cookie, 18);
2332         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2333         sha512(buf, sizeof(buf), cookiehash);
2334         b64encode_urlsafe(cookiehash, cookiehash, 18);
2335
2336         b64encode_urlsafe(cookie, cookie, 18);
2337
2338         free(fingerprint);
2339
2340         // Create a file containing the details of the invitation.
2341         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
2342         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
2343
2344         if(!ifd) {
2345                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
2346                 meshlink_errno = MESHLINK_ESTORAGE;
2347                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2348                 return NULL;
2349         }
2350
2351         FILE *f = fdopen(ifd, "w");
2352
2353         if(!f) {
2354                 abort();
2355         }
2356
2357         // Fill in the details.
2358         fprintf(f, "Name = %s\n", name);
2359
2360         if(s) {
2361                 fprintf(f, "SubMesh = %s\n", s->name);
2362         }
2363
2364         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2365
2366         // Copy Broadcast and Mode
2367         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2368         FILE *tc = fopen(filename,  "r");
2369
2370         if(tc) {
2371                 char buf[1024];
2372
2373                 while(fgets(buf, sizeof(buf), tc)) {
2374                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2375                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2376                                 fputs(buf, f);
2377
2378                                 // Make sure there is a newline character.
2379                                 if(!strchr(buf, '\n')) {
2380                                         fputc('\n', f);
2381                                 }
2382                         }
2383                 }
2384
2385                 fclose(tc);
2386         } else {
2387                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2388                 meshlink_errno = MESHLINK_ESTORAGE;
2389                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2390                 return NULL;
2391         }
2392
2393         fprintf(f, "#---------------------------------------------------------------#\n");
2394         fprintf(f, "Name = %s\n", mesh->self->name);
2395
2396         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2397         fcopy(f, filename);
2398         fclose(f);
2399
2400         // Create an URL from the local address, key hash and cookie
2401         char *url;
2402         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2403         free(address);
2404
2405         pthread_mutex_unlock(&(mesh->mesh_mutex));
2406         return url;
2407 }
2408
2409 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2410         return meshlink_invite_ex(mesh, submesh, name, 0);
2411 }
2412
2413 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2414         if(!mesh || !invitation) {
2415                 meshlink_errno = MESHLINK_EINVAL;
2416                 return false;
2417         }
2418
2419         pthread_mutex_lock(&(mesh->mesh_mutex));
2420
2421         //Before doing meshlink_join make sure we are not connected to another mesh
2422         if(mesh->threadstarted) {
2423                 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2424                 meshlink_errno = MESHLINK_EINVAL;
2425                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2426                 return false;
2427         }
2428
2429         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2430         char copy[strlen(invitation) + 1];
2431         strcpy(copy, invitation);
2432
2433         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2434
2435         char *slash = strchr(copy, '/');
2436
2437         if(!slash) {
2438                 goto invalid;
2439         }
2440
2441         *slash++ = 0;
2442
2443         if(strlen(slash) != 48) {
2444                 goto invalid;
2445         }
2446
2447         char *address = copy;
2448         char *port = NULL;
2449
2450         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2451                 goto invalid;
2452         }
2453
2454         // Generate a throw-away key for the invitation.
2455         ecdsa_t *key = ecdsa_generate();
2456
2457         if(!key) {
2458                 meshlink_errno = MESHLINK_EINTERNAL;
2459                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2460                 return false;
2461         }
2462
2463         char *b64key = ecdsa_get_base64_public_key(key);
2464         char *comma;
2465         mesh->sock = -1;
2466
2467         while(address && *address) {
2468                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2469                 comma = strchr(address, ',');
2470
2471                 if(comma) {
2472                         *comma++ = 0;
2473                 }
2474
2475                 // Split of the port
2476                 port = strrchr(address, ':');
2477
2478                 if(!port) {
2479                         goto invalid;
2480                 }
2481
2482                 *port++ = 0;
2483
2484                 // IPv6 address are enclosed in brackets, per RFC 3986
2485                 if(*address == '[') {
2486                         address++;
2487                         char *bracket = strchr(address, ']');
2488
2489                         if(!bracket) {
2490                                 goto invalid;
2491                         }
2492
2493                         *bracket++ = 0;
2494
2495                         if(*bracket) {
2496                                 goto invalid;
2497                         }
2498                 }
2499
2500                 // Connect to the meshlink daemon mentioned in the URL.
2501                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2502
2503                 if(ai) {
2504                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2505                                 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2506
2507                                 if(mesh->sock == -1) {
2508                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2509                                         meshlink_errno = MESHLINK_ENETWORK;
2510                                         continue;
2511                                 }
2512
2513                                 set_timeout(mesh->sock, 5000);
2514
2515                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2516                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2517                                         meshlink_errno = MESHLINK_ENETWORK;
2518                                         closesocket(mesh->sock);
2519                                         mesh->sock = -1;
2520                                         continue;
2521                                 }
2522                         }
2523
2524                         freeaddrinfo(ai);
2525                 } else {
2526                         meshlink_errno = MESHLINK_ERESOLV;
2527                 }
2528
2529                 if(mesh->sock != -1 || !comma) {
2530                         break;
2531                 }
2532
2533                 address = comma;
2534         }
2535
2536         if(mesh->sock == -1) {
2537                 pthread_mutex_unlock(&mesh->mesh_mutex);
2538                 return false;
2539         }
2540
2541         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2542
2543         // Tell him we have an invitation, and give him our throw-away key.
2544
2545         mesh->blen = 0;
2546
2547         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2548                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2549                 closesocket(mesh->sock);
2550                 meshlink_errno = MESHLINK_ENETWORK;
2551                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2552                 return false;
2553         }
2554
2555         free(b64key);
2556
2557         char hisname[4096] = "";
2558         int code, hismajor, hisminor = 0;
2559
2560         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) {
2561                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2562                 closesocket(mesh->sock);
2563                 meshlink_errno = MESHLINK_ENETWORK;
2564                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2565                 return false;
2566         }
2567
2568         // Check if the hash of the key he gave us matches the hash in the URL.
2569         char *fingerprint = mesh->line + 2;
2570         char hishash[64];
2571
2572         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2573                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2574                 meshlink_errno = MESHLINK_EINTERNAL;
2575                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2576                 return false;
2577         }
2578
2579         if(memcmp(hishash, mesh->hash, 18)) {
2580                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2581                 meshlink_errno = MESHLINK_EPEER;
2582                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2583                 return false;
2584
2585         }
2586
2587         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2588
2589         if(!hiskey) {
2590                 meshlink_errno = MESHLINK_EINTERNAL;
2591                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2592                 return false;
2593         }
2594
2595         // Start an SPTPS session
2596         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2597                 meshlink_errno = MESHLINK_EINTERNAL;
2598                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2599                 return false;
2600         }
2601
2602         // Feed rest of input buffer to SPTPS
2603         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2604                 meshlink_errno = MESHLINK_EPEER;
2605                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2606                 return false;
2607         }
2608
2609         int len;
2610
2611         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2612                 if(len < 0) {
2613                         if(errno == EINTR) {
2614                                 continue;
2615                         }
2616
2617                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2618                         meshlink_errno = MESHLINK_ENETWORK;
2619                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2620                         return false;
2621                 }
2622
2623                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2624                         meshlink_errno = MESHLINK_EPEER;
2625                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2626                         return false;
2627                 }
2628         }
2629
2630         sptps_stop(&mesh->sptps);
2631         ecdsa_free(hiskey);
2632         ecdsa_free(key);
2633         closesocket(mesh->sock);
2634
2635         if(!mesh->success) {
2636                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2637                 meshlink_errno = MESHLINK_EPEER;
2638                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2639                 return false;
2640         }
2641
2642         pthread_mutex_unlock(&(mesh->mesh_mutex));
2643         return true;
2644
2645 invalid:
2646         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2647         meshlink_errno = MESHLINK_EINVAL;
2648         pthread_mutex_unlock(&(mesh->mesh_mutex));
2649         return false;
2650 }
2651
2652 char *meshlink_export(meshlink_handle_t *mesh) {
2653         if(!mesh) {
2654                 meshlink_errno = MESHLINK_EINVAL;
2655                 return NULL;
2656         }
2657
2658         pthread_mutex_lock(&(mesh->mesh_mutex));
2659
2660         char filename[PATH_MAX];
2661         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2662         FILE *f = fopen(filename, "r");
2663
2664         if(!f) {
2665                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2666                 meshlink_errno = MESHLINK_ESTORAGE;
2667                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2668                 return NULL;
2669         }
2670
2671         fseek(f, 0, SEEK_END);
2672         int fsize = ftell(f);
2673         rewind(f);
2674
2675         size_t len = fsize + 9 + strlen(mesh->self->name);
2676         char *buf = xmalloc(len);
2677         snprintf(buf, len, "Name = %s\n", mesh->self->name);
2678
2679         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2680                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2681                 fclose(f);
2682                 free(buf);
2683                 meshlink_errno = MESHLINK_ESTORAGE;
2684                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2685                 return NULL;
2686         }
2687
2688         fclose(f);
2689         buf[len - 1] = 0;
2690
2691         pthread_mutex_unlock(&(mesh->mesh_mutex));
2692         return buf;
2693 }
2694
2695 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2696         if(!mesh || !data) {
2697                 meshlink_errno = MESHLINK_EINVAL;
2698                 return false;
2699         }
2700
2701         pthread_mutex_lock(&(mesh->mesh_mutex));
2702
2703         if(strncmp(data, "Name = ", 7)) {
2704                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2705                 meshlink_errno = MESHLINK_EPEER;
2706                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2707                 return false;
2708         }
2709
2710         char *end = strchr(data + 7, '\n');
2711
2712         if(!end) {
2713                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2714                 meshlink_errno = MESHLINK_EPEER;
2715                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2716                 return false;
2717         }
2718
2719         int len = end - (data + 7);
2720         char name[len + 1];
2721         memcpy(name, data + 7, len);
2722         name[len] = 0;
2723
2724         if(!check_id(name)) {
2725                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2726                 meshlink_errno = MESHLINK_EPEER;
2727                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2728                 return false;
2729         }
2730
2731         char filename[PATH_MAX];
2732         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2733
2734         if(!access(filename, F_OK)) {
2735                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2736                 meshlink_errno = MESHLINK_EEXIST;
2737                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2738                 return false;
2739         }
2740
2741         if(errno != ENOENT) {
2742                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2743                 meshlink_errno = MESHLINK_ESTORAGE;
2744                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2745                 return false;
2746         }
2747
2748         FILE *f = fopen(filename, "w");
2749
2750         if(!f) {
2751                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2752                 meshlink_errno = MESHLINK_ESTORAGE;
2753                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2754                 return false;
2755         }
2756
2757         fwrite(end + 1, strlen(end + 1), 1, f);
2758         fclose(f);
2759
2760         load_all_nodes(mesh);
2761
2762         pthread_mutex_unlock(&(mesh->mesh_mutex));
2763         return true;
2764 }
2765
2766 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2767         if(!mesh || !node) {
2768                 meshlink_errno = MESHLINK_EINVAL;
2769                 return;
2770         }
2771
2772         pthread_mutex_lock(&(mesh->mesh_mutex));
2773
2774         node_t *n;
2775         n = (node_t *)node;
2776         n->status.blacklisted = true;
2777         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2778
2779         //Make blacklisting persistent in the config file
2780         append_config_file(mesh, n->name, "blacklisted", "yes");
2781
2782         //Immediately terminate any connections we have with the blacklisted node
2783         for list_each(connection_t, c, mesh->connections) {
2784                 if(c->node == n) {
2785                         terminate_connection(mesh, c, c->status.active);
2786                 }
2787         }
2788
2789         pthread_mutex_unlock(&(mesh->mesh_mutex));
2790 }
2791
2792 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2793         if(!mesh || !node) {
2794                 meshlink_errno = MESHLINK_EINVAL;
2795                 return;
2796         }
2797
2798         pthread_mutex_lock(&(mesh->mesh_mutex));
2799
2800         node_t *n = (node_t *)node;
2801         n->status.blacklisted = false;
2802
2803         //TODO: remove blacklisted = yes from the config file
2804
2805         pthread_mutex_unlock(&(mesh->mesh_mutex));
2806         return;
2807 }
2808
2809 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2810         mesh->default_blacklist = blacklist;
2811 }
2812
2813 /* Hint that a hostname may be found at an address
2814  * See header file for detailed comment.
2815  */
2816 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2817         if(!mesh || !node || !addr) {
2818                 return;
2819         }
2820
2821         // Ignore hints about ourself.
2822         if((node_t *)node == mesh->self) {
2823                 return;
2824         }
2825
2826         pthread_mutex_lock(&(mesh->mesh_mutex));
2827
2828         char *host = NULL, *port = NULL, *str = NULL;
2829         sockaddr2str((const sockaddr_t *)addr, &host, &port);
2830
2831         if(host && port) {
2832                 xasprintf(&str, "%s %s", host, port);
2833
2834                 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2835                         modify_config_file(mesh, node->name, "Address", str, 5);
2836                 } else {
2837                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2838                 }
2839         }
2840
2841         free(str);
2842         free(host);
2843         free(port);
2844
2845         pthread_mutex_unlock(&(mesh->mesh_mutex));
2846         // @TODO do we want to fire off a connection attempt right away?
2847 }
2848
2849 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2850         (void)port;
2851         node_t *n = utcp->priv;
2852         meshlink_handle_t *mesh = n->mesh;
2853         return mesh->channel_accept_cb;
2854 }
2855
2856 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2857         meshlink_channel_t *channel = connection->priv;
2858
2859         if(!channel) {
2860                 abort();
2861         }
2862
2863         node_t *n = channel->node;
2864         meshlink_handle_t *mesh = n->mesh;
2865
2866         if(n->status.destroyed) {
2867                 meshlink_channel_close(mesh, channel);
2868         } else if(channel->receive_cb) {
2869                 channel->receive_cb(mesh, channel, data, len);
2870         }
2871
2872         return len;
2873 }
2874
2875 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2876         node_t *n = utcp_connection->utcp->priv;
2877
2878         if(!n) {
2879                 abort();
2880         }
2881
2882         meshlink_handle_t *mesh = n->mesh;
2883
2884         if(!mesh->channel_accept_cb) {
2885                 return;
2886         }
2887
2888         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2889         channel->node = n;
2890         channel->c = utcp_connection;
2891
2892         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2893                 utcp_accept(utcp_connection, channel_recv, channel);
2894         } else {
2895                 free(channel);
2896         }
2897 }
2898
2899 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2900         node_t *n = utcp->priv;
2901
2902         if(n->status.destroyed) {
2903                 return -1;
2904         }
2905
2906         meshlink_handle_t *mesh = n->mesh;
2907         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2908 }
2909
2910 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2911         if(!mesh || !channel) {
2912                 meshlink_errno = MESHLINK_EINVAL;
2913                 return;
2914         }
2915
2916         channel->receive_cb = cb;
2917 }
2918
2919 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2920         (void)mesh;
2921         node_t *n = (node_t *)source;
2922
2923         if(!n->utcp) {
2924                 abort();
2925         }
2926
2927         utcp_recv(n->utcp, data, len);
2928 }
2929
2930 static void channel_poll(struct utcp_connection *connection, size_t len) {
2931         meshlink_channel_t *channel = connection->priv;
2932
2933         if(!channel) {
2934                 abort();
2935         }
2936
2937         node_t *n = channel->node;
2938         meshlink_handle_t *mesh = n->mesh;
2939
2940         if(channel->poll_cb) {
2941                 channel->poll_cb(mesh, channel, len);
2942         }
2943 }
2944
2945 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2946         (void)mesh;
2947         channel->poll_cb = cb;
2948         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2949 }
2950
2951 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2952         if(!mesh) {
2953                 meshlink_errno = MESHLINK_EINVAL;
2954                 return;
2955         }
2956
2957         pthread_mutex_lock(&mesh->mesh_mutex);
2958         mesh->channel_accept_cb = cb;
2959         mesh->receive_cb = channel_receive;
2960
2961         for splay_each(node_t, n, mesh->nodes) {
2962                 if(!n->utcp && n != mesh->self) {
2963                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2964                 }
2965         }
2966
2967         pthread_mutex_unlock(&mesh->mesh_mutex);
2968 }
2969
2970 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) {
2971         if(data || len) {
2972                 abort();        // TODO: handle non-NULL data
2973         }
2974
2975         if(!mesh || !node) {
2976                 meshlink_errno = MESHLINK_EINVAL;
2977                 return NULL;
2978         }
2979
2980         node_t *n = (node_t *)node;
2981
2982         if(!n->utcp) {
2983                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2984                 mesh->receive_cb = channel_receive;
2985
2986                 if(!n->utcp) {
2987                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2988                         return NULL;
2989                 }
2990         }
2991
2992         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2993         channel->node = n;
2994         channel->receive_cb = cb;
2995         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2996
2997         if(!channel->c) {
2998                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2999                 free(channel);
3000                 return NULL;
3001         }
3002
3003         return channel;
3004 }
3005
3006 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) {
3007         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3008 }
3009
3010 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3011         if(!mesh || !channel) {
3012                 meshlink_errno = MESHLINK_EINVAL;
3013                 return;
3014         }
3015
3016         utcp_shutdown(channel->c, direction);
3017 }
3018
3019 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3020         if(!mesh || !channel) {
3021                 meshlink_errno = MESHLINK_EINVAL;
3022                 return;
3023         }
3024
3025         utcp_close(channel->c);
3026         free(channel);
3027 }
3028
3029 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3030         if(!mesh || !channel) {
3031                 meshlink_errno = MESHLINK_EINVAL;
3032                 return -1;
3033         }
3034
3035         if(!len) {
3036                 return 0;
3037         }
3038
3039         if(!data) {
3040                 meshlink_errno = MESHLINK_EINVAL;
3041                 return -1;
3042         }
3043
3044         // TODO: more finegrained locking.
3045         // Ideally we want to put the data into the UTCP connection's send buffer.
3046         // Then, preferrably only if there is room in the receiver window,
3047         // kick the meshlink thread to go send packets.
3048
3049         pthread_mutex_lock(&mesh->mesh_mutex);
3050         ssize_t retval = utcp_send(channel->c, data, len);
3051         pthread_mutex_unlock(&mesh->mesh_mutex);
3052
3053         if(retval < 0) {
3054                 meshlink_errno = MESHLINK_ENETWORK;
3055         }
3056
3057         return retval;
3058 }
3059
3060 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3061         if(!mesh || !channel) {
3062                 meshlink_errno = MESHLINK_EINVAL;
3063                 return -1;
3064         }
3065
3066         return channel->c->flags;
3067 }
3068
3069 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3070         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3071                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3072         }
3073
3074         if(mesh->node_status_cb) {
3075                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
3076         }
3077 }
3078
3079 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3080         if(!mesh->node_duplicate_cb || n->status.duplicate) {
3081                 return;
3082         }
3083
3084         n->status.duplicate = true;
3085         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3086 }
3087
3088 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3089 #if HAVE_CATTA
3090
3091         if(!mesh) {
3092                 meshlink_errno = MESHLINK_EINVAL;
3093                 return;
3094         }
3095
3096         pthread_mutex_lock(&mesh->mesh_mutex);
3097
3098         if(mesh->discovery == enable) {
3099                 goto end;
3100         }
3101
3102         if(mesh->threadstarted) {
3103                 if(enable) {
3104                         discovery_start(mesh);
3105                 } else {
3106                         discovery_stop(mesh);
3107                 }
3108         }
3109
3110         mesh->discovery = enable;
3111
3112 end:
3113         pthread_mutex_unlock(&mesh->mesh_mutex);
3114 #else
3115         (void)mesh;
3116         (void)enable;
3117         meshlink_errno = MESHLINK_ENOTSUP;
3118 #endif
3119 }
3120
3121 static void __attribute__((constructor)) meshlink_init(void) {
3122         crypto_init();
3123         unsigned int seed;
3124         randomize(&seed, sizeof(seed));
3125         srand(seed);
3126 }
3127
3128 static void __attribute__((destructor)) meshlink_exit(void) {
3129         crypto_exit();
3130 }
3131
3132 /// Device class traits
3133 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3134         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3135         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
3136         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
3137         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
3138 };