]> git.meshlink.io Git - meshlink/blob - src/meshlink.c
Allow MeshLink to be cross-compiled for Windows.
[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(!tty) {
240         //      if(!hostname) {
241         //              fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
242         //              return NULL;
243         //      }
244         //      goto save;
245         //}
246
247 again:
248         fprintf(stderr, "Please enter your host's external address or hostname");
249         if(hostname)
250                 fprintf(stderr, " [%s]", hostname);
251         fprintf(stderr, ": ");
252
253         if(!fgets(line, sizeof line, stdin)) {
254                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
255                 free(hostname);
256                 return NULL;
257         }
258
259         if(!rstrip(line)) {
260                 if(hostname)
261                         goto save;
262                 else
263                         goto again;
264         }
265
266         for(char *p = line; *p; p++) {
267                 if(isalnum(*p) || *p == '-' || *p == '.')
268                         continue;
269                 fprintf(stderr, "Invalid address or hostname.\n");
270                 goto again;
271         }
272
273         free(hostname);
274         hostname = xstrdup(line);
275
276 save:
277         f = fopen(filename, "a");
278         if(f) {
279                 fprintf(f, "\nAddress = %s\n", hostname);
280                 fclose(f);
281         } else {
282                 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
283         }
284
285 done:
286         if(port) {
287                 if(strchr(hostname, ':'))
288                         xasprintf(&hostport, "[%s]:%s", hostname, port);
289                 else
290                         xasprintf(&hostport, "%s:%s", hostname, port);
291         } else {
292                 if(strchr(hostname, ':'))
293                         xasprintf(&hostport, "[%s]", hostname);
294                 else
295                         hostport = xstrdup(hostname);
296         }
297
298         free(hostname);
299         free(port);
300         return hostport;
301 }
302
303 static char *get_line(const char **data) {
304         if(!data || !*data)
305                 return NULL;
306
307         if(!**data) {
308                 *data = NULL;
309                 return NULL;
310         }
311
312         static char line[1024];
313         const char *end = strchr(*data, '\n');
314         size_t len = end ? end - *data : strlen(*data);
315         if(len >= sizeof line) {
316                 fprintf(stderr, "Maximum line length exceeded!\n");
317                 return NULL;
318         }
319         if(len && !isprint(**data))
320                 abort();
321
322         memcpy(line, *data, len);
323         line[len] = 0;
324
325         if(end)
326                 *data = end + 1;
327         else
328                 *data = NULL;
329
330         return line;
331 }
332
333 static char *get_value(const char *data, const char *var) {
334         char *line = get_line(&data);
335         if(!line)
336                 return NULL;
337
338         char *sep = line + strcspn(line, " \t=");
339         char *val = sep + strspn(sep, " \t");
340         if(*val == '=')
341                 val += 1 + strspn(val + 1, " \t");
342         *sep = 0;
343         if(strcasecmp(line, var))
344                 return NULL;
345         return val;
346 }
347
348 static bool try_bind(int port) {
349         struct addrinfo *ai = NULL;
350         struct addrinfo hint = {
351                 .ai_flags = AI_PASSIVE,
352                 .ai_family = AF_UNSPEC,
353                 .ai_socktype = SOCK_STREAM,
354                 .ai_protocol = IPPROTO_TCP,
355         };
356
357         char portstr[16];
358         snprintf(portstr, sizeof portstr, "%d", port);
359
360         if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai)
361                 return false;
362
363         while(ai) {
364                 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
365                 if(!fd)
366                         return false;
367                 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
368                 closesocket(fd);
369                 if(result)
370                         return false;
371                 ai = ai->ai_next;
372         }
373
374         return true;
375 }
376
377 static int check_port(meshlink_handle_t *mesh) {
378         if(try_bind(655))
379                 return 655;
380
381         fprintf(stderr, "Warning: could not bind to port 655.\n");
382
383         for(int i = 0; i < 100; i++) {
384                 int port = 0x1000 + (rand() & 0x7fff);
385                 if(try_bind(port)) {
386                         char filename[PATH_MAX];
387                         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
388                         FILE *f = fopen(filename, "a");
389                         if(!f) {
390                                 fprintf(stderr, "Please change MeshLink's Port manually.\n");
391                                 return 0;
392                         }
393
394                         fprintf(f, "Port = %d\n", port);
395                         fclose(f);
396                         fprintf(stderr, "MeshLink will instead listen on port %d.\n", port);
397                         return port;
398                 }
399         }
400
401         fprintf(stderr, "Please change MeshLink's Port manually.\n");
402         return 0;
403 }
404
405 static bool finalize_join(meshlink_handle_t *mesh) {
406         char *name = xstrdup(get_value(mesh->data, "Name"));
407         if(!name) {
408                 fprintf(stderr, "No Name found in invitation!\n");
409                 return false;
410         }
411
412         if(!check_id(name)) {
413                 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
414                 return false;
415         }
416
417         char filename[PATH_MAX];
418         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
419
420         FILE *f = fopen(filename, "w");
421         if(!f) {
422                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
423                 return false;
424         }
425
426         fprintf(f, "Name = %s\n", name);
427
428         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
429         FILE *fh = fopen(filename, "w");
430         if(!fh) {
431                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
432                 fclose(f);
433                 return false;
434         }
435
436         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
437         // Other chunks go unfiltered to their respective host config files
438         const char *p = mesh->data;
439         char *l, *value;
440
441         while((l = get_line(&p))) {
442                 // Ignore comments
443                 if(*l == '#')
444                         continue;
445
446                 // Split line into variable and value
447                 int len = strcspn(l, "\t =");
448                 value = l + len;
449                 value += strspn(value, "\t ");
450                 if(*value == '=') {
451                         value++;
452                         value += strspn(value, "\t ");
453                 }
454                 l[len] = 0;
455
456                 // Is it a Name?
457                 if(!strcasecmp(l, "Name"))
458                         if(strcmp(value, name))
459                                 break;
460                         else
461                                 continue;
462                 else if(!strcasecmp(l, "NetName"))
463                         continue;
464
465                 // Check the list of known variables //TODO: most variables will not be available in meshlink, only name and key will be absolutely necessary
466                 bool found = false;
467                 int i;
468                 for(i = 0; variables[i].name; i++) {
469                         if(strcasecmp(l, variables[i].name))
470                                 continue;
471                         found = true;
472                         break;
473                 }
474
475                 // Ignore unknown and unsafe variables
476                 if(!found) {
477                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
478                         continue;
479                 } else if(!(variables[i].type & VAR_SAFE)) {
480                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
481                         continue;
482                 }
483
484                 // Copy the safe variable to the right config file
485                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
486         }
487
488         fclose(f);
489
490         while(l && !strcasecmp(l, "Name")) {
491                 if(!check_id(value)) {
492                         fprintf(stderr, "Invalid Name found in invitation.\n");
493                         return false;
494                 }
495
496                 if(!strcmp(value, name)) {
497                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
498                         return false;
499                 }
500
501                 snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, value);
502                 f = fopen(filename, "w");
503
504                 if(!f) {
505                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
506                         return false;
507                 }
508
509                 while((l = get_line(&p))) {
510                         if(!strcmp(l, "#---------------------------------------------------------------#"))
511                                 continue;
512                         int len = strcspn(l, "\t =");
513                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
514                                 value = l + len;
515                                 value += strspn(value, "\t ");
516                                 if(*value == '=') {
517                                         value++;
518                                         value += strspn(value, "\t ");
519                                 }
520                                 l[len] = 0;
521                                 break;
522                         }
523
524                         fputs(l, f);
525                         fputc('\n', f);
526                 }
527
528                 fclose(f);
529         }
530
531         char *b64key = ecdsa_get_base64_public_key(mesh->self->connection->ecdsa);
532         if(!b64key)
533                 return false;
534
535         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
536         fprintf(fh, "Port = %s\n", mesh->myport);
537
538         fclose(fh);
539
540         sptps_send_record(&(mesh->sptps), 1, b64key, strlen(b64key));
541         free(b64key);
542
543         free(mesh->self->name);
544         free(mesh->self->connection->name);
545         mesh->self->name = xstrdup(name);
546         mesh->self->connection->name = xstrdup(name);
547
548         fprintf(stderr, "Configuration stored in: %s\n", mesh->confbase);
549
550         load_all_nodes(mesh);
551
552         return true;
553 }
554
555 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
556         meshlink_handle_t* mesh = handle;
557         while(len) {
558                 int result = send(mesh->sock, data, len, 0);
559                 if(result == -1 && errno == EINTR)
560                         continue;
561                 else if(result <= 0)
562                         return false;
563                 data += result;
564                 len -= result;
565         }
566         return true;
567 }
568
569 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
570         meshlink_handle_t* mesh = handle;
571         switch(type) {
572                 case SPTPS_HANDSHAKE:
573                         return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof mesh->cookie);
574
575                 case 0:
576                         mesh->data = xrealloc(mesh->data, mesh->thedatalen + len + 1);
577                         memcpy(mesh->data + mesh->thedatalen, msg, len);
578                         mesh->thedatalen += len;
579                         mesh->data[mesh->thedatalen] = 0;
580                         break;
581
582                 case 1:
583                         return finalize_join(mesh);
584
585                 case 2:
586                         fprintf(stderr, "Invitation succesfully accepted.\n");
587                         shutdown(mesh->sock, SHUT_RDWR);
588                         mesh->success = true;
589                         break;
590
591                 default:
592                         return false;
593         }
594
595         return true;
596 }
597
598 static bool recvline(meshlink_handle_t* mesh, size_t len) {
599         char *newline = NULL;
600
601         if(!mesh->sock)
602                 abort();
603
604         while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
605                 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof mesh->buffer - mesh->blen, 0);
606                 if(result == -1 && errno == EINTR)
607                         continue;
608                 else if(result <= 0)
609                         return false;
610                 mesh->blen += result;
611         }
612
613         if(newline - mesh->buffer >= len)
614                 return false;
615
616         len = newline - mesh->buffer;
617
618         memcpy(mesh->line, mesh->buffer, len);
619         mesh->line[len] = 0;
620         memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
621         mesh->blen -= len + 1;
622
623         return true;
624 }
625 static bool sendline(int fd, char *format, ...) {
626         static char buffer[4096];
627         char *p = buffer;
628         int blen = 0;
629         va_list ap;
630
631         va_start(ap, format);
632         blen = vsnprintf(buffer, sizeof buffer, format, ap);
633         va_end(ap);
634
635         if(blen < 1 || blen >= sizeof buffer)
636                 return false;
637
638         buffer[blen] = '\n';
639         blen++;
640
641         while(blen) {
642                 int result = send(fd, p, blen, MSG_NOSIGNAL);
643                 if(result == -1 && errno == EINTR)
644                         continue;
645                 else if(result <= 0)
646                         return false;
647                 p += result;
648                 blen -= result;
649         }
650
651         return true;
652 }
653
654 static const char *errstr[] = {
655         [MESHLINK_OK] = "No error",
656         [MESHLINK_ENOMEM] = "Out of memory",
657         [MESHLINK_ENOENT] = "No such node",
658 };
659
660 const char *meshlink_strerror(meshlink_errno_t errno) {
661         return errstr[errno];
662 }
663
664 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
665         ecdsa_t *key;
666         FILE *f;
667         char pubname[PATH_MAX], privname[PATH_MAX];
668
669         fprintf(stderr, "Generating ECDSA keypair:\n");
670
671         if(!(key = ecdsa_generate())) {
672                 fprintf(stderr, "Error during key generation!\n");
673                 return false;
674         } else
675                 fprintf(stderr, "Done.\n");
676
677         snprintf(privname, sizeof privname, "%s" SLASH "ecdsa_key.priv", mesh->confbase);
678         f = fopen(privname, "w");
679
680         if(!f)
681                 return false;
682
683 #ifdef HAVE_FCHMOD
684         fchmod(fileno(f), 0600);
685 #endif
686
687         if(!ecdsa_write_pem_private_key(key, f)) {
688                 fprintf(stderr, "Error writing private key!\n");
689                 ecdsa_free(key);
690                 fclose(f);
691                 return false;
692         }
693
694         fclose(f);
695
696
697         snprintf(pubname, sizeof pubname, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->name);
698         f = fopen(pubname, "a");
699
700         if(!f)
701                 return false;
702
703         char *pubkey = ecdsa_get_base64_public_key(key);
704         fprintf(f, "ECDSAPublicKey = %s\n", pubkey);
705         free(pubkey);
706
707         fclose(f);
708         ecdsa_free(key);
709
710         return true;
711 }
712
713 static bool meshlink_setup(meshlink_handle_t *mesh) {
714         if(mkdir(mesh->confbase, 0777) && errno != EEXIST) {
715                 fprintf(stderr, "Could not create directory %s: %s\n", mesh->confbase, strerror(errno));
716                 return false;
717         }
718
719         char filename[PATH_MAX];
720         snprintf(filename, sizeof filename, "%s" SLASH "hosts", mesh->confbase);
721
722         if(mkdir(filename, 0777) && errno != EEXIST) {
723                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
724                 return false;
725         }
726
727         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
728
729         if(!access(filename, F_OK)) {
730                 fprintf(stderr, "Configuration file %s already exists!\n", filename);
731                 return false;
732         }
733
734         FILE *f = fopen(filename, "w");
735         if(!f) {
736                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
737                 return 1;
738         }
739
740         fprintf(f, "Name = %s\n", mesh->name);
741         fclose(f);
742
743         if(!ecdsa_keygen(mesh))
744                 return false;
745
746         check_port(mesh);
747
748         return true;
749 }
750
751 meshlink_handle_t *meshlink_open(const char *confbase, const char *name) {
752         // Validate arguments provided by the application
753
754         if(!confbase || !*confbase) {
755                 fprintf(stderr, "No confbase given!\n");
756                 return NULL;
757         }
758
759         if(!name || !*name) {
760                 fprintf(stderr, "No name given!\n");
761                 return NULL;
762         }
763
764         if(!check_id(name)) {
765                 fprintf(stderr, "Invalid name given!\n");
766                 return NULL;
767         }
768
769         meshlink_handle_t *mesh = xzalloc(sizeof *mesh);
770         mesh->confbase = xstrdup(confbase);
771         mesh->name = xstrdup(name);
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                         meshlink_setup(mesh);
787                 } else {
788                         fprintf(stderr, "Cannot not read from %s: %s\n", filename, strerror(errno));
789                         return meshlink_close(mesh), NULL;
790                 }
791         }
792
793         // Read the configuration
794
795         init_configuration(&mesh->config);
796
797         if(!read_server_config(mesh))
798                 return meshlink_close(mesh), NULL;
799
800         // Setup up everything
801         // TODO: we should not open listening sockets yet
802
803         if(!setup_network(mesh))
804                 return meshlink_close(mesh), NULL;
805
806         return mesh;
807 }
808
809 void *meshlink_main_loop(void *arg) {
810         meshlink_handle_t *mesh = arg;
811
812         try_outgoing_connections(mesh);
813
814         main_loop(mesh);
815
816         return NULL;
817 }
818
819 bool meshlink_start(meshlink_handle_t *mesh) {
820         // TODO: open listening sockets first
821
822         // Start the main thread
823
824         if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
825                 fprintf(stderr, "Could not start thread: %s\n", strerror(errno));
826                 memset(&mesh->thread, 0, sizeof mesh->thread);
827                 return false;
828         }
829
830         return true;
831 }
832
833 void meshlink_stop(meshlink_handle_t *mesh) {
834         // Shut down the listening sockets to signal the main thread to shut down
835
836         for(int i = 0; i < mesh->listen_sockets; i++) {
837                 shutdown(mesh->listen_socket[i].tcp.fd, SHUT_RDWR);
838                 shutdown(mesh->listen_socket[i].udp.fd, SHUT_RDWR);
839         }
840
841         // Wait for the main thread to finish
842
843         pthread_join(mesh->thread, NULL);
844 }
845
846 void meshlink_close(meshlink_handle_t *mesh) {
847         // Close and free all resources used.
848
849         close_network_connections(mesh);
850
851         logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");
852
853         exit_configuration(&mesh->config);
854         event_loop_exit(&mesh->loop);
855 }
856
857 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
858         mesh->receive_cb = cb;
859 }
860
861 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
862         mesh->node_status_cb = cb;
863 }
864
865 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
866         mesh->log_cb = cb;
867         mesh->log_level = level;
868 }
869
870 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, unsigned int len) {
871         vpn_packet_t packet;
872         meshlink_packethdr_t *hdr = (meshlink_packethdr_t *)packet.data;
873         if (sizeof(meshlink_packethdr_t) + len > MAXSIZE) {
874                 //log something
875                 return false;
876         }
877
878         packet.probe = false;
879         memset(hdr, 0, sizeof *hdr);
880         memcpy(hdr->destination, destination->name, sizeof hdr->destination);
881         memcpy(hdr->source, mesh->self->name, sizeof hdr->source);
882
883         packet.len = sizeof *hdr + len;
884         memcpy(packet.data + sizeof *hdr, data, len);
885
886         mesh->self->in_packets++;
887         mesh->self->in_bytes += packet.len;
888         route(mesh, mesh->self, &packet);
889         return false;
890 }
891
892 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
893         return (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
894 }
895
896 size_t meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t nmemb) {
897         size_t i = 0;
898
899         for splay_each(node_t, n, mesh->nodes) {
900                 if(i < nmemb)
901                         nodes[i] = (meshlink_node_t *)n;
902                 i++;
903         }
904
905         return i;
906 }
907
908 char *meshlink_sign(meshlink_handle_t *mesh, const char *data, size_t len) {
909         return NULL;
910 }
911
912 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const char *data, size_t len, const char *signature) {
913         return false;
914 }
915
916 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
917         char filename[PATH_MAX];
918
919         snprintf(filename, sizeof filename, "%s" SLASH "invitations", mesh->confbase);
920         if(mkdir(filename, 0700) && errno != EEXIST) {
921                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
922                 return NULL;
923         }
924
925         // Count the number of valid invitations, clean up old ones
926         DIR *dir = opendir(filename);
927         if(!dir) {
928                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
929                 return NULL;
930         }
931
932         errno = 0;
933         int count = 0;
934         struct dirent *ent;
935         time_t deadline = time(NULL) - 604800; // 1 week in the past
936
937         while((ent = readdir(dir))) {
938                 if(strlen(ent->d_name) != 24)
939                         continue;
940                 char invname[PATH_MAX];
941                 struct stat st;
942                 snprintf(invname, sizeof invname, "%s" SLASH "%s", filename, ent->d_name);
943                 if(!stat(invname, &st)) {
944                         if(mesh->invitation_key && deadline < st.st_mtime)
945                                 count++;
946                         else
947                                 unlink(invname);
948                 } else {
949                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
950                         errno = 0;
951                 }
952         }
953
954         if(errno) {
955                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
956                 closedir(dir);
957                 return false;
958         }
959
960         closedir(dir);
961
962         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
963
964         // Remove the key if there are no outstanding invitations.
965         if(!count) {
966                 unlink(filename);
967                 if(mesh->invitation_key) {
968                         ecdsa_free(mesh->invitation_key);
969                         mesh->invitation_key = NULL;
970                 }
971         }
972
973         if(mesh->invitation_key)
974                 return true;
975
976         // Create a new key if necessary.
977         FILE *f = fopen(filename, "r");
978         if(!f) {
979                 if(errno != ENOENT) {
980                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
981                         return NULL;
982                 }
983
984                 mesh->invitation_key = ecdsa_generate();
985                 if(!mesh->invitation_key) {
986                         fprintf(stderr, "Could not generate a new key!\n");
987                         return NULL;
988                 }
989                 f = fopen(filename, "w");
990                 if(!f) {
991                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
992                         return NULL;
993                 }
994                 chmod(filename, 0600);
995                 ecdsa_write_pem_private_key(mesh->invitation_key, f);
996                 fclose(f);
997         } else {
998                 mesh->invitation_key = ecdsa_read_pem_private_key(f);
999                 fclose(f);
1000                 if(!mesh->invitation_key)
1001                         fprintf(stderr, "Could not read private key from %s\n", filename);
1002         }
1003
1004         return mesh->invitation_key;
1005 }
1006
1007 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1008         // Check validity of the new node's name
1009         if(!check_id(name)) {
1010                 fprintf(stderr, "Invalid name for node.\n");
1011                 return NULL;
1012         }
1013
1014         // Ensure no host configuration file with that name exists
1015         char filename[PATH_MAX];
1016         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
1017         if(!access(filename, F_OK)) {
1018                 fprintf(stderr, "A host config file for %s already exists!\n", name);
1019                 return NULL;
1020         }
1021
1022         // Ensure no other nodes know about this name
1023         if(meshlink_get_node(mesh, name)) {
1024                 fprintf(stderr, "A node with name %s is already known!\n", name);
1025                 return NULL;
1026         }
1027
1028         if(!refresh_invitation_key(mesh))
1029                 return NULL;
1030
1031         char hash[64];
1032
1033         // Create a hash of the key.
1034         char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1035         sha512(fingerprint, strlen(fingerprint), hash);
1036         b64encode_urlsafe(hash, hash, 18);
1037
1038         // Create a random cookie for this invitation.
1039         char cookie[25];
1040         randomize(cookie, 18);
1041
1042         // Create a filename that doesn't reveal the cookie itself
1043         char buf[18 + strlen(fingerprint)];
1044         char cookiehash[64];
1045         memcpy(buf, cookie, 18);
1046         memcpy(buf + 18, fingerprint, sizeof buf - 18);
1047         sha512(buf, sizeof buf, cookiehash);
1048         b64encode_urlsafe(cookiehash, cookiehash, 18);
1049
1050         b64encode_urlsafe(cookie, cookie, 18);
1051
1052         // Create a file containing the details of the invitation.
1053         snprintf(filename, sizeof filename, "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
1054         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
1055         if(!ifd) {
1056                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
1057                 return NULL;
1058         }
1059         FILE *f = fdopen(ifd, "w");
1060         if(!f)
1061                 abort();
1062
1063         // Get the local address
1064         char *address = get_my_hostname(mesh);
1065
1066         // Fill in the details.
1067         fprintf(f, "Name = %s\n", name);
1068         //if(netname)
1069         //      fprintf(f, "NetName = %s\n", netname);
1070         fprintf(f, "ConnectTo = %s\n", mesh->self->name);
1071
1072         // Copy Broadcast and Mode
1073         snprintf(filename, sizeof filename, "%s" SLASH "meshlink.conf", mesh->confbase);
1074         FILE *tc = fopen(filename,  "r");
1075         if(tc) {
1076                 char buf[1024];
1077                 while(fgets(buf, sizeof buf, tc)) {
1078                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
1079                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
1080                                 fputs(buf, f);
1081                                 // Make sure there is a newline character.
1082                                 if(!strchr(buf, '\n'))
1083                                         fputc('\n', f);
1084                         }
1085                 }
1086                 fclose(tc);
1087         } else {
1088                 fprintf(stderr, "Could not create %s: %s\n", filename, strerror(errno));
1089                 return NULL;
1090         }
1091
1092         fprintf(f, "#---------------------------------------------------------------#\n");
1093         fprintf(f, "Name = %s\n", mesh->self->name);
1094
1095         snprintf(filename, sizeof filename, "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
1096         fcopy(f, filename);
1097         fclose(f);
1098
1099         // Create an URL from the local address, key hash and cookie
1100         char *url;
1101         xasprintf(&url, "%s/%s%s", address, hash, cookie);
1102
1103         return url;
1104 }
1105
1106 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1107         //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1108         char copy[strlen(invitation) + 1];
1109         strcpy(copy, invitation);
1110
1111         // Split the invitation URL into hostname, port, key hash and cookie.
1112
1113         char *slash = strchr(copy, '/');
1114         if(!slash)
1115                 goto invalid;
1116
1117         *slash++ = 0;
1118
1119         if(strlen(slash) != 48)
1120                 goto invalid;
1121
1122         char *address = copy;
1123         char *port = NULL;
1124         if(*address == '[') {
1125                 address++;
1126                 char *bracket = strchr(address, ']');
1127                 if(!bracket)
1128                         goto invalid;
1129                 *bracket = 0;
1130                 if(bracket[1] == ':')
1131                         port = bracket + 2;
1132         } else {
1133                 port = strchr(address, ':');
1134                 if(port)
1135                         *port++ = 0;
1136         }
1137
1138         if(!*port)
1139                 port = "655";
1140
1141         if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18))
1142                 goto invalid;
1143
1144         // Generate a throw-away key for the invitation.
1145         ecdsa_t *key = ecdsa_generate();
1146         if(!key)
1147                 return false;
1148
1149         char *b64key = ecdsa_get_base64_public_key(key);
1150
1151         // Connect to the meshlink daemon mentioned in the URL.
1152         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1153         if(!ai)
1154                 return false;
1155
1156         mesh->sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1157         if(mesh->sock <= 0) {
1158                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1159                 return false;
1160         }
1161
1162         if(connect(mesh->sock, ai->ai_addr, ai->ai_addrlen)) {
1163                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1164                 closesocket(mesh->sock);
1165                 return false;
1166         }
1167
1168         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1169
1170         // Tell him we have an invitation, and give him our throw-away key.
1171
1172         mesh->blen = 0;
1173
1174         if(!sendline(mesh->sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1175                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1176                 closesocket(mesh->sock);
1177                 return false;
1178         }
1179
1180         char hisname[4096] = "";
1181         int code, hismajor, hisminor = 0;
1182
1183         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) {
1184                 fprintf(stderr, "Cannot read greeting from peer\n");
1185                 closesocket(mesh->sock);
1186                 return false;
1187         }
1188
1189         // Check if the hash of the key he gave us matches the hash in the URL.
1190         char *fingerprint = mesh->line + 2;
1191         char hishash[64];
1192         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1193                 fprintf(stderr, "Could not create hash\n%s\n", mesh->line + 2);
1194                 return false;
1195         }
1196         if(memcmp(hishash, mesh->hash, 18)) {
1197                 fprintf(stderr, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1198                 return false;
1199
1200         }
1201
1202         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1203         if(!hiskey)
1204                 return false;
1205
1206         // Start an SPTPS session
1207         if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, "meshlink invitation", 15, invitation_send, invitation_receive))
1208                 return false;
1209
1210         // Feed rest of input buffer to SPTPS
1211         if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen))
1212                 return false;
1213
1214         int len;
1215
1216         while((len = recv(mesh->sock, mesh->line, sizeof mesh->line, 0))) {
1217                 if(len < 0) {
1218                         if(errno == EINTR)
1219                                 continue;
1220                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1221                         return false;
1222                 }
1223
1224                 if(!sptps_receive_data(&mesh->sptps, mesh->line, len))
1225                         return false;
1226         }
1227
1228         sptps_stop(&mesh->sptps);
1229         ecdsa_free(hiskey);
1230         ecdsa_free(key);
1231         closesocket(mesh->sock);
1232
1233         if(!mesh->success) {
1234                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1235                 return false;
1236         }
1237
1238         return true;
1239
1240 invalid:
1241         fprintf(stderr, "Invalid invitation URL.\n");
1242         return false;
1243 }
1244
1245 char *meshlink_export(meshlink_handle_t *mesh) {
1246         return NULL;
1247 }
1248
1249 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
1250         return false;
1251 }
1252
1253 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
1254     node_t *n;
1255     n = (node_t*)node;
1256     n->status.blacklisted=true;
1257         fprintf(stderr, "Blacklisted %s.\n",node->name);
1258
1259         //Make blacklisting persistent in the config file
1260         append_config_file(mesh, n->name, "blacklisted", "yes");
1261     return;
1262
1263 }
1264
1265 static void __attribute__((constructor)) meshlink_init(void) {
1266         crypto_init();
1267 }
1268
1269 static void __attribute__((destructor)) meshlink_exit(void) {
1270         crypto_exit();
1271 }