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