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