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