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