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