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