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