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