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