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