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