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