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