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