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