]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
9fc80153d48210b0cbb60f7c7793b673c4e090cd
[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_EINVAL] = "Invalid argument",
629         [MESHLINK_ENOMEM] = "Out of memory",
630         [MESHLINK_ENOENT] = "No such node",
631         [MESHLINK_EEXIST] = "Node already exists",
632         [MESHLINK_EINTERNAL] = "Internal error",
633         [MESHLINK_ERESOLV] = "Could not resolve hostname",
634         [MESHLINK_ESTORAGE] = "Storage error",
635         [MESHLINK_ENETWORK] = "Network error",
636         [MESHLINK_EPEER] = "Error communicating with peer",
637 };
638
639 const char *meshlink_strerror(meshlink_errno_t err) {
640         if(err < 0 || err >= sizeof errstr / sizeof *errstr)
641                 return "Invalid error code";
642         return errstr[err];
643 }
644
645 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
646         ecdsa_t *key;
647         FILE *f;
648         char pubname[PATH_MAX], privname[PATH_MAX];
649
650         fprintf(stderr, "Generating ECDSA keypair:\n");
651
652         if(!(key = ecdsa_generate())) {
653                 fprintf(stderr, "Error during key generation!\n");
654                 meshlink_errno = MESHLINK_EINTERNAL;
655                 return false;
656         } else
657                 fprintf(stderr, "Done.\n");
658
659         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
660         f = fopen(privname, "w");
661
662         if(!f) {
663                 meshlink_errno = MESHLINK_ESTORAGE;
664                 return false;
665         }
666
667 #ifdef HAVE_FCHMOD
668         fchmod(fileno(f), 0600);
669 #endif
670
671         if(!ecdsa_write_pem_private_key(key, f)) {
672                 fprintf(stderr, "Error writing private key!\n");
673                 ecdsa_free(key);
674                 fclose(f);
675                 meshlink_errno = MESHLINK_EINTERNAL;
676                 return false;
677         }
678
679         fclose(f);
680
681         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
682         f = fopen(pubname, "a");
683
684         if(!f) {
685                 meshlink_errno = MESHLINK_ESTORAGE;
686                 return false;
687         }
688
689         char *pubkey = ecdsa_get_base64_public_key(key);
690         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
691         free(pubkey);
692
693         fclose(f);
694         ecdsa_free(key);
695
696         return true;
697 }
698
699 static bool meshlink_setup(meshlink_handle_t *mesh) {
700         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
701                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
702                 meshlink_errno = MESHLINK_ESTORAGE;
703                 return false;
704         }
705
706         char filename[PATH_MAX];
707         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
708
709         if(mkdir(filename, 0777) && errno != EEXIST) {
710                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
711                 meshlink_errno = MESHLINK_ESTORAGE;
712                 return false;
713         }
714
715         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
716
717         if(!access(filename, F_OK)) {
718                 fprintf(stderr, "Configuration file %s already exists!\n", filename);
719                 meshlink_errno = MESHLINK_EEXIST;
720                 return false;
721         }
722
723         FILE *f = fopen(filename, "w");
724         if(!f) {
725                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
726                 meshlink_errno = MESHLINK_ESTORAGE;
727                 return false;
728         }
729
730         fprintf(f, "Name = %s\n", mesh->name);
731         fclose(f);
732
733         if(!ecdsa_keygen(mesh)) {
734                 meshlink_errno = MESHLINK_EINTERNAL;
735                 return false;
736         }
737
738         check_port(mesh);
739
740         return true;
741 }
742
743 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
744         // Validate arguments provided by the application
745         bool usingname = false;
746
747         if(!confbase || !*confbase) {
748                 fprintf(stderr, "No confbase given!\n");
749                 meshlink_errno = MESHLINK_EINVAL;
750                 return NULL;
751         }
752
753         if(!name || !*name) {
754                 fprintf(stderr, "No name given!\n");
755                 //return NULL;
756         }
757         else { //check name only if there is a name != NULL
758
759                 if(!check_id(name)) {
760                         fprintf(stderr, "Invalid name given!\n");
761                         meshlink_errno = MESHLINK_EINVAL;
762                         return NULL;
763                 } else { usingname = true;}
764         }
765
766         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
767         mesh->confbase = xstrdup(confbase);
768         if (usingname) mesh->name = xstrdup(name);
769         pthread_mutex_init ( &(mesh->outpacketqueue_mutex), NULL);
770         pthread_mutex_init ( &(mesh->nodes_mutex), NULL);
771         mesh->threadstarted = false;
772         event_loop_init(&mesh->loop);
773         mesh->loop.data = mesh;
774
775         // TODO: should be set by a function.
776         mesh->debug_level = 5;
777
778         // Check whether meshlink.conf already exists
779
780         char filename[PATH_MAX];
781         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", confbase);
782
783         if(access(filename, R_OK)) {
784                 if(errno == ENOENT) {
785                         // If not, create it
786                         if(!meshlink_setup(mesh)) {
787                                 // meshlink_errno is set by meshlink_setup()
788                                 return NULL;
789                         }
790                 } else {
791                         fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
792                         meshlink_close(mesh);
793                         meshlink_errno = MESHLINK_ESTORAGE;
794                         return NULL;
795                 }
796         }
797
798         // Read the configuration
799
800         init_configuration(&mesh->config);
801
802         if(!read_server_config(mesh)) {
803                 meshlink_close(mesh);
804                 meshlink_errno = MESHLINK_ESTORAGE;
805                 return NULL;
806         };
807
808 #ifdef HAVE_MINGW
809         struct WSAData wsa_state;
810         WSAStartup(MAKEWORD(2, 2), &wsa_state);
811 #endif
812
813         // Setup up everything
814         // TODO: we should not open listening sockets yet
815
816         if(!setup_network(mesh)) {
817                 meshlink_close(mesh);
818                 meshlink_errno = MESHLINK_ENETWORK;
819                 return NULL;
820         }
821
822         return mesh;
823 }
824
825 static void *meshlink_main_loop(void *arg) {
826         meshlink_handle_t *mesh = arg;
827
828         try_outgoing_connections(mesh);
829
830         main_loop(mesh);
831
832         return NULL;
833 }
834
835 bool meshlink_start(meshlink_handle_t *mesh) {
836         if(!mesh) {
837                 meshlink_errno = MESHLINK_EINVAL;
838                 return false;
839         }
840
841         // TODO: open listening sockets first
842
843         //Check that a valid name is set
844         if(!mesh->name ) {
845                 fprintf(stderr, "No name given!\n");
846                 meshlink_errno = MESHLINK_EINVAL;
847                 return false;
848         }
849
850         // Start the main thread
851
852         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
853                 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
854                 memset(&mesh->thread, 0, sizeof mesh->thread);
855                 meshlink_errno = MESHLINK_EINTERNAL;
856                 return false;
857         }
858
859         mesh->threadstarted=true;
860
861         return true;
862 }
863
864 void meshlink_stop(meshlink_handle_t *mesh) {
865         if(!mesh) {
866                 meshlink_errno = MESHLINK_EINVAL;
867                 return;
868         }
869
870         // Shut down the listening sockets to signal the main thread to shut down
871
872         for(int i = 0; i < mesh->listen_sockets; i++) {
873                 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
874                 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
875         }
876
877         // Wait for the main thread to finish
878
879         pthread_join(mesh->thread, NULL);
880 }
881
882 void meshlink_close(meshlink_handle_t *mesh) {
883         if(!mesh || !mesh->confbase) {
884                 meshlink_errno = MESHLINK_EINVAL;
885                 return;
886         }
887
888         // Close and free all resources used.
889
890         close_network_connections(mesh);
891
892         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
893
894         exit_configuration(&mesh->config);
895         event_loop_exit(&mesh->loop);
896
897 #ifdef HAVE_MINGW
898         if(mesh->confbase)
899                 WSACleanup();
900 #endif
901
902         ecdsa_free(mesh->invitation_key);
903
904         free(mesh->name);
905         free(mesh->confbase);
906
907         memset(mesh, 0, sizeof *mesh);
908
909         free(mesh);
910 }
911
912 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
913         if(!mesh) {
914                 meshlink_errno = MESHLINK_EINVAL;
915                 return;
916         }
917
918         mesh->receive_cb = cb;
919 }
920
921 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
922         if(!mesh) {
923                 meshlink_errno = MESHLINK_EINVAL;
924                 return;
925         }
926
927         mesh->node_status_cb = cb;
928 }
929
930 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
931         if(!mesh) {
932                 meshlink_errno = MESHLINK_EINVAL;
933                 return;
934         }
935
936         mesh->log_cb = cb;
937         mesh->log_level = level;
938 }
939
940 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
941         if(!mesh || !destination) {
942                 meshlink_errno = MESHLINK_EINVAL;
943                 return false;
944         }
945
946         if(!len)
947                 return true;
948
949         if(!data) {
950                 meshlink_errno = MESHLINK_EINVAL;
951                 return false;
952         }
953
954         /* If there is no outgoing list yet, create one. */
955
956         if(!mesh->outpacketqueue)
957                 mesh->outpacketqueue = list_alloc(NULL);
958
959         //add packet to the queue
960         outpacketqueue_t *packet_in_queue = xzalloc(sizeof *packet_in_queue);
961         packet_in_queue->destination=destination;
962         packet_in_queue->data=data;
963         packet_in_queue->len=len;
964         pthread_mutex_lock(&(mesh->outpacketqueue_mutex));
965         list_insert_head(mesh->outpacketqueue,packet_in_queue);
966         pthread_mutex_unlock(&(mesh->outpacketqueue_mutex));
967
968         //notify event loop
969         signal_trigger(&(mesh->loop),&(mesh->datafromapp));
970         return true;
971 }
972
973 void meshlink_send_from_queue(event_loop_t* el,meshlink_handle_t *mesh) {
974         vpn_packet_t packet;
975         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
976
977         outpacketqueue_t* p = list_get_tail(mesh->outpacketqueue);
978         if (p)
979         list_delete_tail(mesh->outpacketqueue);
980         else return ;
981
982         if (sizeof(meshlink_packethdr_t) + p->len > MAXSIZE) {
983                 //log something
984                 return ;
985         }
986
987         packet.probe = false;
988         memset(hdr, 0, sizeof *hdr);
989         memcpy(hdr->destination, p->destination->name, sizeof hdr->destination);
990         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
991
992         packet.len = sizeof *hdr + p->len;
993         memcpy(packet.data + sizeof *hdr, p->data, p->len);
994
995         mesh->self->in_packets++;
996         mesh->self->in_bytes += packet.len;
997         route(mesh, mesh->self, &packet);
998         return ;
999 }
1000
1001 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1002         if(!mesh || !destination) {
1003                 meshlink_errno = MESHLINK_EINVAL;
1004                 return -1;
1005         }
1006
1007         node_t *n = (node_t *)destination;
1008         if(!n->status.reachable)
1009                 return 0;
1010         else if(n->mtuprobes > 30 && n->minmtu)
1011                 return n->minmtu;
1012         else
1013                 return MTU;
1014 }
1015
1016 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1017         if(!mesh || !node) {
1018                 meshlink_errno = MESHLINK_EINVAL;
1019                 return NULL;
1020         }
1021
1022         node_t *n = (node_t *)node;
1023
1024         if(!node_read_ecdsa_public_key(mesh, n) || !n->ecdsa) {
1025                 meshlink_errno = MESHLINK_EINTERNAL;
1026                 return false;
1027         }
1028
1029         char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1030
1031         if(!fingerprint)
1032                 meshlink_errno = MESHLINK_EINTERNAL;
1033
1034         return fingerprint;
1035 }
1036
1037 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1038         if(!mesh || !name) {
1039                 meshlink_errno = MESHLINK_EINVAL;
1040                 return NULL;
1041         }
1042
1043         return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1044 }
1045
1046 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1047         if(!mesh || !nmemb || (*nmemb && !nodes)) {
1048                 meshlink_errno = MESHLINK_EINVAL;
1049                 return NULL;
1050         }
1051
1052         meshlink_node_t **result;
1053
1054         //lock mesh->nodes
1055         pthread_mutex_lock(&(mesh->nodes_mutex));
1056
1057         *nmemb = mesh->nodes->count;
1058         result = realloc(nodes, *nmemb * sizeof *nodes);
1059
1060         if(result) {
1061                 meshlink_node_t **p = result;
1062                 for splay_each(node_t, n, mesh->nodes)
1063                         *p++ = (meshlink_node_t *)n;
1064         } else {
1065                 *nmemb = 0;
1066                 free(nodes);
1067                 meshlink_errno = MESHLINK_ENOMEM;
1068         }
1069
1070         pthread_mutex_unlock(&(mesh->nodes_mutex));
1071
1072         return result;
1073 }
1074
1075 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1076         if(!mesh || !data || !len || !signature || !siglen) {
1077                 meshlink_errno = MESHLINK_EINVAL;
1078                 return false;
1079         }
1080
1081         if(*siglen < MESHLINK_SIGLEN) {
1082                 meshlink_errno = MESHLINK_EINVAL;
1083                 return false;
1084         }
1085
1086         if(!ecdsa_sign(mesh->self->connection->ecdsa, data, len, signature)) {
1087                 meshlink_errno = MESHLINK_EINTERNAL;
1088                 return false;
1089         }
1090
1091         *siglen = MESHLINK_SIGLEN;
1092         return true;
1093 }
1094
1095 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1096         if(!mesh || !data || !len || !signature) {
1097                 meshlink_errno = MESHLINK_EINVAL;
1098                 return false;
1099         }
1100
1101         if(siglen != MESHLINK_SIGLEN) {
1102                 meshlink_errno = MESHLINK_EINVAL;
1103                 return false;
1104         }
1105
1106         struct node_t *n = (struct node_t *)source;
1107         node_read_ecdsa_public_key(mesh, n);
1108         if(!n->ecdsa) {
1109                 meshlink_errno = MESHLINK_EINTERNAL;
1110                 return false;
1111         }
1112
1113         return ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1114 }
1115
1116 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1117         char filename[PATH_MAX];
1118
1119         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
1120         if(mkdir(filename, 0700) && errno != EEXIST) {
1121                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
1122                 meshlink_errno = MESHLINK_ESTORAGE;
1123                 return false;
1124         }
1125
1126         // Count the number of valid invitations, clean up old ones
1127         DIR *dir = opendir(filename);
1128         if(!dir) {
1129                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
1130                 meshlink_errno = MESHLINK_ESTORAGE;
1131                 return false;
1132         }
1133
1134         errno = 0;
1135         int count = 0;
1136         struct dirent *ent;
1137         time_t deadline = time(NULL) - 604800; // 1 week in the past
1138
1139         while((ent = readdir(dir))) {
1140                 if(strlen(ent->d_name) != 24)
1141                         continue;
1142                 char invname[PATH_MAX];
1143                 struct stat st;
1144                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
1145                 if(!stat(invname, &st)) {
1146                         if(mesh->invitation_key && deadline < st.st_mtime)
1147                                 count++;
1148                         else
1149                                 unlink(invname);
1150                 } else {
1151                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
1152                         errno = 0;
1153                 }
1154         }
1155
1156         if(errno) {
1157                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
1158                 closedir(dir);
1159                 meshlink_errno = MESHLINK_ESTORAGE;
1160                 return false;
1161         }
1162
1163         closedir(dir);
1164
1165         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
1166
1167         // Remove the key if there are no outstanding invitations.
1168         if(!count) {
1169                 unlink(filename);
1170                 if(mesh->invitation_key) {
1171                         ecdsa_free(mesh->invitation_key);
1172                         mesh->invitation_key = NULL;
1173                 }
1174         }
1175
1176         if(mesh->invitation_key)
1177                 return true;
1178
1179         // Create a new key if necessary.
1180         FILE *f = fopen(filename, "r");
1181         if(!f) {
1182                 if(errno != ENOENT) {
1183                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
1184                         meshlink_errno = MESHLINK_ESTORAGE;
1185                         return false;
1186                 }
1187
1188                 mesh->invitation_key = ecdsa_generate();
1189                 if(!mesh->invitation_key) {
1190                         fprintf(stderr, "Could not generate a new key!\n");
1191                         meshlink_errno = MESHLINK_EINTERNAL;
1192                         return false;
1193                 }
1194                 f = fopen(filename, "w");
1195                 if(!f) {
1196                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
1197                         meshlink_errno = MESHLINK_ESTORAGE;
1198                         return false;
1199                 }
1200                 chmod(filename, 0600);
1201                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
1202                 fclose(f);
1203         } else {
1204                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
1205                 fclose(f);
1206                 if(!mesh->invitation_key) {
1207                         fprintf(stderr, "Could not read private key from %s\n", filename);
1208                         meshlink_errno = MESHLINK_ESTORAGE;
1209                 }
1210         }
1211
1212         return mesh->invitation_key;
1213 }
1214
1215 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1216         if(!mesh || !address) {
1217                 meshlink_errno = MESHLINK_EINVAL;
1218                 return false;
1219         }
1220
1221         for(const char *p = address; *p; p++) {
1222                 if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
1223                         continue;
1224                 fprintf(stderr, "Invalid character in address: %s\n", address);
1225                 meshlink_errno = MESHLINK_EINVAL;
1226                 return false;
1227         }
1228
1229         return append_config_file(mesh, mesh->self->name, "Address", address);
1230 }
1231
1232 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1233         if(!mesh) {
1234                 meshlink_errno = MESHLINK_EINVAL;
1235                 return NULL;
1236         }
1237
1238         // Check validity of the new node's name
1239         if(!check_id(name)) {
1240                 fprintf(stderr, "Invalid name for node.\n");
1241                 meshlink_errno = MESHLINK_EINVAL;
1242                 return NULL;
1243         }
1244
1245         // Ensure no host configuration file with that name exists
1246         char filename[PATH_MAX];
1247         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1248         if(!access(filename, F_OK)) {
1249                 fprintf(stderr, "A host config file for %s already exists!\n", name);
1250                 meshlink_errno = MESHLINK_EEXIST;
1251                 return NULL;
1252         }
1253
1254         // Ensure no other nodes know about this name
1255         if(meshlink_get_node(mesh, name)) {
1256                 fprintf(stderr, "A node with name %s is already known!\n", name);
1257                 meshlink_errno = MESHLINK_EEXIST;
1258                 return NULL;
1259         }
1260
1261         // Get the local address
1262         char *address = get_my_hostname(mesh);
1263         if(!address) {
1264                 fprintf(stderr, "No Address known for ourselves!\n");
1265                 meshlink_errno = MESHLINK_ERESOLV;
1266                 return NULL;
1267         }
1268
1269         if(!refresh_invitation_key(mesh)) {
1270                 meshlink_errno = MESHLINK_EINTERNAL;
1271                 return NULL;
1272         }
1273
1274         char hash[64];
1275
1276         // Create a hash of the key.
1277         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1278         sha512(fingerprint, strlen(fingerprint), hash);
1279         b64encode_urlsafe(hash, hash, 18);
1280
1281         // Create a random cookie for this invitation.
1282         char cookie[25];
1283         randomize(cookie, 18);
1284
1285         // Create a filename that doesn't reveal the cookie itself
1286         char buf[18 + strlen(fingerprint)];
1287         char cookiehash[64];
1288         memcpy(buf, cookie, 18);
1289         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1290         sha512(buf, sizeof buf, cookiehash);
1291         b64encode_urlsafe(cookiehash, cookiehash, 18);
1292
1293         b64encode_urlsafe(cookie, cookie, 18);
1294
1295         free(fingerprint);
1296
1297         // Create a file containing the details of the invitation.
1298         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1299         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1300         if(!ifd) {
1301                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1302                 meshlink_errno = MESHLINK_ESTORAGE;
1303                 return NULL;
1304         }
1305         FILE *f = fdopen(ifd, "w");
1306         if(!f)
1307                 abort();
1308
1309         // Fill in the details.
1310         fprintf(f, "Name = %s\n", name);
1311         //if(netname)
1312         //      fprintf(f, "NetName = %s\n", netname);
1313         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1314
1315         // Copy Broadcast and Mode
1316         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1317         FILE *tc = fopen(filename,  "r");
1318         if(tc) {
1319                 char buf[1024];
1320                 while(fgets(buf, sizeof buf, tc)) {
1321                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1322                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1323                                 fputs(buf, f);
1324                                 // Make sure there is a newline character.
1325                                 if(!strchr(buf, '\n'))
1326                                         fputc('\n', f);
1327                         }
1328                 }
1329                 fclose(tc);
1330         } else {
1331                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1332                 meshlink_errno = MESHLINK_ESTORAGE;
1333                 return NULL;
1334         }
1335
1336         fprintf(f, "#---------------------------------------------------------------#\n");
1337         fprintf(f, "Name = %s\n", mesh->self->name);
1338
1339         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1340         fcopy(f, filename);
1341         fclose(f);
1342
1343         // Create an URL from the local address, key hash and cookie
1344         char *url;
1345         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1346         free(address);
1347
1348         return url;
1349 }
1350
1351 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1352         if(!mesh || !invitation) {
1353                 meshlink_errno = MESHLINK_EINVAL;
1354                 return false;
1355         }
1356
1357         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1358         char copy[strlen(invitation) + 1];
1359         strcpy(copy, invitation);
1360
1361         // Split the invitation URL into hostname, port, key hash and cookie.
1362
1363         char *slash = strchr(copy, '/');
1364         if(!slash)
1365                 goto invalid;
1366
1367         *slash++ = 0;
1368
1369         if(strlen(slash) != 48)
1370                 goto invalid;
1371
1372         char *address = copy;
1373         char *port = NULL;
1374         if(*address == '[') {
1375                 address++;
1376                 char *bracket = strchr(address, ']');
1377                 if(!bracket)
1378                         goto invalid;
1379                 *bracket = 0;
1380                 if(bracket[1] == ':')
1381                         port = bracket + 2;
1382         } else {
1383                 port = strchr(address, ':');
1384                 if(port)
1385                         *port++ = 0;
1386         }
1387
1388         if(!port)
1389                 port = "655";
1390
1391         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1392                 goto invalid;
1393
1394         // Generate a throw-away key for the invitation.
1395         ecdsa_t *key = ecdsa_generate();
1396         if(!key) {
1397                 meshlink_errno = MESHLINK_EINTERNAL;
1398                 return false;
1399         }
1400
1401         char *b64key = ecdsa_get_base64_public_key(key);
1402
1403         //Before doing meshlink_join make sure we are not connected to another mesh
1404         if ( mesh->threadstarted ){
1405                 goto invalid;
1406         }
1407
1408         // Connect to the meshlink daemon mentioned in the URL.
1409         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1410         if(!ai) {
1411                 meshlink_errno = MESHLINK_ERESOLV;
1412                 return false;
1413         }
1414
1415         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1416         if(mesh->sock <= 0) {
1417                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1418                 freeaddrinfo(ai);
1419                 meshlink_errno = MESHLINK_ENETWORK;
1420                 return false;
1421         }
1422
1423         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1424                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1425                 closesocket(mesh->sock);
1426                 freeaddrinfo(ai);
1427                 meshlink_errno = MESHLINK_ENETWORK;
1428                 return false;
1429         }
1430
1431         freeaddrinfo(ai);
1432
1433         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1434
1435         // Tell him we have an invitation, and give him our throw-away key.
1436
1437         mesh->blen = 0;
1438
1439         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1440                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1441                 closesocket(mesh->sock);
1442                 meshlink_errno = MESHLINK_ENETWORK;
1443                 return false;
1444         }
1445
1446         free(b64key);
1447
1448         char hisname[4096] = "";
1449         int code, hismajor, hisminor = 0;
1450
1451         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) {
1452                 fprintf(stderr, "Cannot read greeting from peer\n");
1453                 closesocket(mesh->sock);
1454                 meshlink_errno = MESHLINK_ENETWORK;
1455                 return false;
1456         }
1457
1458         // Check if the hash of the key he gave us matches the hash in the URL.
1459         char *fingerprint = mesh->line + 2;
1460         char hishash[64];
1461         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1462                 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1463                 meshlink_errno = MESHLINK_EINTERNAL;
1464                 return false;
1465         }
1466         if(memcmp(hishash, mesh->hash, 18)) {
1467                 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1468                 meshlink_errno = MESHLINK_EPEER;
1469                 return false;
1470
1471         }
1472
1473         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1474         if(!hiskey) {
1475                 meshlink_errno = MESHLINK_EINTERNAL;
1476                 return false;
1477         }
1478
1479         // Start an SPTPS session
1480         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive)) {
1481                 meshlink_errno = MESHLINK_EINTERNAL;
1482                 return false;
1483         }
1484
1485         // Feed rest of input buffer to SPTPS
1486         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1487                 meshlink_errno = MESHLINK_EPEER;
1488                 return false;
1489         }
1490
1491         int len;
1492
1493         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1494                 if(len < 0) {
1495                         if(errno == EINTR)
1496                                 continue;
1497                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1498                         meshlink_errno = MESHLINK_ENETWORK;
1499                         return false;
1500                 }
1501
1502                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1503                         meshlink_errno = MESHLINK_EPEER;
1504                         return false;
1505                 }
1506         }
1507
1508         sptps_stop(&mesh->sptps);
1509         ecdsa_free(hiskey);
1510         ecdsa_free(key);
1511         closesocket(mesh->sock);
1512
1513         if(!mesh->success) {
1514                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1515                 meshlink_errno = MESHLINK_EPEER;
1516                 return false;
1517         }
1518
1519         return true;
1520
1521 invalid:
1522         fprintf(stderr, "Invalid invitation URL or you are already connected to a Mesh ?\n");
1523         meshlink_errno = MESHLINK_EINVAL;
1524         return false;
1525 }
1526
1527 char *meshlink_export(meshlink_handle_t *mesh) {
1528         if(!mesh) {
1529                 meshlink_errno = MESHLINK_EINVAL;
1530                 return NULL;
1531         }
1532
1533         char filename[PATH_MAX];
1534         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1535         FILE *f = fopen(filename, "r");
1536         if(!f) {
1537                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
1538                 meshlink_errno = MESHLINK_ESTORAGE;
1539                 return NULL;
1540         }
1541
1542         fseek(f, 0, SEEK_END);
1543         int fsize = ftell(f);
1544         rewind(f);
1545
1546         size_t len = fsize + 9 + strlen(mesh->self->name);
1547         char *buf = xmalloc(len);
1548         snprintf(buf, len, "Name = %s\n", mesh->self->name);
1549         if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
1550                 fprintf(stderr, "Error reading from %s: %s\n", filename, strerror(errno));
1551                 fclose(f);
1552                 meshlink_errno = MESHLINK_ESTORAGE;
1553                 return NULL;
1554         }
1555
1556         fclose(f);
1557         buf[len - 1] = 0;
1558         return buf;
1559 }
1560
1561 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1562         if(!mesh || !data) {
1563                 meshlink_errno = MESHLINK_EINVAL;
1564                 return false;
1565         }
1566
1567         if(strncmp(data, "Name = ", 7)) {
1568                 fprintf(stderr, "Invalid data\n");
1569                 meshlink_errno = MESHLINK_EPEER;
1570                 return false;
1571         }
1572
1573         char *end = strchr(data + 7, '\n');
1574         if(!end) {
1575                 fprintf(stderr, "Invalid data\n");
1576                 meshlink_errno = MESHLINK_EPEER;
1577                 return false;
1578         }
1579
1580         int len = end - (data + 7);
1581         char name[len + 1];
1582         memcpy(name, data + 7, len);
1583         name[len] = 0;
1584         if(!check_id(name)) {
1585                 fprintf(stderr, "Invalid Name\n");
1586                 meshlink_errno = MESHLINK_EPEER;
1587                 return false;
1588         }
1589
1590         char filename[PATH_MAX];
1591         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1592         if(!access(filename, F_OK)) {
1593                 fprintf(stderr, "File %s already exists, not importing\n", filename);
1594                 meshlink_errno = MESHLINK_EEXIST;
1595                 return false;
1596         }
1597
1598         if(errno != ENOENT) {
1599                 fprintf(stderr, "Error accessing %s: %s\n", filename, strerror(errno));
1600                 meshlink_errno = MESHLINK_ESTORAGE;
1601                 return false;
1602         }
1603
1604         FILE *f = fopen(filename, "w");
1605         if(!f) {
1606                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1607                 meshlink_errno = MESHLINK_ESTORAGE;
1608                 return false;
1609         }
1610
1611         fwrite(end + 1, strlen(end + 1), 1, f);
1612         fclose(f);
1613
1614         load_all_nodes(mesh);
1615
1616         return true;
1617 }
1618
1619 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1620         if(!mesh || !node) {
1621                 meshlink_errno = MESHLINK_EINVAL;
1622                 return;
1623         }
1624
1625         node_t *n;
1626         n = (node_t*)node;
1627         n->status.blacklisted=true;
1628         fprintf(stderr, "Blacklisted %s.\n",node->name);
1629
1630         //Make blacklisting persistent in the config file
1631         append_config_file(mesh, n->name, "blacklisted", "yes");
1632
1633         return;
1634 }
1635
1636 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1637         if(!mesh || !node) {
1638                 meshlink_errno = MESHLINK_EINVAL;
1639                 return;
1640         }
1641
1642         node_t *n = (node_t *)node;
1643         n->status.blacklisted = false;
1644
1645         //TODO: remove blacklisted = yes from the config file
1646
1647         return;
1648 }
1649
1650 static void __attribute__((constructor)) meshlink_init(void) {
1651         crypto_init();
1652 }
1653
1654 static void __attribute__((destructor)) meshlink_exit(void) {
1655         crypto_exit();
1656 }