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