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