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