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