]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Lock meshlink.conf to ensure only one instance can run at a time.
[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         [MESHLINK_ENOTSUP] = "Operation not supported",
873         [MESHLINK_EBUSY] = "MeshLink instance already in use",
874 };
875
876 const char *meshlink_strerror(meshlink_errno_t err) {
877         if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
878                 return "Invalid error code";
879         }
880
881         return errstr[err];
882 }
883
884 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
885         ecdsa_t *key;
886         FILE *f;
887         char pubname[PATH_MAX], privname[PATH_MAX];
888
889         logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
890
891         if(!(key = ecdsa_generate())) {
892                 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
893                 meshlink_errno = MESHLINK_EINTERNAL;
894                 return false;
895         } else {
896                 logger(mesh, MESHLINK_DEBUG, "Done.\n");
897         }
898
899         if(snprintf(privname, sizeof(privname), "%s" SLASH "ecdsa_key.priv", mesh->confbase) >= PATH_MAX) {
900                 logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "ecdsa_key.priv\n", mesh->confbase);
901                 meshlink_errno = MESHLINK_ESTORAGE;
902                 return false;
903         }
904
905         f = fopen(privname, "wb");
906
907         if(!f) {
908                 meshlink_errno = MESHLINK_ESTORAGE;
909                 return false;
910         }
911
912 #ifdef HAVE_FCHMOD
913         fchmod(fileno(f), 0600);
914 #endif
915
916         if(!ecdsa_write_pem_private_key(key, f)) {
917                 logger(mesh, MESHLINK_DEBUG, "Error writing private key!\n");
918                 ecdsa_free(key);
919                 fclose(f);
920                 meshlink_errno = MESHLINK_EINTERNAL;
921                 return false;
922         }
923
924         fclose(f);
925
926         snprintf(pubname, sizeof(pubname), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
927         f = fopen(pubname, "a");
928
929         if(!f) {
930                 meshlink_errno = MESHLINK_ESTORAGE;
931                 return false;
932         }
933
934         char *pubkey = ecdsa_get_base64_public_key(key);
935         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
936         free(pubkey);
937
938         fclose(f);
939         ecdsa_free(key);
940
941         return true;
942 }
943
944 static struct timeval idle(event_loop_t *loop, void *data) {
945         (void)loop;
946         meshlink_handle_t *mesh = data;
947         struct timeval t, tmin = {3600, 0};
948
949         for splay_each(node_t, n, mesh->nodes) {
950                 if(!n->utcp) {
951                         continue;
952                 }
953
954                 t = utcp_timeout(n->utcp);
955
956                 if(timercmp(&t, &tmin, <)) {
957                         tmin = t;
958                 }
959         }
960
961         return tmin;
962 }
963
964 // Get our local address(es) by simulating connecting to an Internet host.
965 static void add_local_addresses(meshlink_handle_t *mesh) {
966         char host[NI_MAXHOST];
967         char entry[MAX_STRING_SIZE];
968
969         // IPv4 example.org
970
971         if(getlocaladdrname("93.184.216.34", host, sizeof(host))) {
972                 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
973                 append_config_file(mesh, mesh->name, "Address", entry);
974         }
975
976         // IPv6 example.org
977
978         if(getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", host, sizeof(host))) {
979                 snprintf(entry, sizeof(entry), "%s %s", host, mesh->myport);
980                 append_config_file(mesh, mesh->name, "Address", entry);
981         }
982 }
983
984 static bool meshlink_setup(meshlink_handle_t *mesh) {
985         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
986                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
987                 meshlink_errno = MESHLINK_ESTORAGE;
988                 return false;
989         }
990
991         char filename[PATH_MAX];
992         snprintf(filename, sizeof(filename), "%s" SLASH "hosts", mesh->confbase);
993
994         if(mkdir(filename, 0777) && errno != EEXIST) {
995                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
996                 meshlink_errno = MESHLINK_ESTORAGE;
997                 return false;
998         }
999
1000         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
1001
1002         if(!access(filename, F_OK)) {
1003                 logger(mesh, MESHLINK_DEBUG, "Configuration file %s already exists!\n", filename);
1004                 meshlink_errno = MESHLINK_EEXIST;
1005                 return false;
1006         }
1007
1008         FILE *f = fopen(filename, "w");
1009
1010         if(!f) {
1011                 logger(mesh, MESHLINK_DEBUG, "Could not create file %s: %s\n", filename, strerror(errno));
1012                 meshlink_errno = MESHLINK_ESTORAGE;
1013                 return false;
1014         }
1015
1016         fprintf(f, "Name = %s\n", mesh->name);
1017         fclose(f);
1018
1019         if(!ecdsa_keygen(mesh)) {
1020                 meshlink_errno = MESHLINK_EINTERNAL;
1021                 unlink(filename);
1022                 return false;
1023         }
1024
1025         if(check_port(mesh) == 0) {
1026                 meshlink_errno = MESHLINK_ENETWORK;
1027                 unlink(filename);
1028                 return false;
1029         }
1030
1031         return true;
1032 }
1033
1034 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1035         // Validate arguments provided by the application
1036         bool usingname = false;
1037
1038         logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1039
1040         if(!confbase || !*confbase) {
1041                 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1042                 meshlink_errno = MESHLINK_EINVAL;
1043                 return NULL;
1044         }
1045
1046         if(!appname || !*appname) {
1047                 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1048                 meshlink_errno = MESHLINK_EINVAL;
1049                 return NULL;
1050         }
1051
1052         if(strchr(appname, ' ')) {
1053                 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1054                 meshlink_errno = MESHLINK_EINVAL;
1055                 return NULL;
1056         }
1057
1058         if(!name || !*name) {
1059                 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1060                 //return NULL;
1061         } else { //check name only if there is a name != NULL
1062
1063                 if(!check_id(name)) {
1064                         logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1065                         meshlink_errno = MESHLINK_EINVAL;
1066                         return NULL;
1067                 } else {
1068                         usingname = true;
1069                 }
1070         }
1071
1072         if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1073                 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1074                 meshlink_errno = MESHLINK_EINVAL;
1075                 return NULL;
1076         }
1077
1078         meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1079         mesh->confbase = xstrdup(confbase);
1080         mesh->appname = xstrdup(appname);
1081         mesh->devclass = devclass;
1082         mesh->discovery = true;
1083         mesh->invitation_timeout = 604800; // 1 week
1084
1085         if(usingname) {
1086                 mesh->name = xstrdup(name);
1087         }
1088
1089         // initialize mutex
1090         pthread_mutexattr_t attr;
1091         pthread_mutexattr_init(&attr);
1092         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1093         pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1094
1095         mesh->threadstarted = false;
1096         event_loop_init(&mesh->loop);
1097         mesh->loop.data = mesh;
1098
1099         meshlink_queue_init(&mesh->outpacketqueue);
1100
1101         // Check whether meshlink.conf already exists
1102
1103         char filename[PATH_MAX];
1104         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1105
1106         if(access(filename, R_OK)) {
1107                 if(errno == ENOENT) {
1108                         // If not, create it
1109                         if(!meshlink_setup(mesh)) {
1110                                 // meshlink_errno is set by meshlink_setup()
1111                                 return NULL;
1112                         }
1113                 } else {
1114                         logger(NULL, MESHLINK_ERROR, "Cannot not read from %s: %s\n", filename, strerror(errno));
1115                         meshlink_close(mesh);
1116                         meshlink_errno = MESHLINK_ESTORAGE;
1117                         return NULL;
1118                 }
1119         }
1120
1121         // Open the configuration file and lock it
1122
1123         mesh->conffile = fopen(filename, "r");
1124
1125         if(!mesh->conffile) {
1126                 logger(NULL, MESHLINK_ERROR, "Cannot not open %s: %s\n", filename, strerror(errno));
1127                 meshlink_close(mesh);
1128                 meshlink_errno = MESHLINK_ESTORAGE;
1129                 return NULL;
1130         }
1131
1132 #ifdef FD_CLOEXEC
1133         fcntl(fileno(mesh->conffile), F_SETFD, FD_CLOEXEC);
1134 #endif
1135
1136 #ifdef HAVE_MINGW
1137         // TODO: use _locking()?
1138 #else
1139         if(flock(fileno(mesh->conffile), LOCK_EX | LOCK_NB) != 0) {
1140                 logger(NULL, MESHLINK_ERROR, "Cannot lock %s: %s\n", filename, strerror(errno));
1141                 meshlink_close(mesh);
1142                 meshlink_errno = MESHLINK_EBUSY;
1143                 return NULL;
1144         }
1145 #endif
1146
1147         // Read the configuration
1148
1149         init_configuration(&mesh->config);
1150
1151         if(!read_server_config(mesh)) {
1152                 meshlink_close(mesh);
1153                 meshlink_errno = MESHLINK_ESTORAGE;
1154                 return NULL;
1155         };
1156
1157 #ifdef HAVE_MINGW
1158         struct WSAData wsa_state;
1159
1160         WSAStartup(MAKEWORD(2, 2), &wsa_state);
1161
1162 #endif
1163
1164         // Setup up everything
1165         // TODO: we should not open listening sockets yet
1166
1167         if(!setup_network(mesh)) {
1168                 meshlink_close(mesh);
1169                 meshlink_errno = MESHLINK_ENETWORK;
1170                 return NULL;
1171         }
1172
1173         add_local_addresses(mesh);
1174
1175         idle_set(&mesh->loop, idle, mesh);
1176
1177         logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1178         return mesh;
1179 }
1180
1181 static void *meshlink_main_loop(void *arg) {
1182         meshlink_handle_t *mesh = arg;
1183
1184         pthread_mutex_lock(&(mesh->mesh_mutex));
1185
1186         try_outgoing_connections(mesh);
1187
1188         logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1189         main_loop(mesh);
1190         logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1191
1192         pthread_mutex_unlock(&(mesh->mesh_mutex));
1193         return NULL;
1194 }
1195
1196 bool meshlink_start(meshlink_handle_t *mesh) {
1197         if(!mesh) {
1198                 meshlink_errno = MESHLINK_EINVAL;
1199                 return false;
1200         }
1201
1202         logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1203
1204         pthread_mutex_lock(&(mesh->mesh_mutex));
1205
1206         if(mesh->threadstarted) {
1207                 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1208                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1209                 return true;
1210         }
1211
1212         if(mesh->listen_socket[0].tcp.fd < 0) {
1213                 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1214                 meshlink_errno = MESHLINK_ENETWORK;
1215                 return false;
1216         }
1217
1218         mesh->thedatalen = 0;
1219
1220         // TODO: open listening sockets first
1221
1222         //Check that a valid name is set
1223         if(!mesh->name) {
1224                 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1225                 meshlink_errno = MESHLINK_EINVAL;
1226                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1227                 return false;
1228         }
1229
1230         // Start the main thread
1231
1232         event_loop_start(&mesh->loop);
1233
1234         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1235                 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1236                 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1237                 meshlink_errno = MESHLINK_EINTERNAL;
1238                 event_loop_stop(&mesh->loop);
1239                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1240                 return false;
1241         }
1242
1243         mesh->threadstarted = true;
1244
1245 #if HAVE_CATTA
1246
1247         if(mesh->discovery) {
1248                 discovery_start(mesh);
1249         }
1250
1251 #endif
1252
1253         pthread_mutex_unlock(&(mesh->mesh_mutex));
1254         return true;
1255 }
1256
1257 void meshlink_stop(meshlink_handle_t *mesh) {
1258         if(!mesh) {
1259                 meshlink_errno = MESHLINK_EINVAL;
1260                 return;
1261         }
1262
1263         pthread_mutex_lock(&(mesh->mesh_mutex));
1264         logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1265
1266 #if HAVE_CATTA
1267
1268         // Stop discovery
1269         if(mesh->discovery) {
1270                 discovery_stop(mesh);
1271         }
1272
1273 #endif
1274
1275         // Shut down the main thread
1276         event_loop_stop(&mesh->loop);
1277
1278         // Send ourselves a UDP packet to kick the event loop
1279         for(int i = 0; i < mesh->listen_sockets; i++) {
1280                 sockaddr_t sa;
1281                 socklen_t salen = sizeof(sa.sa);
1282
1283                 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1284                         logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1285                         continue;
1286                 }
1287
1288                 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1289                         logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1290                 }
1291         }
1292
1293         if(mesh->threadstarted) {
1294                 // Wait for the main thread to finish
1295                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1296                 pthread_join(mesh->thread, NULL);
1297                 pthread_mutex_lock(&(mesh->mesh_mutex));
1298
1299                 mesh->threadstarted = false;
1300         }
1301
1302         // Close all metaconnections
1303         if(mesh->connections) {
1304                 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1305                         next = node->next;
1306                         connection_t *c = node->data;
1307                         c->outgoing = NULL;
1308                         terminate_connection(mesh, c, false);
1309                 }
1310         }
1311
1312         if(mesh->outgoings) {
1313                 list_delete_list(mesh->outgoings);
1314                 mesh->outgoings = NULL;
1315         }
1316
1317         pthread_mutex_unlock(&(mesh->mesh_mutex));
1318 }
1319
1320 void meshlink_close(meshlink_handle_t *mesh) {
1321         if(!mesh || !mesh->confbase) {
1322                 meshlink_errno = MESHLINK_EINVAL;
1323                 return;
1324         }
1325
1326         // stop can be called even if mesh has not been started
1327         meshlink_stop(mesh);
1328
1329         // lock is not released after this
1330         pthread_mutex_lock(&(mesh->mesh_mutex));
1331
1332         // Close and free all resources used.
1333
1334         close_network_connections(mesh);
1335
1336         logger(mesh, MESHLINK_INFO, "Terminating");
1337
1338         exit_configuration(&mesh->config);
1339         event_loop_exit(&mesh->loop);
1340
1341 #ifdef HAVE_MINGW
1342
1343         if(mesh->confbase) {
1344                 WSACleanup();
1345         }
1346
1347 #endif
1348
1349         ecdsa_free(mesh->invitation_key);
1350
1351         free(mesh->name);
1352         free(mesh->appname);
1353         free(mesh->confbase);
1354         pthread_mutex_destroy(&(mesh->mesh_mutex));
1355
1356         if(mesh->conffile) {
1357                 fclose(mesh->conffile);
1358         }
1359
1360         memset(mesh, 0, sizeof(*mesh));
1361
1362         free(mesh);
1363 }
1364
1365 bool meshlink_destroy(const char *confbase) {
1366         if(!confbase) {
1367                 meshlink_errno = MESHLINK_EINVAL;
1368                 return false;
1369         }
1370
1371         char filename[PATH_MAX];
1372         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", confbase);
1373
1374         if(unlink(filename)) {
1375                 if(errno == ENOENT) {
1376                         meshlink_errno = MESHLINK_ENOENT;
1377                         return false;
1378                 } else {
1379                         logger(NULL, MESHLINK_ERROR, "Cannot delete %s: %s\n", filename, strerror(errno));
1380                         meshlink_errno = MESHLINK_ESTORAGE;
1381                         return false;
1382                 }
1383         }
1384
1385         deltree(confbase);
1386
1387         return true;
1388 }
1389
1390 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1391         if(!mesh) {
1392                 meshlink_errno = MESHLINK_EINVAL;
1393                 return;
1394         }
1395
1396         pthread_mutex_lock(&(mesh->mesh_mutex));
1397         mesh->receive_cb = cb;
1398         pthread_mutex_unlock(&(mesh->mesh_mutex));
1399 }
1400
1401 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1402         if(!mesh) {
1403                 meshlink_errno = MESHLINK_EINVAL;
1404                 return;
1405         }
1406
1407         pthread_mutex_lock(&(mesh->mesh_mutex));
1408         mesh->node_status_cb = cb;
1409         pthread_mutex_unlock(&(mesh->mesh_mutex));
1410 }
1411
1412 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1413         if(!mesh) {
1414                 meshlink_errno = MESHLINK_EINVAL;
1415                 return;
1416         }
1417
1418         pthread_mutex_lock(&(mesh->mesh_mutex));
1419         mesh->node_duplicate_cb = cb;
1420         pthread_mutex_unlock(&(mesh->mesh_mutex));
1421 }
1422
1423 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1424         if(mesh) {
1425                 pthread_mutex_lock(&(mesh->mesh_mutex));
1426                 mesh->log_cb = cb;
1427                 mesh->log_level = cb ? level : 0;
1428                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1429         } else {
1430                 global_log_cb = cb;
1431                 global_log_level = cb ? level : 0;
1432         }
1433 }
1434
1435 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1436         meshlink_packethdr_t *hdr;
1437
1438         // Validate arguments
1439         if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1440                 meshlink_errno = MESHLINK_EINVAL;
1441                 return false;
1442         }
1443
1444         if(!len) {
1445                 return true;
1446         }
1447
1448         if(!data) {
1449                 meshlink_errno = MESHLINK_EINVAL;
1450                 return false;
1451         }
1452
1453         // Prepare the packet
1454         vpn_packet_t *packet = malloc(sizeof(*packet));
1455
1456         if(!packet) {
1457                 meshlink_errno = MESHLINK_ENOMEM;
1458                 return false;
1459         }
1460
1461         packet->probe = false;
1462         packet->tcp = false;
1463         packet->len = len + sizeof(*hdr);
1464
1465         hdr = (meshlink_packethdr_t *)packet->data;
1466         memset(hdr, 0, sizeof(*hdr));
1467         // leave the last byte as 0 to make sure strings are always
1468         // null-terminated if they are longer than the buffer
1469         strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1470         strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1471
1472         memcpy(packet->data + sizeof(*hdr), data, len);
1473
1474         // Queue it
1475         if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1476                 free(packet);
1477                 meshlink_errno = MESHLINK_ENOMEM;
1478                 return false;
1479         }
1480
1481         // Notify event loop
1482         signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1483
1484         return true;
1485 }
1486
1487 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1488         (void)loop;
1489         vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1490
1491         if(!packet) {
1492                 return;
1493         }
1494
1495         mesh->self->in_packets++;
1496         mesh->self->in_bytes += packet->len;
1497         route(mesh, mesh->self, packet);
1498 }
1499
1500 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1501         if(!mesh || !destination) {
1502                 meshlink_errno = MESHLINK_EINVAL;
1503                 return -1;
1504         }
1505
1506         pthread_mutex_lock(&(mesh->mesh_mutex));
1507
1508         node_t *n = (node_t *)destination;
1509
1510         if(!n->status.reachable) {
1511                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1512                 return 0;
1513
1514         } else if(n->mtuprobes > 30 && n->minmtu) {
1515                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1516                 return n->minmtu;
1517         } else {
1518                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1519                 return MTU;
1520         }
1521 }
1522
1523 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1524         if(!mesh || !node) {
1525                 meshlink_errno = MESHLINK_EINVAL;
1526                 return NULL;
1527         }
1528
1529         pthread_mutex_lock(&(mesh->mesh_mutex));
1530
1531         node_t *n = (node_t *)node;
1532
1533         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1534                 meshlink_errno = MESHLINK_EINTERNAL;
1535                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1536                 return false;
1537         }
1538
1539         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1540
1541         if(!fingerprint) {
1542                 meshlink_errno = MESHLINK_EINTERNAL;
1543         }
1544
1545         pthread_mutex_unlock(&(mesh->mesh_mutex));
1546         return fingerprint;
1547 }
1548
1549 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1550         if(!mesh) {
1551                 meshlink_errno = MESHLINK_EINVAL;
1552                 return NULL;
1553         }
1554
1555         return (meshlink_node_t *)mesh->self;
1556 }
1557
1558 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1559         if(!mesh || !name) {
1560                 meshlink_errno = MESHLINK_EINVAL;
1561                 return NULL;
1562         }
1563
1564         meshlink_node_t *node = NULL;
1565
1566         pthread_mutex_lock(&(mesh->mesh_mutex));
1567         node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1568         pthread_mutex_unlock(&(mesh->mesh_mutex));
1569         return node;
1570 }
1571
1572 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1573         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1574                 meshlink_errno = MESHLINK_EINVAL;
1575                 return NULL;
1576         }
1577
1578         meshlink_node_t **result;
1579
1580         //lock mesh->nodes
1581         pthread_mutex_lock(&(mesh->mesh_mutex));
1582
1583         *nmemb = mesh->nodes->count;
1584         result = realloc(nodes, *nmemb * sizeof(*nodes));
1585
1586         if(result) {
1587                 meshlink_node_t **p = result;
1588
1589                 for splay_each(node_t, n, mesh->nodes) {
1590                         *p++ = (meshlink_node_t *)n;
1591                 }
1592         } else {
1593                 *nmemb = 0;
1594                 free(nodes);
1595                 meshlink_errno = MESHLINK_ENOMEM;
1596         }
1597
1598         pthread_mutex_unlock(&(mesh->mesh_mutex));
1599
1600         return result;
1601 }
1602
1603 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1604         if(!mesh || !data || !len || !signature || !siglen) {
1605                 meshlink_errno = MESHLINK_EINVAL;
1606                 return false;
1607         }
1608
1609         if(*siglen < MESHLINK_SIGLEN) {
1610                 meshlink_errno = MESHLINK_EINVAL;
1611                 return false;
1612         }
1613
1614         pthread_mutex_lock(&(mesh->mesh_mutex));
1615
1616         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1617                 meshlink_errno = MESHLINK_EINTERNAL;
1618                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1619                 return false;
1620         }
1621
1622         *siglen = MESHLINK_SIGLEN;
1623         pthread_mutex_unlock(&(mesh->mesh_mutex));
1624         return true;
1625 }
1626
1627 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1628         if(!mesh || !data || !len || !signature) {
1629                 meshlink_errno = MESHLINK_EINVAL;
1630                 return false;
1631         }
1632
1633         if(siglen != MESHLINK_SIGLEN) {
1634                 meshlink_errno = MESHLINK_EINVAL;
1635                 return false;
1636         }
1637
1638         pthread_mutex_lock(&(mesh->mesh_mutex));
1639
1640         bool rval = false;
1641
1642         struct node_t *n = (struct node_t *)source;
1643         node_read_ecdsa_public_key(mesh, n);
1644
1645         if(!n->ecdsa) {
1646                 meshlink_errno = MESHLINK_EINTERNAL;
1647                 rval = false;
1648         } else {
1649                 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1650         }
1651
1652         pthread_mutex_unlock(&(mesh->mesh_mutex));
1653         return rval;
1654 }
1655
1656 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1657         char filename[PATH_MAX];
1658
1659         pthread_mutex_lock(&(mesh->mesh_mutex));
1660
1661         snprintf(filename, sizeof(filename), "%s" SLASH "invitations", mesh->confbase);
1662
1663         if(mkdir(filename, 0700) && errno != EEXIST) {
1664                 logger(mesh, MESHLINK_DEBUG, "Could not create directory %s: %s\n", filename, strerror(errno));
1665                 meshlink_errno = MESHLINK_ESTORAGE;
1666                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1667                 return false;
1668         }
1669
1670         // Count the number of valid invitations, clean up old ones
1671         DIR *dir = opendir(filename);
1672
1673         if(!dir) {
1674                 logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
1675                 meshlink_errno = MESHLINK_ESTORAGE;
1676                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1677                 return false;
1678         }
1679
1680         errno = 0;
1681         int count = 0;
1682         struct dirent *ent;
1683         time_t deadline = time(NULL) - 604800; // 1 week in the past
1684
1685         while((ent = readdir(dir))) {
1686                 if(strlen(ent->d_name) != 24) {
1687                         continue;
1688                 }
1689
1690                 char invname[PATH_MAX];
1691                 struct stat st;
1692
1693                 if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
1694                         logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
1695                         continue;
1696                 }
1697
1698                 if(!stat(invname, &st)) {
1699                         if(mesh->invitation_key && deadline < st.st_mtime) {
1700                                 count++;
1701                         } else {
1702                                 unlink(invname);
1703                         }
1704                 } else {
1705                         logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
1706                         errno = 0;
1707                 }
1708         }
1709
1710         if(errno) {
1711                 logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
1712                 closedir(dir);
1713                 meshlink_errno = MESHLINK_ESTORAGE;
1714                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1715                 return false;
1716         }
1717
1718         closedir(dir);
1719
1720         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1721
1722         // Remove the key if there are no outstanding invitations.
1723         if(!count) {
1724                 unlink(filename);
1725
1726                 if(mesh->invitation_key) {
1727                         ecdsa_free(mesh->invitation_key);
1728                         mesh->invitation_key = NULL;
1729                 }
1730         }
1731
1732         if(mesh->invitation_key) {
1733                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1734                 return true;
1735         }
1736
1737         // Create a new key if necessary.
1738         FILE *f = fopen(filename, "rb");
1739
1740         if(!f) {
1741                 if(errno != ENOENT) {
1742                         logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
1743                         meshlink_errno = MESHLINK_ESTORAGE;
1744                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1745                         return false;
1746                 }
1747
1748                 mesh->invitation_key = ecdsa_generate();
1749
1750                 if(!mesh->invitation_key) {
1751                         logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
1752                         meshlink_errno = MESHLINK_EINTERNAL;
1753                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1754                         return false;
1755                 }
1756
1757                 f = fopen(filename, "wb");
1758
1759                 if(!f) {
1760                         logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
1761                         meshlink_errno = MESHLINK_ESTORAGE;
1762                         pthread_mutex_unlock(&(mesh->mesh_mutex));
1763                         return false;
1764                 }
1765
1766                 chmod(filename, 0600);
1767                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1768                 fclose(f);
1769         } else {
1770                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1771                 fclose(f);
1772
1773                 if(!mesh->invitation_key) {
1774                         logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
1775                         meshlink_errno = MESHLINK_ESTORAGE;
1776                 }
1777         }
1778
1779         pthread_mutex_unlock(&(mesh->mesh_mutex));
1780         return mesh->invitation_key;
1781 }
1782
1783 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1784         if(!mesh || !node || !address) {
1785                 meshlink_errno = MESHLINK_EINVAL;
1786                 return false;
1787         }
1788
1789         if(!is_valid_hostname(address)) {
1790                 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1791                 meshlink_errno = MESHLINK_EINVAL;
1792                 return false;
1793         }
1794
1795         if(port && !is_valid_port(port)) {
1796                 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1797                 meshlink_errno = MESHLINK_EINVAL;
1798                 return false;
1799         }
1800
1801         char *canonical_address;
1802
1803         if(port) {
1804                 xasprintf(&canonical_address, "%s %s", address, port);
1805         } else {
1806                 canonical_address = xstrdup(address);
1807         }
1808
1809         pthread_mutex_lock(&(mesh->mesh_mutex));
1810         bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
1811         pthread_mutex_unlock(&(mesh->mesh_mutex));
1812
1813         free(canonical_address);
1814         return rval;
1815 }
1816
1817 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1818         return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1819 }
1820
1821 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1822         if(!mesh) {
1823                 meshlink_errno = MESHLINK_EINVAL;
1824                 return false;
1825         }
1826
1827         char *address = meshlink_get_external_address(mesh);
1828
1829         if(!address) {
1830                 return false;
1831         }
1832
1833         bool rval = false;
1834
1835         pthread_mutex_lock(&(mesh->mesh_mutex));
1836         rval = append_config_file(mesh, mesh->self->name, "Address", address);
1837         pthread_mutex_unlock(&(mesh->mesh_mutex));
1838
1839         free(address);
1840         return rval;
1841 }
1842
1843 int meshlink_get_port(meshlink_handle_t *mesh) {
1844         if(!mesh) {
1845                 meshlink_errno = MESHLINK_EINVAL;
1846                 return -1;
1847         }
1848
1849         if(!mesh->myport) {
1850                 meshlink_errno = MESHLINK_EINTERNAL;
1851                 return -1;
1852         }
1853
1854         return atoi(mesh->myport);
1855 }
1856
1857 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1858         if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1859                 meshlink_errno = MESHLINK_EINVAL;
1860                 return false;
1861         }
1862
1863         if(mesh->myport && port == atoi(mesh->myport)) {
1864                 return true;
1865         }
1866
1867         if(!try_bind(port)) {
1868                 meshlink_errno = MESHLINK_ENETWORK;
1869                 return false;
1870         }
1871
1872         bool rval = false;
1873
1874         pthread_mutex_lock(&(mesh->mesh_mutex));
1875
1876         if(mesh->threadstarted) {
1877                 meshlink_errno = MESHLINK_EINVAL;
1878                 goto done;
1879         }
1880
1881         close_network_connections(mesh);
1882         exit_configuration(&mesh->config);
1883
1884         char portstr[10];
1885         snprintf(portstr, sizeof(portstr), "%d", port);
1886         portstr[sizeof(portstr) - 1] = 0;
1887
1888         modify_config_file(mesh, mesh->name, "Port", portstr, true);
1889
1890         init_configuration(&mesh->config);
1891
1892         if(!read_server_config(mesh)) {
1893                 meshlink_errno = MESHLINK_ESTORAGE;
1894         } else if(!setup_network(mesh)) {
1895                 meshlink_errno = MESHLINK_ENETWORK;
1896         } else {
1897                 rval = true;
1898         }
1899
1900 done:
1901         pthread_mutex_unlock(&(mesh->mesh_mutex));
1902
1903         return rval;
1904 }
1905
1906 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1907         mesh->invitation_timeout = timeout;
1908 }
1909
1910 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1911         if(!mesh) {
1912                 meshlink_errno = MESHLINK_EINVAL;
1913                 return NULL;
1914         }
1915
1916         pthread_mutex_lock(&(mesh->mesh_mutex));
1917
1918         // Check validity of the new node's name
1919         if(!check_id(name)) {
1920                 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1921                 meshlink_errno = MESHLINK_EINVAL;
1922                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1923                 return NULL;
1924         }
1925
1926         // Ensure no host configuration file with that name exists
1927         char filename[PATH_MAX];
1928         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1929
1930         if(!access(filename, F_OK)) {
1931                 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1932                 meshlink_errno = MESHLINK_EEXIST;
1933                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1934                 return NULL;
1935         }
1936
1937         // Ensure no other nodes know about this name
1938         if(meshlink_get_node(mesh, name)) {
1939                 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1940                 meshlink_errno = MESHLINK_EEXIST;
1941                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1942                 return NULL;
1943         }
1944
1945         // Get the local address
1946         char *address = get_my_hostname(mesh);
1947
1948         if(!address) {
1949                 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1950                 meshlink_errno = MESHLINK_ERESOLV;
1951                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1952                 return NULL;
1953         }
1954
1955         if(!refresh_invitation_key(mesh)) {
1956                 meshlink_errno = MESHLINK_EINTERNAL;
1957                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1958                 return NULL;
1959         }
1960
1961         char hash[64];
1962
1963         // Create a hash of the key.
1964         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1965         sha512(fingerprint, strlen(fingerprint), hash);
1966         b64encode_urlsafe(hash, hash, 18);
1967
1968         // Create a random cookie for this invitation.
1969         char cookie[25];
1970         randomize(cookie, 18);
1971
1972         // Create a filename that doesn't reveal the cookie itself
1973         char buf[18 + strlen(fingerprint)];
1974         char cookiehash[64];
1975         memcpy(buf, cookie, 18);
1976         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1977         sha512(buf, sizeof(buf), cookiehash);
1978         b64encode_urlsafe(cookiehash, cookiehash, 18);
1979
1980         b64encode_urlsafe(cookie, cookie, 18);
1981
1982         free(fingerprint);
1983
1984         // Create a file containing the details of the invitation.
1985         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1986         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1987
1988         if(!ifd) {
1989                 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1990                 meshlink_errno = MESHLINK_ESTORAGE;
1991                 pthread_mutex_unlock(&(mesh->mesh_mutex));
1992                 return NULL;
1993         }
1994
1995         FILE *f = fdopen(ifd, "w");
1996
1997         if(!f) {
1998                 abort();
1999         }
2000
2001         // Fill in the details.
2002         fprintf(f, "Name = %s\n", name);
2003         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
2004
2005         // Copy Broadcast and Mode
2006         snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
2007         FILE *tc = fopen(filename,  "r");
2008
2009         if(tc) {
2010                 char buf[1024];
2011
2012                 while(fgets(buf, sizeof(buf), tc)) {
2013                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
2014                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
2015                                 fputs(buf, f);
2016
2017                                 // Make sure there is a newline character.
2018                                 if(!strchr(buf, '\n')) {
2019                                         fputc('\n', f);
2020                                 }
2021                         }
2022                 }
2023
2024                 fclose(tc);
2025         } else {
2026                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2027                 meshlink_errno = MESHLINK_ESTORAGE;
2028                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2029                 return NULL;
2030         }
2031
2032         fprintf(f, "#---------------------------------------------------------------#\n");
2033         fprintf(f, "Name = %s\n", mesh->self->name);
2034
2035         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2036         fcopy(f, filename);
2037         fclose(f);
2038
2039         // Create an URL from the local address, key hash and cookie
2040         char *url;
2041         xasprintf(&url, "%s/%s%s", address, hash, cookie);
2042         free(address);
2043
2044         pthread_mutex_unlock(&(mesh->mesh_mutex));
2045         return url;
2046 }
2047
2048 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2049         if(!mesh || !invitation) {
2050                 meshlink_errno = MESHLINK_EINVAL;
2051                 return false;
2052         }
2053
2054         pthread_mutex_lock(&(mesh->mesh_mutex));
2055
2056         //Before doing meshlink_join make sure we are not connected to another mesh
2057         if(mesh->threadstarted) {
2058                 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2059                 meshlink_errno = MESHLINK_EINVAL;
2060                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061                 return false;
2062         }
2063
2064         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2065         char copy[strlen(invitation) + 1];
2066         strcpy(copy, invitation);
2067
2068         // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2069
2070         char *slash = strchr(copy, '/');
2071
2072         if(!slash) {
2073                 goto invalid;
2074         }
2075
2076         *slash++ = 0;
2077
2078         if(strlen(slash) != 48) {
2079                 goto invalid;
2080         }
2081
2082         char *address = copy;
2083         char *port = NULL;
2084
2085         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2086                 goto invalid;
2087         }
2088
2089         // Generate a throw-away key for the invitation.
2090         ecdsa_t *key = ecdsa_generate();
2091
2092         if(!key) {
2093                 meshlink_errno = MESHLINK_EINTERNAL;
2094                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2095                 return false;
2096         }
2097
2098         char *b64key = ecdsa_get_base64_public_key(key);
2099         char *comma;
2100         mesh->sock = -1;
2101
2102         while(address && *address) {
2103                 // We allow commas in the address part to support multiple addresses in one invitation URL.
2104                 comma = strchr(address, ',');
2105
2106                 if(comma) {
2107                         *comma++ = 0;
2108                 }
2109
2110                 // Split of the port
2111                 port = strrchr(address, ':');
2112
2113                 if(!port) {
2114                         goto invalid;
2115                 }
2116
2117                 *port++ = 0;
2118
2119                 // IPv6 address are enclosed in brackets, per RFC 3986
2120                 if(*address == '[') {
2121                         address++;
2122                         char *bracket = strchr(address, ']');
2123
2124                         if(!bracket) {
2125                                 goto invalid;
2126                         }
2127
2128                         *bracket++ = 0;
2129
2130                         if(*bracket) {
2131                                 goto invalid;
2132                         }
2133                 }
2134
2135                 // Connect to the meshlink daemon mentioned in the URL.
2136                 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2137
2138                 if(ai) {
2139                         for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2140                                 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
2141
2142                                 if(mesh->sock == -1) {
2143                                         logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2144                                         meshlink_errno = MESHLINK_ENETWORK;
2145                                         continue;
2146                                 }
2147
2148                                 set_timeout(mesh->sock, 5000);
2149
2150                                 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2151                                         logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2152                                         meshlink_errno = MESHLINK_ENETWORK;
2153                                         closesocket(mesh->sock);
2154                                         mesh->sock = -1;
2155                                         continue;
2156                                 }
2157                         }
2158
2159                         freeaddrinfo(ai);
2160                 } else {
2161                         meshlink_errno = MESHLINK_ERESOLV;
2162                 }
2163
2164                 if(mesh->sock != -1 || !comma) {
2165                         break;
2166                 }
2167
2168                 address = comma;
2169         }
2170
2171         if(mesh->sock == -1) {
2172                 pthread_mutex_unlock(&mesh->mesh_mutex);
2173                 return false;
2174         }
2175
2176         logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2177
2178         // Tell him we have an invitation, and give him our throw-away key.
2179
2180         mesh->blen = 0;
2181
2182         if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2183                 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2184                 closesocket(mesh->sock);
2185                 meshlink_errno = MESHLINK_ENETWORK;
2186                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2187                 return false;
2188         }
2189
2190         free(b64key);
2191
2192         char hisname[4096] = "";
2193         int code, hismajor, hisminor = 0;
2194
2195         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) {
2196                 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2197                 closesocket(mesh->sock);
2198                 meshlink_errno = MESHLINK_ENETWORK;
2199                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2200                 return false;
2201         }
2202
2203         // Check if the hash of the key he gave us matches the hash in the URL.
2204         char *fingerprint = mesh->line + 2;
2205         char hishash[64];
2206
2207         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2208                 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2209                 meshlink_errno = MESHLINK_EINTERNAL;
2210                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2211                 return false;
2212         }
2213
2214         if(memcmp(hishash, mesh->hash, 18)) {
2215                 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2216                 meshlink_errno = MESHLINK_EPEER;
2217                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2218                 return false;
2219
2220         }
2221
2222         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2223
2224         if(!hiskey) {
2225                 meshlink_errno = MESHLINK_EINTERNAL;
2226                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2227                 return false;
2228         }
2229
2230         // Start an SPTPS session
2231         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2232                 meshlink_errno = MESHLINK_EINTERNAL;
2233                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2234                 return false;
2235         }
2236
2237         // Feed rest of input buffer to SPTPS
2238         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2239                 meshlink_errno = MESHLINK_EPEER;
2240                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2241                 return false;
2242         }
2243
2244         int len;
2245
2246         while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2247                 if(len < 0) {
2248                         if(errno == EINTR) {
2249                                 continue;
2250                         }
2251
2252                         logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2253                         meshlink_errno = MESHLINK_ENETWORK;
2254                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2255                         return false;
2256                 }
2257
2258                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2259                         meshlink_errno = MESHLINK_EPEER;
2260                         pthread_mutex_unlock(&(mesh->mesh_mutex));
2261                         return false;
2262                 }
2263         }
2264
2265         sptps_stop(&mesh->sptps);
2266         ecdsa_free(hiskey);
2267         ecdsa_free(key);
2268         closesocket(mesh->sock);
2269
2270         if(!mesh->success) {
2271                 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2272                 meshlink_errno = MESHLINK_EPEER;
2273                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2274                 return false;
2275         }
2276
2277         pthread_mutex_unlock(&(mesh->mesh_mutex));
2278         return true;
2279
2280 invalid:
2281         logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2282         meshlink_errno = MESHLINK_EINVAL;
2283         pthread_mutex_unlock(&(mesh->mesh_mutex));
2284         return false;
2285 }
2286
2287 char *meshlink_export(meshlink_handle_t *mesh) {
2288         if(!mesh) {
2289                 meshlink_errno = MESHLINK_EINVAL;
2290                 return NULL;
2291         }
2292
2293         pthread_mutex_lock(&(mesh->mesh_mutex));
2294
2295         char filename[PATH_MAX];
2296         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
2297         FILE *f = fopen(filename, "r");
2298
2299         if(!f) {
2300                 logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
2301                 meshlink_errno = MESHLINK_ESTORAGE;
2302                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2303                 return NULL;
2304         }
2305
2306         fseek(f, 0, SEEK_END);
2307         int fsize = ftell(f);
2308         rewind(f);
2309
2310         size_t len = fsize + 9 + strlen(mesh->self->name);
2311         char *buf = xmalloc(len);
2312         snprintf(buf, len, "Name = %s\n", mesh->self->name);
2313
2314         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
2315                 logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
2316                 fclose(f);
2317                 free(buf);
2318                 meshlink_errno = MESHLINK_ESTORAGE;
2319                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2320                 return NULL;
2321         }
2322
2323         fclose(f);
2324         buf[len - 1] = 0;
2325
2326         pthread_mutex_unlock(&(mesh->mesh_mutex));
2327         return buf;
2328 }
2329
2330 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2331         if(!mesh || !data) {
2332                 meshlink_errno = MESHLINK_EINVAL;
2333                 return false;
2334         }
2335
2336         pthread_mutex_lock(&(mesh->mesh_mutex));
2337
2338         if(strncmp(data, "Name = ", 7)) {
2339                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2340                 meshlink_errno = MESHLINK_EPEER;
2341                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2342                 return false;
2343         }
2344
2345         char *end = strchr(data + 7, '\n');
2346
2347         if(!end) {
2348                 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2349                 meshlink_errno = MESHLINK_EPEER;
2350                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2351                 return false;
2352         }
2353
2354         int len = end - (data + 7);
2355         char name[len + 1];
2356         memcpy(name, data + 7, len);
2357         name[len] = 0;
2358
2359         if(!check_id(name)) {
2360                 logger(mesh, MESHLINK_DEBUG, "Invalid Name\n");
2361                 meshlink_errno = MESHLINK_EPEER;
2362                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2363                 return false;
2364         }
2365
2366         char filename[PATH_MAX];
2367         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
2368
2369         if(!access(filename, F_OK)) {
2370                 logger(mesh, MESHLINK_DEBUG, "File %s already exists, not importing\n", filename);
2371                 meshlink_errno = MESHLINK_EEXIST;
2372                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2373                 return false;
2374         }
2375
2376         if(errno != ENOENT) {
2377                 logger(mesh, MESHLINK_DEBUG, "Error accessing %s: %s\n", filename, strerror(errno));
2378                 meshlink_errno = MESHLINK_ESTORAGE;
2379                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2380                 return false;
2381         }
2382
2383         FILE *f = fopen(filename, "w");
2384
2385         if(!f) {
2386                 logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
2387                 meshlink_errno = MESHLINK_ESTORAGE;
2388                 pthread_mutex_unlock(&(mesh->mesh_mutex));
2389                 return false;
2390         }
2391
2392         fwrite(end + 1, strlen(end + 1), 1, f);
2393         fclose(f);
2394
2395         load_all_nodes(mesh);
2396
2397         pthread_mutex_unlock(&(mesh->mesh_mutex));
2398         return true;
2399 }
2400
2401 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2402         if(!mesh || !node) {
2403                 meshlink_errno = MESHLINK_EINVAL;
2404                 return;
2405         }
2406
2407         pthread_mutex_lock(&(mesh->mesh_mutex));
2408
2409         node_t *n;
2410         n = (node_t *)node;
2411         n->status.blacklisted = true;
2412         logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2413
2414         //Make blacklisting persistent in the config file
2415         append_config_file(mesh, n->name, "blacklisted", "yes");
2416
2417         //Immediately terminate any connections we have with the blacklisted node
2418         for list_each(connection_t, c, mesh->connections) {
2419                 if(c->node == n) {
2420                         terminate_connection(mesh, c, c->status.active);
2421                 }
2422         }
2423
2424         pthread_mutex_unlock(&(mesh->mesh_mutex));
2425 }
2426
2427 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2428         if(!mesh || !node) {
2429                 meshlink_errno = MESHLINK_EINVAL;
2430                 return;
2431         }
2432
2433         pthread_mutex_lock(&(mesh->mesh_mutex));
2434
2435         node_t *n = (node_t *)node;
2436         n->status.blacklisted = false;
2437
2438         //TODO: remove blacklisted = yes from the config file
2439
2440         pthread_mutex_unlock(&(mesh->mesh_mutex));
2441         return;
2442 }
2443
2444 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2445         mesh->default_blacklist = blacklist;
2446 }
2447
2448 /* Hint that a hostname may be found at an address
2449  * See header file for detailed comment.
2450  */
2451 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2452         if(!mesh || !node || !addr) {
2453                 return;
2454         }
2455
2456         // Ignore hints about ourself.
2457         if((node_t *)node == mesh->self) {
2458                 return;
2459         }
2460
2461         pthread_mutex_lock(&(mesh->mesh_mutex));
2462
2463         char *host = NULL, *port = NULL, *str = NULL;
2464         sockaddr2str((const sockaddr_t *)addr, &host, &port);
2465
2466         if(host && port) {
2467                 xasprintf(&str, "%s %s", host, port);
2468
2469                 if((strncmp("fe80", host, 4) != 0) && (strncmp("127.", host, 4) != 0) && (strcmp("localhost", host) != 0)) {
2470                         modify_config_file(mesh, node->name, "Address", str, 5);
2471                 } else {
2472                         logger(mesh, MESHLINK_DEBUG, "Not adding Link Local IPv6 Address to config\n");
2473                 }
2474         }
2475
2476         free(str);
2477         free(host);
2478         free(port);
2479
2480         pthread_mutex_unlock(&(mesh->mesh_mutex));
2481         // @TODO do we want to fire off a connection attempt right away?
2482 }
2483
2484 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2485         (void)port;
2486         node_t *n = utcp->priv;
2487         meshlink_handle_t *mesh = n->mesh;
2488         return mesh->channel_accept_cb;
2489 }
2490
2491 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2492         meshlink_channel_t *channel = connection->priv;
2493
2494         if(!channel) {
2495                 abort();
2496         }
2497
2498         node_t *n = channel->node;
2499         meshlink_handle_t *mesh = n->mesh;
2500
2501         if(n->status.destroyed) {
2502                 meshlink_channel_close(mesh, channel);
2503         } else if(channel->receive_cb) {
2504                 channel->receive_cb(mesh, channel, data, len);
2505         }
2506
2507         return len;
2508 }
2509
2510 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2511         node_t *n = utcp_connection->utcp->priv;
2512
2513         if(!n) {
2514                 abort();
2515         }
2516
2517         meshlink_handle_t *mesh = n->mesh;
2518
2519         if(!mesh->channel_accept_cb) {
2520                 return;
2521         }
2522
2523         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2524         channel->node = n;
2525         channel->c = utcp_connection;
2526
2527         if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2528                 utcp_accept(utcp_connection, channel_recv, channel);
2529         } else {
2530                 free(channel);
2531         }
2532 }
2533
2534 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2535         node_t *n = utcp->priv;
2536
2537         if(n->status.destroyed) {
2538                 return -1;
2539         }
2540
2541         meshlink_handle_t *mesh = n->mesh;
2542         return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2543 }
2544
2545 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2546         if(!mesh || !channel) {
2547                 meshlink_errno = MESHLINK_EINVAL;
2548                 return;
2549         }
2550
2551         channel->receive_cb = cb;
2552 }
2553
2554 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2555         (void)mesh;
2556         node_t *n = (node_t *)source;
2557
2558         if(!n->utcp) {
2559                 abort();
2560         }
2561
2562         utcp_recv(n->utcp, data, len);
2563 }
2564
2565 static void channel_poll(struct utcp_connection *connection, size_t len) {
2566         meshlink_channel_t *channel = connection->priv;
2567
2568         if(!channel) {
2569                 abort();
2570         }
2571
2572         node_t *n = channel->node;
2573         meshlink_handle_t *mesh = n->mesh;
2574
2575         if(channel->poll_cb) {
2576                 channel->poll_cb(mesh, channel, len);
2577         }
2578 }
2579
2580 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2581         (void)mesh;
2582         channel->poll_cb = cb;
2583         utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2584 }
2585
2586 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2587         if(!mesh) {
2588                 meshlink_errno = MESHLINK_EINVAL;
2589                 return;
2590         }
2591
2592         pthread_mutex_lock(&mesh->mesh_mutex);
2593         mesh->channel_accept_cb = cb;
2594         mesh->receive_cb = channel_receive;
2595
2596         for splay_each(node_t, n, mesh->nodes) {
2597                 if(!n->utcp && n != mesh->self) {
2598                         n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2599                 }
2600         }
2601
2602         pthread_mutex_unlock(&mesh->mesh_mutex);
2603 }
2604
2605 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) {
2606         if(data || len) {
2607                 abort();        // TODO: handle non-NULL data
2608         }
2609
2610         if(!mesh || !node) {
2611                 meshlink_errno = MESHLINK_EINVAL;
2612                 return NULL;
2613         }
2614
2615         node_t *n = (node_t *)node;
2616
2617         if(!n->utcp) {
2618                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2619                 mesh->receive_cb = channel_receive;
2620
2621                 if(!n->utcp) {
2622                         meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2623                         return NULL;
2624                 }
2625         }
2626
2627         meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2628         channel->node = n;
2629         channel->receive_cb = cb;
2630         channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2631
2632         if(!channel->c) {
2633                 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2634                 free(channel);
2635                 return NULL;
2636         }
2637
2638         return channel;
2639 }
2640
2641 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) {
2642         return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2643 }
2644
2645 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2646         if(!mesh || !channel) {
2647                 meshlink_errno = MESHLINK_EINVAL;
2648                 return;
2649         }
2650
2651         utcp_shutdown(channel->c, direction);
2652 }
2653
2654 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2655         if(!mesh || !channel) {
2656                 meshlink_errno = MESHLINK_EINVAL;
2657                 return;
2658         }
2659
2660         utcp_close(channel->c);
2661         free(channel);
2662 }
2663
2664 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2665         if(!mesh || !channel) {
2666                 meshlink_errno = MESHLINK_EINVAL;
2667                 return -1;
2668         }
2669
2670         if(!len) {
2671                 return 0;
2672         }
2673
2674         if(!data) {
2675                 meshlink_errno = MESHLINK_EINVAL;
2676                 return -1;
2677         }
2678
2679         // TODO: more finegrained locking.
2680         // Ideally we want to put the data into the UTCP connection's send buffer.
2681         // Then, preferrably only if there is room in the receiver window,
2682         // kick the meshlink thread to go send packets.
2683
2684         pthread_mutex_lock(&mesh->mesh_mutex);
2685         ssize_t retval = utcp_send(channel->c, data, len);
2686         pthread_mutex_unlock(&mesh->mesh_mutex);
2687
2688         if(retval < 0) {
2689                 meshlink_errno = MESHLINK_ENETWORK;
2690         }
2691
2692         return retval;
2693 }
2694
2695 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2696         if(!mesh || !channel) {
2697                 meshlink_errno = MESHLINK_EINVAL;
2698                 return -1;
2699         }
2700
2701         return channel->c->flags;
2702 }
2703
2704 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2705         if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2706                 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2707         }
2708
2709         if(mesh->node_status_cb) {
2710                 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2711         }
2712 }
2713
2714 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2715         if(!mesh->node_duplicate_cb || n->status.duplicate) {
2716                 return;
2717         }
2718
2719         n->status.duplicate = true;
2720         mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2721 }
2722
2723 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2724 #if HAVE_CATTA
2725
2726         if(!mesh) {
2727                 meshlink_errno = MESHLINK_EINVAL;
2728                 return;
2729         }
2730
2731         pthread_mutex_lock(&mesh->mesh_mutex);
2732
2733         if(mesh->discovery == enable) {
2734                 goto end;
2735         }
2736
2737         if(mesh->threadstarted) {
2738                 if(enable) {
2739                         discovery_start(mesh);
2740                 } else {
2741                         discovery_stop(mesh);
2742                 }
2743         }
2744
2745         mesh->discovery = enable;
2746
2747 end:
2748         pthread_mutex_unlock(&mesh->mesh_mutex);
2749 #else
2750         (void)mesh;
2751         (void)enable;
2752         meshlink_errno = MESHLINK_ENOTSUP;
2753 #endif
2754 }
2755
2756 static void __attribute__((constructor)) meshlink_init(void) {
2757         crypto_init();
2758         unsigned int seed;
2759         randomize(&seed, sizeof(seed));
2760         srand(seed);
2761 }
2762
2763 static void __attribute__((destructor)) meshlink_exit(void) {
2764         crypto_exit();
2765 }
2766
2767 /// Device class traits
2768 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2769         { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2770         { .min_connects = 3, .max_connects = 100, .edge_weight = 3 },   // DEV_CLASS_STATIONARY
2771         { .min_connects = 3, .max_connects = 3, .edge_weight = 6 },             // DEV_CLASS_PORTABLE
2772         { .min_connects = 1, .max_connects = 1, .edge_weight = 9 },             // DEV_CLASS_UNKNOWN
2773 };