]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Merge remote-tracking branch 'origin/everbase' into discovery
[meshlink] / src / meshlink.c
1 /*
2     meshlink.c -- Implementation of the MeshLink API.
3     Copyright (C) 2014 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 typedef struct {
25         const char *name;
26         int type;
27 } var_t;
28
29 #include "system.h"
30 #include <pthread.h>
31
32 #include "crypto.h"
33 #include "ecdsagen.h"
34 #include "meshlink_internal.h"
35 #include "netutl.h"
36 #include "node.h"
37 #include "protocol.h"
38 #include "route.h"
39 #include "utils.h"
40 #include "xalloc.h"
41 #include "ed25519/sha512.h"
42 #include "discovery.h"
43
44 #ifndef MSG_NOSIGNAL
45 #define MSG_NOSIGNAL 0
46 #endif
47
48 __thread meshlink_errno_t meshlink_errno;
49
50 //TODO: this can go away completely
51 const var_t variables[] = {
52         /* Server configuration */
53         {"AddressFamily", VAR_SERVER},
54         {"AutoConnect", VAR_SERVER | VAR_SAFE},
55         {"BindToAddress", VAR_SERVER | VAR_MULTIPLE},
56         {"BindToInterface", VAR_SERVER},
57         {"Broadcast", VAR_SERVER | VAR_SAFE},
58         {"ConnectTo", VAR_SERVER | VAR_MULTIPLE | VAR_SAFE},
59         {"DecrementTTL", VAR_SERVER},
60         {"Device", VAR_SERVER},
61         {"DeviceType", VAR_SERVER},
62         {"DirectOnly", VAR_SERVER},
63         {"ECDSAPrivateKeyFile", VAR_SERVER},
64         {"ExperimentalProtocol", VAR_SERVER},
65         {"Forwarding", VAR_SERVER},
66         {"GraphDumpFile", VAR_SERVER | VAR_OBSOLETE},
67         {"Hostnames", VAR_SERVER},
68         {"IffOneQueue", VAR_SERVER},
69         {"Interface", VAR_SERVER},
70         {"KeyExpire", VAR_SERVER},
71         {"ListenAddress", VAR_SERVER | VAR_MULTIPLE},
72         {"LocalDiscovery", VAR_SERVER},
73         {"MACExpire", VAR_SERVER},
74         {"MaxConnectionBurst", VAR_SERVER},
75         {"MaxOutputBufferSize", VAR_SERVER},
76         {"MaxTimeout", VAR_SERVER},
77         {"Mode", VAR_SERVER | VAR_SAFE},
78         {"Name", VAR_SERVER},
79         {"PingInterval", VAR_SERVER},
80         {"PingTimeout", VAR_SERVER},
81         {"PriorityInheritance", VAR_SERVER},
82         {"PrivateKey", VAR_SERVER | VAR_OBSOLETE},
83         {"PrivateKeyFile", VAR_SERVER},
84         {"ProcessPriority", VAR_SERVER},
85         {"Proxy", VAR_SERVER},
86         {"ReplayWindow", VAR_SERVER},
87         {"ScriptsExtension", VAR_SERVER},
88         {"ScriptsInterpreter", VAR_SERVER},
89         {"StrictSubnets", VAR_SERVER},
90         {"TunnelServer", VAR_SERVER},
91         {"VDEGroup", VAR_SERVER},
92         {"VDEPort", VAR_SERVER},
93         /* Host configuration */
94         {"Address", VAR_HOST | VAR_MULTIPLE},
95         {"Cipher", VAR_SERVER | VAR_HOST},
96         {"ClampMSS", VAR_SERVER | VAR_HOST},
97         {"Compression", VAR_SERVER | VAR_HOST},
98         {"Digest", VAR_SERVER | VAR_HOST},
99         {"ECDSAPublicKey", VAR_HOST},
100         {"ECDSAPublicKeyFile", VAR_SERVER | VAR_HOST},
101         {"IndirectData", VAR_SERVER | VAR_HOST},
102         {"MACLength", VAR_SERVER | VAR_HOST},
103         {"PMTU", VAR_SERVER | VAR_HOST},
104         {"PMTUDiscovery", VAR_SERVER | VAR_HOST},
105         {"Port", VAR_HOST},
106         {"PublicKey", VAR_HOST | VAR_OBSOLETE},
107         {"PublicKeyFile", VAR_SERVER | VAR_HOST | VAR_OBSOLETE},
108         {"Subnet", VAR_HOST | VAR_MULTIPLE | VAR_SAFE},
109         {"TCPOnly", VAR_SERVER | VAR_HOST},
110         {"Weight", VAR_HOST | VAR_SAFE},
111         {NULL, 0}
112 };
113
114 static bool fcopy(FILE *out, const char *filename) {
115         FILE *in = fopen(filename, "r");
116         if(!in) {
117                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
118                 return false;
119         }
120
121         char buf[1024];
122         size_t len;
123         while((len = fread(buf, 1, sizeof buf, in)))
124                 fwrite(buf, len, 1, out);
125         fclose(in);
126         return true;
127 }
128
129 static int rstrip(char *value) {
130         int len = strlen(value);
131         while(len && strchr("\t\r\n ", value[len - 1]))
132                 value[--len] = 0;
133         return len;
134 }
135
136 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
137         char line[4096];
138         if(!filename || (*hostname && *port))
139                 return;
140
141         FILE *f = fopen(filename, "r");
142         if(!f)
143                 return;
144
145         while(fgets(line, sizeof line, f)) {
146                 if(!rstrip(line))
147                         continue;
148                 char *p = line, *q;
149                 p += strcspn(p, "\t =");
150                 if(!*p)
151                         continue;
152                 q = p + strspn(p, "\t ");
153                 if(*q == '=')
154                         q += 1 + strspn(q + 1, "\t ");
155                 *p = 0;
156                 p = q + strcspn(q, "\t ");
157                 if(*p)
158                         *p++ = 0;
159                 p += strspn(p, "\t ");
160                 p[strcspn(p, "\t ")] = 0;
161
162                 if(!*port && !strcasecmp(line, "Port")) {
163                         *port = xstrdup(q);
164                 } else if(!*hostname && !strcasecmp(line, "Address")) {
165                         *hostname = xstrdup(q);
166                         if(*p) {
167                                 free(*port);
168                                 *port = xstrdup(p);
169                         }
170                 }
171
172                 if(*hostname && *port)
173                         break;
174         }
175
176         fclose(f);
177 }
178 static char *get_my_hostname(meshlink_handle_t* mesh) {
179         char *hostname = NULL;
180         char *port = NULL;
181         char *hostport = NULL;
182         char *name = mesh->self->name;
183         char filename[PATH_MAX] = "";
184         char line[4096];
185         FILE *f;
186
187         // Use first Address statement in own host config file
188         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
189         scan_for_hostname(filename, &hostname, &port);
190
191         if(hostname)
192                 goto done;
193
194         // If that doesn't work, guess externally visible hostname
195         fprintf(stderr, "Trying to discover externally visible hostname...\n");
196         struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
197         struct addrinfo *aip = ai;
198         static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
199
200         while(aip) {
201                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
202                 if(s >= 0) {
203                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
204                                 closesocket(s);
205                                 s = -1;
206                         }
207                 }
208                 if(s >= 0) {
209                         send(s, request, sizeof request - 1, 0);
210                         int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
211                         if(len > 0) {
212                                 line[len] = 0;
213                                 if(line[len - 1] == '\n')
214                                         line[--len] = 0;
215                                 char *p = strrchr(line, '\n');
216                                 if(p && p[1])
217                                         hostname = xstrdup(p + 1);
218                         }
219                         closesocket(s);
220                         if(hostname)
221                                 break;
222                 }
223                 aip = aip->ai_next;
224                 continue;
225         }
226
227         if(ai)
228                 freeaddrinfo(ai);
229
230         // Check that the hostname is reasonable
231         if(hostname) {
232                 for(char *p = hostname; *p; p++) {
233                         if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
234                                 continue;
235                         // If not, forget it.
236                         free(hostname);
237                         hostname = NULL;
238                         break;
239                 }
240         }
241
242         if(!hostname)
243                 return NULL;
244
245         f = fopen(filename, "a");
246         if(f) {
247                 fprintf(f, "\nAddress = %s\n", hostname);
248                 fclose(f);
249         } else {
250                 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
251         }
252
253 done:
254         if(port) {
255                 if(strchr(hostname, ':'))
256                         xasprintf(&hostport, "[%s]:%s", hostname, port);
257                 else
258                         xasprintf(&hostport, "%s:%s", hostname, port);
259         } else {
260                 if(strchr(hostname, ':'))
261                         xasprintf(&hostport, "[%s]", hostname);
262                 else
263                         hostport = xstrdup(hostname);
264         }
265
266         free(hostname);
267         free(port);
268         return hostport;
269 }
270
271 static char *get_line(const char **data) {
272         if(!data || !*data)
273                 return NULL;
274
275         if(!**data) {
276                 *data = NULL;
277                 return NULL;
278         }
279
280         static char line[1024];
281         const char *end = strchr(*data, '\n');
282         size_t len = end ? end - *data : strlen(*data);
283         if(len >= sizeof line) {
284                 fprintf(stderr, "Maximum line length exceeded!\n");
285                 return NULL;
286         }
287         if(len && !isprint(**data))
288                 abort();
289
290         memcpy(line, *data, len);
291         line[len] = 0;
292
293         if(end)
294                 *data = end + 1;
295         else
296                 *data = NULL;
297
298         return line;
299 }
300
301 static char *get_value(const char *data, const char *var) {
302         char *line = get_line(&data);
303         if(!line)
304                 return NULL;
305
306         char *sep = line + strcspn(line, " \t=");
307         char *val = sep + strspn(sep, " \t");
308         if(*val == '=')
309                 val += 1 + strspn(val + 1, " \t");
310         *sep = 0;
311         if(strcasecmp(line, var))
312                 return NULL;
313         return val;
314 }
315
316 static bool try_bind(int port) {
317         struct addrinfo *ai = NULL;
318         struct addrinfo hint = {
319                 .ai_flags = AI_PASSIVE,
320                 .ai_family = AF_UNSPEC,
321                 .ai_socktype = SOCK_STREAM,
322                 .ai_protocol = IPPROTO_TCP,
323         };
324
325         char portstr[16];
326         snprintf(portstr, sizeof portstr, "%d", port);
327
328         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
329                 return false;
330
331         while(ai) {
332                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
333                 if(!fd) {
334                         freeaddrinfo(ai);
335                         return false;
336                 }
337                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
338                 closesocket(fd);
339                 if(result) {
340                         freeaddrinfo(ai);
341                         return false;
342                 }
343                 ai = ai->ai_next;
344         }
345
346         freeaddrinfo(ai);
347         return true;
348 }
349
350 static int check_port(meshlink_handle_t *mesh) {
351         if(try_bind(655))
352                 return 655;
353
354         fprintf(stderr, "Warning: could not bind to port 655.\n");
355
356         for(int i = 0; i < 100; i++) {
357                 int port = 0x1000 + (rand() & 0x7fff);
358                 if(try_bind(port)) {
359                         char filename[PATH_MAX];
360                         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
361                         FILE *f = fopen(filename, "a");
362                         if(!f) {
363                                 fprintf(stderr, "Please change MeshLink's Port manually.\n");
364                                 return 0;
365                         }
366
367                         fprintf(f, "Port = %d\n", port);
368                         fclose(f);
369                         fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
370                         return port;
371                 }
372         }
373
374         fprintf(stderr, "Please change MeshLink's Port manually.\n");
375         return 0;
376 }
377
378 static bool finalize_join(meshlink_handle_t *mesh) {
379         char *name = xstrdup(get_value(mesh->data, "Name"));
380         if(!name) {
381                 fprintf(stderr, "No Name found in invitation!\n");
382                 return false;
383         }
384
385         if(!check_id(name)) {
386                 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
387                 return false;
388         }
389
390         char filename[PATH_MAX];
391         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
392
393         FILE *f = fopen(filename, "w");
394         if(!f) {
395                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
396                 return false;
397         }
398
399         fprintf(f, "Name = %s\n", name);
400
401         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
402         FILE *fh = fopen(filename, "w");
403         if(!fh) {
404                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
405                 fclose(f);
406                 return false;
407         }
408
409         // Filter first chunk on approved keywords, split between meshlink.conf and hosts/Name
410         // Other chunks go unfiltered to their respective host config files
411         const char *p = mesh->data;
412         char *l, *value;
413
414         while((l = get_line(&p))) {
415                 // Ignore comments
416                 if(*l == '#')
417                         continue;
418
419                 // Split line into variable and value
420                 int len = strcspn(l, "\t =");
421                 value = l + len;
422                 value += strspn(value, "\t ");
423                 if(*value == '=') {
424                         value++;
425                         value += strspn(value, "\t ");
426                 }
427                 l[len] = 0;
428
429                 // Is it a Name?
430                 if(!strcasecmp(l, "Name"))
431                         if(strcmp(value, name))
432                                 break;
433                         else
434                                 continue;
435                 else if(!strcasecmp(l, "NetName"))
436                         continue;
437
438                 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
439                 bool found = false;
440                 int i;
441                 for(i = 0; variables[i].name; i++) {
442                         if(strcasecmp(l, variables[i].name))
443                                 continue;
444                         found = true;
445                         break;
446                 }
447
448                 // Ignore unknown and unsafe variables
449                 if(!found) {
450                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
451                         continue;
452                 } else if(!(variables[i].type & VAR_SAFE)) {
453                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
454                         continue;
455                 }
456
457                 // Copy the safe variable to the right config file
458                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
459         }
460
461         fclose(f);
462
463         while(l && !strcasecmp(l, "Name")) {
464                 if(!check_id(value)) {
465                         fprintf(stderr, "Invalid Name found in invitation.\n");
466                         return false;
467                 }
468
469                 if(!strcmp(value, name)) {
470                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
471                         return false;
472                 }
473
474                 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
475                 f = fopen(filename, "w");
476
477                 if(!f) {
478                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
479                         return false;
480                 }
481
482                 while((l = get_line(&p))) {
483                         if(!strcmp(l, "#---------------------------------------------------------------#"))
484                                 continue;
485                         int len = strcspn(l, "\t =");
486                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
487                                 value = l + len;
488                                 value += strspn(value, "\t ");
489                                 if(*value == '=') {
490                                         value++;
491                                         value += strspn(value, "\t ");
492                                 }
493                                 l[len] = 0;
494                                 break;
495                         }
496
497                         fputs(l, f);
498                         fputc('\n', f);
499                 }
500
501                 fclose(f);
502         }
503
504         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
505         if(!b64key)
506                 return false;
507
508         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
509         fprintf(fh, "Port = %s\n", mesh->myport);
510
511         fclose(fh);
512
513         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
514         free(b64key);
515
516         free(mesh->self->name);
517         free(mesh->self->connection->name);
518         mesh->self->name = xstrdup(name);
519         mesh->self->connection->name = name;
520
521         fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
522
523         load_all_nodes(mesh);
524
525         return true;
526 }
527
528 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
529         meshlink_handle_t* mesh = handle;
530         while(len) {
531                 int result = send(mesh->sock, data, len, 0);
532                 if(result == -1 && errno == EINTR)
533                         continue;
534                 else if(result <= 0)
535                         return false;
536                 data += result;
537                 len -= result;
538         }
539         return true;
540 }
541
542 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
543         meshlink_handle_t* mesh = handle;
544         switch(type) {
545                 case SPTPS_HANDSHAKE:
546                         return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
547
548                 case 0:
549                         mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
550                         memcpy(mesh->data + mesh->thedatalen, msg, len);
551                         mesh->thedatalen += len;
552                         mesh->data[mesh->thedatalen] = 0;
553                         break;
554
555                 case 1:
556                         return finalize_join(mesh);
557
558                 case 2:
559                         fprintf(stderr, "Invitation succesfully accepted.\n");
560                         shutdown(mesh->sock, SHUT_RDWR);
561                         mesh->success = true;
562                         break;
563
564                 default:
565                         return false;
566         }
567
568         return true;
569 }
570
571 static bool recvline(meshlink_handle_t* mesh, size_t len) {
572         char *newline = NULL;
573
574         if(!mesh->sock)
575                 abort();
576
577         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
578                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
579                 if(result == -1 && errno == EINTR)
580                         continue;
581                 else if(result <= 0)
582                         return false;
583                 mesh->blen += result;
584         }
585
586         if(newline - mesh->buffer >= len)
587                 return false;
588
589         len = newline - mesh->buffer;
590
591         memcpy(mesh->line, mesh->buffer, len);
592         mesh->line[len] = 0;
593         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
594         mesh->blen -= len + 1;
595
596         return true;
597 }
598 static bool sendline(int fd, char *format, ...) {
599         static char buffer[4096];
600         char *p = buffer;
601         int blen = 0;
602         va_list ap;
603
604         va_start(ap, format);
605         blen = vsnprintf(buffer, sizeof buffer, format, ap);
606         va_end(ap);
607
608         if(blen < 1 || blen >= sizeof buffer)
609                 return false;
610
611         buffer[blen] = '\n';
612         blen++;
613
614         while(blen) {
615                 int result = send(fd, p, blen, MSG_NOSIGNAL);
616                 if(result == -1 && errno == EINTR)
617                         continue;
618                 else if(result <= 0)
619                         return false;
620                 p += result;
621                 blen -= result;
622         }
623
624         return true;
625 }
626
627 static const char *errstr[] = {
628         [MESHLINK_OK] = "No error",
629         [MESHLINK_EINVAL] = "Invalid argument",
630         [MESHLINK_ENOMEM] = "Out of memory",
631         [MESHLINK_ENOENT] = "No such node",
632         [MESHLINK_EEXIST] = "Node already exists",
633         [MESHLINK_EINTERNAL] = "Internal error",
634         [MESHLINK_ERESOLV] = "Could not resolve hostname",
635         [MESHLINK_ESTORAGE] = "Storage error",
636         [MESHLINK_ENETWORK] = "Network error",
637         [MESHLINK_EPEER] = "Error communicating with peer",
638 };
639
640 const char *meshlink_strerror(meshlink_errno_t err) {
641         if(err < 0 || err >= sizeof errstr / sizeof *errstr)
642                 return "Invalid error code";
643         return errstr[err];
644 }
645
646 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
647         ecdsa_t *key;
648         FILE *f;
649         char pubname[PATH_MAX], privname[PATH_MAX];
650
651         fprintf(stderr, "Generating ECDSA keypair:\n");
652
653         if(!(key = ecdsa_generate())) {
654                 fprintf(stderr, "Error during key generation!\n");
655                 meshlink_errno = MESHLINK_EINTERNAL;
656                 return false;
657         } else
658                 fprintf(stderr, "Done.\n");
659
660         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
661         f = fopen(privname, "w");
662
663         if(!f) {
664                 meshlink_errno = MESHLINK_ESTORAGE;
665                 return false;
666         }
667
668 #ifdef HAVE_FCHMOD
669         fchmod(fileno(f), 0600);
670 #endif
671
672         if(!ecdsa_write_pem_private_key(key, f)) {
673                 fprintf(stderr, "Error writing private key!\n");
674                 ecdsa_free(key);
675                 fclose(f);
676                 meshlink_errno = MESHLINK_EINTERNAL;
677                 return false;
678         }
679
680         fclose(f);
681
682         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
683         f = fopen(pubname, "a");
684
685         if(!f) {
686                 meshlink_errno = MESHLINK_ESTORAGE;
687                 return false;
688         }
689
690         char *pubkey = ecdsa_get_base64_public_key(key);
691         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
692         free(pubkey);
693
694         fclose(f);
695         ecdsa_free(key);
696
697         return true;
698 }
699
700 static bool meshlink_setup(meshlink_handle_t *mesh) {
701         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
702                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
703                 meshlink_errno = MESHLINK_ESTORAGE;
704                 return false;
705         }
706
707         char filename[PATH_MAX];
708         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
709
710         if(mkdir(filename, 0777) && errno != EEXIST) {
711                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
712                 meshlink_errno = MESHLINK_ESTORAGE;
713                 return false;
714         }
715
716         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
717
718         if(!access(filename, F_OK)) {
719                 fprintf(stderr, "Configuration file %s already exists!\n", filename);
720                 meshlink_errno = MESHLINK_EEXIST;
721                 return false;
722         }
723
724         FILE *f = fopen(filename, "w");
725         if(!f) {
726                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
727                 meshlink_errno = MESHLINK_ESTORAGE;
728                 return false;
729         }
730
731         fprintf(f, "Name = %s\n", mesh->name);
732         fclose(f);
733
734         if(!ecdsa_keygen(mesh)) {
735                 meshlink_errno = MESHLINK_EINTERNAL;
736                 return false;
737         }
738
739         check_port(mesh);
740
741         return true;
742 }
743
744 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
745         // Validate arguments provided by the application
746         bool usingname = false;
747
748         if(!confbase || !*confbase) {
749                 fprintf(stderr, "No confbase given!\n");
750                 meshlink_errno = MESHLINK_EINVAL;
751                 return NULL;
752         }
753
754         if(!name || !*name) {
755                 fprintf(stderr, "No name given!\n");
756                 //return NULL;
757         }
758         else { //check name only if there is a name != NULL
759
760                 if(!check_id(name)) {
761                         fprintf(stderr, "Invalid name given!\n");
762                         meshlink_errno = MESHLINK_EINVAL;
763                         return NULL;
764                 } else { usingname = true;}
765         }
766
767         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
768         mesh->confbase = xstrdup(confbase);
769         if (usingname) mesh->name = xstrdup(name);
770         pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
771         pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
772         mesh->threadstarted = false;
773         event_loop_init(&mesh->loop);
774         mesh->loop.data = mesh;
775
776         // TODO: should be set by a function.
777         mesh->debug_level = 5;
778
779         // Check whether meshlink.conf already exists
780
781         char filename[PATH_MAX];
782         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
783
784         if(access(filename, R_OK)) {
785                 if(errno == ENOENT) {
786                         // If not, create it
787                         if(!meshlink_setup(mesh)) {
788                                 // meshlink_errno is set by meshlink_setup()
789                                 return NULL;
790                         }
791                 } else {
792                         fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
793                         meshlink_close(mesh);
794                         meshlink_errno = MESHLINK_ESTORAGE;
795                         return NULL;
796                 }
797         }
798
799         // Read the configuration
800
801         init_configuration(&mesh->config);
802
803         if(!read_server_config(mesh)) {
804                 meshlink_close(mesh);
805                 meshlink_errno = MESHLINK_ESTORAGE;
806                 return NULL;
807         };
808
809 #ifdef HAVE_MINGW
810         struct WSAData wsa_state;
811         WSAStartup(MAKEWORD(2, 2), &wsa_state);
812 #endif
813
814         // Setup up everything
815         // TODO: we should not open listening sockets yet
816
817         if(!setup_network(mesh)) {
818                 meshlink_close(mesh);
819                 meshlink_errno = MESHLINK_ENETWORK;
820                 return NULL;
821         }
822
823         return mesh;
824 }
825
826 static void *meshlink_main_loop(void *arg) {
827         meshlink_handle_t *mesh = arg;
828
829         try_outgoing_connections(mesh);
830
831         main_loop(mesh);
832
833         return NULL;
834 }
835
836 bool meshlink_start(meshlink_handle_t *mesh) {
837         if(!mesh) {
838                 meshlink_errno = MESHLINK_EINVAL;
839                 return false;
840         }
841
842         // TODO: open listening sockets first
843
844         //Check that a valid name is set
845         if(!mesh->name ) {
846                 fprintf(stderr, "No name given!\n");
847                 meshlink_errno = MESHLINK_EINVAL;
848                 return false;
849         }
850
851         // Start the main thread
852
853         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
854                 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
855                 memset(&mesh->thread, 0, sizeof mesh->thread);
856                 meshlink_errno = MESHLINK_EINTERNAL;
857                 return false;
858         }
859
860         mesh->threadstarted=true;
861
862         // Start discovery
863         if(!discovery_start(mesh))
864                 return false;
865
866         return true;
867 }
868
869 void meshlink_stop(meshlink_handle_t *mesh) {
870         if(!mesh) {
871                 meshlink_errno = MESHLINK_EINVAL;
872                 return;
873         }
874
875         // Stop discovery
876         discovery_stop(mesh);
877
878         // Shut down the listening sockets to signal the main thread to shut down
879
880         for(int i = 0; i < mesh->listen_sockets; i++) {
881                 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
882                 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
883         }
884
885         // Wait for the main thread to finish
886
887         pthread_join(mesh->thread, NULL);
888 }
889
890 void meshlink_close(meshlink_handle_t *mesh) {
891         if(!mesh || !mesh->confbase) {
892                 meshlink_errno = MESHLINK_EINVAL;
893                 return;
894         }
895
896         // Close and free all resources used.
897
898         close_network_connections(mesh);
899
900         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
901
902         exit_configuration(&mesh->config);
903         event_loop_exit(&mesh->loop);
904
905 #ifdef HAVE_MINGW
906         if(mesh->confbase)
907                 WSACleanup();
908 #endif
909
910         ecdsa_free(mesh->invitation_key);
911
912         free(mesh->name);
913         free(mesh->confbase);
914
915         memset(mesh, 0, sizeof *mesh);
916
917         free(mesh);
918 }
919
920 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
921         if(!mesh) {
922                 meshlink_errno = MESHLINK_EINVAL;
923                 return;
924         }
925
926         mesh->receive_cb = cb;
927 }
928
929 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
930         if(!mesh) {
931                 meshlink_errno = MESHLINK_EINVAL;
932                 return;
933         }
934
935         mesh->node_status_cb = cb;
936 }
937
938 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
939         if(!mesh) {
940                 meshlink_errno = MESHLINK_EINVAL;
941                 return;
942         }
943
944         mesh->log_cb = cb;
945         mesh->log_level = level;
946 }
947
948 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
949         if(!mesh || !destination) {
950                 meshlink_errno = MESHLINK_EINVAL;
951                 return false;
952         }
953
954         if(!len)
955                 return true;
956
957         if(!data) {
958                 meshlink_errno = MESHLINK_EINVAL;
959                 return false;
960         }
961
962         /* If there is no outgoing list yet, create one. */
963
964         if(!mesh->outpacketqueue)
965                 mesh->outpacketqueue = list_alloc(NULL);
966
967         //add packet to the queue
968         outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
969         packet_in_queue->destination=destination;
970         packet_in_queue->data=data;
971         packet_in_queue->len=len;
972         pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
973         list_insert_head(mesh->outpacketqueue,packet_in_queue);
974         pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
975
976         //notify event loop
977         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
978         return true;
979 }
980
981 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
982         vpn_packet_t packet;
983         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
984
985         outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
986         if (p)
987         list_delete_tail(mesh->outpacketqueue);
988         else return ;
989
990         if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
991                 //log something
992                 return ;
993         }
994
995         packet.probe = false;
996         memset(hdr, 0, sizeof *hdr);
997         memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
998         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
999
1000         packet.len = sizeof *hdr + p->len;
1001         memcpy(packet.data + sizeof *hdr, p->data, p->len);
1002
1003         mesh->self->in_packets++;
1004         mesh->self->in_bytes += packet.len;
1005         route(mesh, mesh->self, &packet);
1006         return ;
1007 }
1008
1009 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1010         if(!mesh || !destination) {
1011                 meshlink_errno = MESHLINK_EINVAL;
1012                 return -1;
1013         }
1014
1015         node_t *n = (node_t *)destination;
1016         if(!n->status.reachable)
1017                 return 0;
1018         else if(n->mtuprobes > 30 && n->minmtu)
1019                 return n->minmtu;
1020         else
1021                 return MTU;
1022 }
1023
1024 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1025         if(!mesh || !node) {
1026                 meshlink_errno = MESHLINK_EINVAL;
1027                 return NULL;
1028         }
1029
1030         node_t *n = (node_t *)node;
1031
1032         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1033                 meshlink_errno = MESHLINK_EINTERNAL;
1034                 return false;
1035         }
1036
1037         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1038
1039         if(!fingerprint)
1040                 meshlink_errno = MESHLINK_EINTERNAL;
1041
1042         return fingerprint;
1043 }
1044
1045 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1046         if(!mesh || !name) {
1047                 meshlink_errno = MESHLINK_EINVAL;
1048                 return NULL;
1049         }
1050
1051         return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1052 }
1053
1054 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1055         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1056                 meshlink_errno = MESHLINK_EINVAL;
1057                 return NULL;
1058         }
1059
1060         meshlink_node_t **result;
1061
1062         //lock mesh->nodes
1063         pthread_mutex_lock(&(mesh->nodes_mutex));
1064
1065         *nmemb = mesh->nodes->count;
1066         result = realloc(nodes, *nmemb * sizeof *nodes);
1067
1068         if(result) {
1069                 meshlink_node_t **p = result;
1070                 for splay_each(node_t, n, mesh->nodes)
1071                         *p++ = (meshlink_node_t *)n;
1072         } else {
1073                 *nmemb = 0;
1074                 free(nodes);
1075                 meshlink_errno = MESHLINK_ENOMEM;
1076         }
1077
1078         pthread_mutex_unlock(&(mesh->nodes_mutex));
1079
1080         return result;
1081 }
1082
1083 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1084         if(!mesh || !data || !len || !signature || !siglen) {
1085                 meshlink_errno = MESHLINK_EINVAL;
1086                 return false;
1087         }
1088
1089         if(*siglen < MESHLINK_SIGLEN) {
1090                 meshlink_errno = MESHLINK_EINVAL;
1091                 return false;
1092         }
1093
1094         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1095                 meshlink_errno = MESHLINK_EINTERNAL;
1096                 return false;
1097         }
1098
1099         *siglen = MESHLINK_SIGLEN;
1100         return true;
1101 }
1102
1103 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1104         if(!mesh || !data || !len || !signature) {
1105                 meshlink_errno = MESHLINK_EINVAL;
1106                 return false;
1107         }
1108
1109         if(siglen != MESHLINK_SIGLEN) {
1110                 meshlink_errno = MESHLINK_EINVAL;
1111                 return false;
1112         }
1113
1114         struct node_t *n = (struct node_t *)source;
1115         node_read_ecdsa_public_key(mesh, n);
1116         if(!n->ecdsa) {
1117                 meshlink_errno = MESHLINK_EINTERNAL;
1118                 return false;
1119         }
1120
1121         return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1122 }
1123
1124 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1125         char filename[PATH_MAX];
1126
1127         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1128         if(mkdir(filename, 0700) && errno != EEXIST) {
1129                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1130                 meshlink_errno = MESHLINK_ESTORAGE;
1131                 return false;
1132         }
1133
1134         // Count the number of valid invitations, clean up old ones
1135         DIR *dir = opendir(filename);
1136         if(!dir) {
1137                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1138                 meshlink_errno = MESHLINK_ESTORAGE;
1139                 return false;
1140         }
1141
1142         errno = 0;
1143         int count = 0;
1144         struct dirent *ent;
1145         time_t deadline = time(NULL) - 604800; // 1 week in the past
1146
1147         while((ent = readdir(dir))) {
1148                 if(strlen(ent->d_name) != 24)
1149                         continue;
1150                 char invname[PATH_MAX];
1151                 struct stat st;
1152                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1153                 if(!stat(invname, &st)) {
1154                         if(mesh->invitation_key && deadline < st.st_mtime)
1155                                 count++;
1156                         else
1157                                 unlink(invname);
1158                 } else {
1159                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1160                         errno = 0;
1161                 }
1162         }
1163
1164         if(errno) {
1165                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1166                 closedir(dir);
1167                 meshlink_errno = MESHLINK_ESTORAGE;
1168                 return false;
1169         }
1170
1171         closedir(dir);
1172
1173         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1174
1175         // Remove the key if there are no outstanding invitations.
1176         if(!count) {
1177                 unlink(filename);
1178                 if(mesh->invitation_key) {
1179                         ecdsa_free(mesh->invitation_key);
1180                         mesh->invitation_key = NULL;
1181                 }
1182         }
1183
1184         if(mesh->invitation_key)
1185                 return true;
1186
1187         // Create a new key if necessary.
1188         FILE *f = fopen(filename, "r");
1189         if(!f) {
1190                 if(errno != ENOENT) {
1191                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1192                         meshlink_errno = MESHLINK_ESTORAGE;
1193                         return false;
1194                 }
1195
1196                 mesh->invitation_key = ecdsa_generate();
1197                 if(!mesh->invitation_key) {
1198                         fprintf(stderr, "Could not generate a new key!\n");
1199                         meshlink_errno = MESHLINK_EINTERNAL;
1200                         return false;
1201                 }
1202                 f = fopen(filename, "w");
1203                 if(!f) {
1204                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1205                         meshlink_errno = MESHLINK_ESTORAGE;
1206                         return false;
1207                 }
1208                 chmod(filename, 0600);
1209                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1210                 fclose(f);
1211         } else {
1212                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1213                 fclose(f);
1214                 if(!mesh->invitation_key) {
1215                         fprintf(stderr, "Could not read private key from %s\n", filename);
1216                         meshlink_errno = MESHLINK_ESTORAGE;
1217                 }
1218         }
1219
1220         return mesh->invitation_key;
1221 }
1222
1223 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1224         if(!mesh || !address) {
1225                 meshlink_errno = MESHLINK_EINVAL;
1226                 return false;
1227         }
1228
1229         for(const char *p = address; *p; p++) {
1230                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1231                         continue;
1232                 fprintf(stderr, "Invalid character in address: %s\n", address);
1233                 meshlink_errno = MESHLINK_EINVAL;
1234                 return false;
1235         }
1236
1237         return append_config_file(mesh, mesh->self->name, "Address", address);
1238 }
1239
1240 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1241         if(!mesh) {
1242                 meshlink_errno = MESHLINK_EINVAL;
1243                 return NULL;
1244         }
1245
1246         // Check validity of the new node's name
1247         if(!check_id(name)) {
1248                 fprintf(stderr, "Invalid name for node.\n");
1249                 meshlink_errno = MESHLINK_EINVAL;
1250                 return NULL;
1251         }
1252
1253         // Ensure no host configuration file with that name exists
1254         char filename[PATH_MAX];
1255         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1256         if(!access(filename, F_OK)) {
1257                 fprintf(stderr, "A host config file for %s already exists!\n", name);
1258                 meshlink_errno = MESHLINK_EEXIST;
1259                 return NULL;
1260         }
1261
1262         // Ensure no other nodes know about this name
1263         if(meshlink_get_node(mesh, name)) {
1264                 fprintf(stderr, "A node with name %s is already known!\n", name);
1265                 meshlink_errno = MESHLINK_EEXIST;
1266                 return NULL;
1267         }
1268
1269         // Get the local address
1270         char *address = get_my_hostname(mesh);
1271         if(!address) {
1272                 fprintf(stderr, "No Address known for ourselves!\n");
1273                 meshlink_errno = MESHLINK_ERESOLV;
1274                 return NULL;
1275         }
1276
1277         if(!refresh_invitation_key(mesh)) {
1278                 meshlink_errno = MESHLINK_EINTERNAL;
1279                 return NULL;
1280         }
1281
1282         char hash[64];
1283
1284         // Create a hash of the key.
1285         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1286         sha512(fingerprint, strlen(fingerprint), hash);
1287         b64encode_urlsafe(hash, hash, 18);
1288
1289         // Create a random cookie for this invitation.
1290         char cookie[25];
1291         randomize(cookie, 18);
1292
1293         // Create a filename that doesn't reveal the cookie itself
1294         char buf[18 + strlen(fingerprint)];
1295         char cookiehash[64];
1296         memcpy(buf, cookie, 18);
1297         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1298         sha512(buf, sizeof buf, cookiehash);
1299         b64encode_urlsafe(cookiehash, cookiehash, 18);
1300
1301         b64encode_urlsafe(cookie, cookie, 18);
1302
1303         free(fingerprint);
1304
1305         // Create a file containing the details of the invitation.
1306         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1307         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1308         if(!ifd) {
1309                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1310                 meshlink_errno = MESHLINK_ESTORAGE;
1311                 return NULL;
1312         }
1313         FILE *f = fdopen(ifd, "w");
1314         if(!f)
1315                 abort();
1316
1317         // Fill in the details.
1318         fprintf(f, "Name = %s\n", name);
1319         //if(netname)
1320         //      fprintf(f, "NetName = %s\n", netname);
1321         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1322
1323         // Copy Broadcast and Mode
1324         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1325         FILE *tc = fopen(filename,  "r");
1326         if(tc) {
1327                 char buf[1024];
1328                 while(fgets(buf, sizeof buf, tc)) {
1329                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1330                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1331                                 fputs(buf, f);
1332                                 // Make sure there is a newline character.
1333                                 if(!strchr(buf, '\n'))
1334                                         fputc('\n', f);
1335                         }
1336                 }
1337                 fclose(tc);
1338         } else {
1339                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1340                 meshlink_errno = MESHLINK_ESTORAGE;
1341                 return NULL;
1342         }
1343
1344         fprintf(f, "#---------------------------------------------------------------#\n");
1345         fprintf(f, "Name = %s\n", mesh->self->name);
1346
1347         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1348         fcopy(f, filename);
1349         fclose(f);
1350
1351         // Create an URL from the local address, key hash and cookie
1352         char *url;
1353         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1354         free(address);
1355
1356         return url;
1357 }
1358
1359 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1360         if(!mesh || !invitation) {
1361                 meshlink_errno = MESHLINK_EINVAL;
1362                 return false;
1363         }
1364
1365         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1366         char copy[strlen(invitation) + 1];
1367         strcpy(copy, invitation);
1368
1369         // Split the invitation URL into hostname, port, key hash and cookie.
1370
1371         char *slash = strchr(copy, '/');
1372         if(!slash)
1373                 goto invalid;
1374
1375         *slash++ = 0;
1376
1377         if(strlen(slash) != 48)
1378                 goto invalid;
1379
1380         char *address = copy;
1381         char *port = NULL;
1382         if(*address == '[') {
1383                 address++;
1384                 char *bracket = strchr(address, ']');
1385                 if(!bracket)
1386                         goto invalid;
1387                 *bracket = 0;
1388                 if(bracket[1] == ':')
1389                         port = bracket + 2;
1390         } else {
1391                 port = strchr(address, ':');
1392                 if(port)
1393                         *port++ = 0;
1394         }
1395
1396         if(!port)
1397                 port = "655";
1398
1399         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1400                 goto invalid;
1401
1402         // Generate a throw-away key for the invitation.
1403         ecdsa_t *key = ecdsa_generate();
1404         if(!key) {
1405                 meshlink_errno = MESHLINK_EINTERNAL;
1406                 return false;
1407         }
1408
1409         char *b64key = ecdsa_get_base64_public_key(key);
1410
1411         //Before doing meshlink_join make sure we are not connected to another mesh
1412         if ( mesh->threadstarted ){
1413                 goto invalid;
1414         }
1415
1416         // Connect to the meshlink daemon mentioned in the URL.
1417         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1418         if(!ai) {
1419                 meshlink_errno = MESHLINK_ERESOLV;
1420                 return false;
1421         }
1422
1423         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1424         if(mesh->sock <= 0) {
1425                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1426                 freeaddrinfo(ai);
1427                 meshlink_errno = MESHLINK_ENETWORK;
1428                 return false;
1429         }
1430
1431         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1432                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1433                 closesocket(mesh->sock);
1434                 freeaddrinfo(ai);
1435                 meshlink_errno = MESHLINK_ENETWORK;
1436                 return false;
1437         }
1438
1439         freeaddrinfo(ai);
1440
1441         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1442
1443         // Tell him we have an invitation, and give him our throw-away key.
1444
1445         mesh->blen = 0;
1446
1447         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1448                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1449                 closesocket(mesh->sock);
1450                 meshlink_errno = MESHLINK_ENETWORK;
1451                 return false;
1452         }
1453
1454         free(b64key);
1455
1456         char hisname[4096] = "";
1457         int code, hismajor, hisminor = 0;
1458
1459         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) {
1460                 fprintf(stderr, "Cannot read greeting from peer\n");
1461                 closesocket(mesh->sock);
1462                 meshlink_errno = MESHLINK_ENETWORK;
1463                 return false;
1464         }
1465
1466         // Check if the hash of the key he gave us matches the hash in the URL.
1467         char *fingerprint = mesh->line + 2;
1468         char hishash[64];
1469         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1470                 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1471                 meshlink_errno = MESHLINK_EINTERNAL;
1472                 return false;
1473         }
1474         if(memcmp(hishash, mesh->hash, 18)) {
1475                 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1476                 meshlink_errno = MESHLINK_EPEER;
1477                 return false;
1478
1479         }
1480
1481         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1482         if(!hiskey) {
1483                 meshlink_errno = MESHLINK_EINTERNAL;
1484                 return false;
1485         }
1486
1487         // Start an SPTPS session
1488         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1489                 meshlink_errno = MESHLINK_EINTERNAL;
1490                 return false;
1491         }
1492
1493         // Feed rest of input buffer to SPTPS
1494         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1495                 meshlink_errno = MESHLINK_EPEER;
1496                 return false;
1497         }
1498
1499         int len;
1500
1501         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1502                 if(len < 0) {
1503                         if(errno == EINTR)
1504                                 continue;
1505                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1506                         meshlink_errno = MESHLINK_ENETWORK;
1507                         return false;
1508                 }
1509
1510                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1511                         meshlink_errno = MESHLINK_EPEER;
1512                         return false;
1513                 }
1514         }
1515
1516         sptps_stop(&mesh->sptps);
1517         ecdsa_free(hiskey);
1518         ecdsa_free(key);
1519         closesocket(mesh->sock);
1520
1521         if(!mesh->success) {
1522                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1523                 meshlink_errno = MESHLINK_EPEER;
1524                 return false;
1525         }
1526
1527         return true;
1528
1529 invalid:
1530         fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1531         meshlink_errno = MESHLINK_EINVAL;
1532         return false;
1533 }
1534
1535 char *meshlink_export(meshlink_handle_t *mesh) {
1536         if(!mesh) {
1537                 meshlink_errno = MESHLINK_EINVAL;
1538                 return NULL;
1539         }
1540
1541         char filename[PATH_MAX];
1542         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1543         FILE *f = fopen(filename, "r");
1544         if(!f) {
1545                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1546                 meshlink_errno = MESHLINK_ESTORAGE;
1547                 return NULL;
1548         }
1549
1550         fseek(f, 0, SEEK_END);
1551         int fsize = ftell(f);
1552         rewind(f);
1553
1554         size_t len = fsize + 9 + strlen(mesh->self->name);
1555         char *buf = xmalloc(len);
1556         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1557         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1558                 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1559                 fclose(f);
1560                 meshlink_errno = MESHLINK_ESTORAGE;
1561                 return NULL;
1562         }
1563
1564         fclose(f);
1565         buf[len - 1] = 0;
1566         return buf;
1567 }
1568
1569 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1570         if(!mesh || !data) {
1571                 meshlink_errno = MESHLINK_EINVAL;
1572                 return false;
1573         }
1574
1575         if(strncmp(data, "Name = ", 7)) {
1576                 fprintf(stderr, "Invalid data\n");
1577                 meshlink_errno = MESHLINK_EPEER;
1578                 return false;
1579         }
1580
1581         char *end = strchr(data + 7, '\n');
1582         if(!end) {
1583                 fprintf(stderr, "Invalid data\n");
1584                 meshlink_errno = MESHLINK_EPEER;
1585                 return false;
1586         }
1587
1588         int len = end - (data + 7);
1589         char name[len + 1];
1590         memcpy(name, data + 7, len);
1591         name[len] = 0;
1592         if(!check_id(name)) {
1593                 fprintf(stderr, "Invalid Name\n");
1594                 meshlink_errno = MESHLINK_EPEER;
1595                 return false;
1596         }
1597
1598         char filename[PATH_MAX];
1599         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1600         if(!access(filename, F_OK)) {
1601                 fprintf(stderr, "File %s already exists, not importing\n", filename);
1602                 meshlink_errno = MESHLINK_EEXIST;
1603                 return false;
1604         }
1605
1606         if(errno != ENOENT) {
1607                 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1608                 meshlink_errno = MESHLINK_ESTORAGE;
1609                 return false;
1610         }
1611
1612         FILE *f = fopen(filename, "w");
1613         if(!f) {
1614                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1615                 meshlink_errno = MESHLINK_ESTORAGE;
1616                 return false;
1617         }
1618
1619         fwrite(end + 1, strlen(end + 1), 1, f);
1620         fclose(f);
1621
1622         load_all_nodes(mesh);
1623
1624         return true;
1625 }
1626
1627 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1628         if(!mesh || !node) {
1629                 meshlink_errno = MESHLINK_EINVAL;
1630                 return;
1631         }
1632
1633         node_t *n;
1634         n = (node_t*)node;
1635         n->status.blacklisted=true;
1636         fprintf(stderr, "Blacklisted %s.\n",node->name);
1637
1638         //Make blacklisting persistent in the config file
1639         append_config_file(mesh, n->name, "blacklisted", "yes");
1640
1641         return;
1642 }
1643
1644 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1645         if(!mesh || !node) {
1646                 meshlink_errno = MESHLINK_EINVAL;
1647                 return;
1648         }
1649
1650         node_t *n = (node_t *)node;
1651         n->status.blacklisted = false;
1652
1653         //TODO: remove blacklisted = yes from the config file
1654
1655         return;
1656 }
1657
1658 static void __attribute__((constructor)) meshlink_init(void) {
1659         crypto_init();
1660 }
1661
1662 static void __attribute__((destructor)) meshlink_exit(void) {
1663         crypto_exit();
1664 }