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