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