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