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