Fix more memory leaks found by ASAN.
[tinc] / src / invitation.c
1 /*
2     invitation.c -- Create and accept invitations
3     Copyright (C) 2013-2017 Guus Sliepen <guus@tinc-vpn.org>
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
20 #include "system.h"
21
22 #include "control_common.h"
23 #include "crypto.h"
24 #include "ecdsa.h"
25 #include "ecdsagen.h"
26 #include "ifconfig.h"
27 #include "invitation.h"
28 #include "names.h"
29 #include "netutl.h"
30 #include "rsagen.h"
31 #include "script.h"
32 #include "sptps.h"
33 #include "subnet.h"
34 #include "tincctl.h"
35 #include "utils.h"
36 #include "xalloc.h"
37
38 #include "ed25519/sha512.h"
39
40 int addressfamily = AF_UNSPEC;
41
42 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
43         if(!filename || (*hostname && *port)) {
44                 return;
45         }
46
47         FILE *f = fopen(filename, "r");
48
49         if(!f) {
50                 return;
51         }
52
53         while(fgets(line, sizeof(line), f)) {
54                 if(!rstrip(line)) {
55                         continue;
56                 }
57
58                 char *p = line, *q;
59                 p += strcspn(p, "\t =");
60
61                 if(!*p) {
62                         continue;
63                 }
64
65                 q = p + strspn(p, "\t ");
66
67                 if(*q == '=') {
68                         q += 1 + strspn(q + 1, "\t ");
69                 }
70
71                 *p = 0;
72                 p = q + strcspn(q, "\t ");
73
74                 if(*p) {
75                         *p++ = 0;
76                 }
77
78                 p += strspn(p, "\t ");
79                 p[strcspn(p, "\t ")] = 0;
80
81                 if(!*port && !strcasecmp(line, "Port")) {
82                         *port = xstrdup(q);
83                 } else if(!*hostname && !strcasecmp(line, "Address")) {
84                         *hostname = xstrdup(q);
85
86                         if(*p) {
87                                 free(*port);
88                                 *port = xstrdup(p);
89                         }
90                 }
91
92                 if(*hostname && *port) {
93                         break;
94                 }
95         }
96
97         fclose(f);
98 }
99
100 char *get_my_hostname() {
101         char *hostname = NULL;
102         char *port = NULL;
103         char *hostport = NULL;
104         char *name = get_my_name(false);
105         char filename[PATH_MAX] = {0};
106
107         // Use first Address statement in own host config file
108         if(check_id(name)) {
109                 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, name);
110                 scan_for_hostname(filename, &hostname, &port);
111                 scan_for_hostname(tinc_conf, &hostname, &port);
112         }
113
114         free(name);
115         name = NULL;
116
117         if(hostname) {
118                 goto done;
119         }
120
121         // If that doesn't work, guess externally visible hostname
122         fprintf(stderr, "Trying to discover externally visible hostname...\n");
123         struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
124         struct addrinfo *aip = ai;
125         static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
126
127         while(aip) {
128                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
129
130                 if(s >= 0) {
131                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
132                                 closesocket(s);
133                                 s = -1;
134                         }
135                 }
136
137                 if(s >= 0) {
138                         send(s, request, sizeof(request) - 1, 0);
139                         int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
140
141                         if(len > 0) {
142                                 line[len] = 0;
143
144                                 if(line[len - 1] == '\n') {
145                                         line[--len] = 0;
146                                 }
147
148                                 char *p = strrchr(line, '\n');
149
150                                 if(p && p[1]) {
151                                         hostname = xstrdup(p + 1);
152                                 }
153                         }
154
155                         closesocket(s);
156
157                         if(hostname) {
158                                 break;
159                         }
160                 }
161
162                 aip = aip->ai_next;
163                 continue;
164         }
165
166         if(ai) {
167                 freeaddrinfo(ai);
168         }
169
170         // Check that the hostname is reasonable
171         if(hostname) {
172                 for(char *p = hostname; *p; p++) {
173                         if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':') {
174                                 continue;
175                         }
176
177                         // If not, forget it.
178                         free(hostname);
179                         hostname = NULL;
180                         break;
181                 }
182         }
183
184         if(!tty) {
185                 if(!hostname) {
186                         fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
187                         free(port);
188                         return NULL;
189                 }
190
191                 goto save;
192         }
193
194 again:
195         fprintf(stderr, "Please enter your host's external address or hostname");
196
197         if(hostname) {
198                 fprintf(stderr, " [%s]", hostname);
199         }
200
201         fprintf(stderr, ": ");
202
203         if(!fgets(line, sizeof(line), stdin)) {
204                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
205                 free(hostname);
206                 free(port);
207                 return NULL;
208         }
209
210         if(!rstrip(line)) {
211                 if(hostname) {
212                         goto save;
213                 } else {
214                         goto again;
215                 }
216         }
217
218         for(char *p = line; *p; p++) {
219                 if(isalnum(*p) || *p == '-' || *p == '.') {
220                         continue;
221                 }
222
223                 fprintf(stderr, "Invalid address or hostname.\n");
224                 goto again;
225         }
226
227         free(hostname);
228         hostname = xstrdup(line);
229
230 save:
231
232         if(*filename) {
233                 FILE *f = fopen(filename, "a");
234
235                 if(f) {
236                         fprintf(f, "\nAddress = %s\n", hostname);
237                         fclose(f);
238                 } else {
239                         fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
240                 }
241         }
242
243 done:
244
245         if(port) {
246                 if(strchr(hostname, ':')) {
247                         xasprintf(&hostport, "[%s]:%s", hostname, port);
248                 } else {
249                         xasprintf(&hostport, "%s:%s", hostname, port);
250                 }
251         } else {
252                 if(strchr(hostname, ':')) {
253                         xasprintf(&hostport, "[%s]", hostname);
254                 } else {
255                         hostport = xstrdup(hostname);
256                 }
257         }
258
259         free(hostname);
260         free(port);
261         return hostport;
262 }
263
264 static bool fcopy(FILE *out, const char *filename) {
265         FILE *in = fopen(filename, "r");
266
267         if(!in) {
268                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
269                 return false;
270         }
271
272         char buf[1024];
273         size_t len;
274
275         while((len = fread(buf, 1, sizeof(buf), in))) {
276                 fwrite(buf, len, 1, out);
277         }
278
279         fclose(in);
280         return true;
281 }
282
283 int cmd_invite(int argc, char *argv[]) {
284         if(argc < 2) {
285                 fprintf(stderr, "Not enough arguments!\n");
286                 return 1;
287         }
288
289         // Check validity of the new node's name
290         if(!check_id(argv[1])) {
291                 fprintf(stderr, "Invalid name for node.\n");
292                 return 1;
293         }
294
295         free(myname);
296         myname = get_my_name(true);
297
298         if(!myname) {
299                 return 1;
300         }
301
302         // Ensure no host configuration file with that name exists
303         char filename[PATH_MAX];
304         snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
305
306         if(!access(filename, F_OK)) {
307                 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
308                 return 1;
309         }
310
311         // If a daemon is running, ensure no other nodes know about this name
312         if(connect_tincd(false)) {
313                 bool found = false;
314                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
315
316                 while(recvline(fd, line, sizeof(line))) {
317                         char node[4096];
318                         int code, req;
319
320                         if(sscanf(line, "%d %d %4095s", &code, &req, node) != 3) {
321                                 break;
322                         }
323
324                         if(!strcmp(node, argv[1])) {
325                                 found = true;
326                         }
327                 }
328
329                 if(found) {
330                         fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
331                         return 1;
332                 }
333         }
334
335         snprintf(filename, sizeof(filename), "%s" SLASH "invitations", confbase);
336
337         if(mkdir(filename, 0700) && errno != EEXIST) {
338                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
339                 return 1;
340         }
341
342         // Count the number of valid invitations, clean up old ones
343         DIR *dir = opendir(filename);
344
345         if(!dir) {
346                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
347                 return 1;
348         }
349
350         errno = 0;
351         int count = 0;
352         struct dirent *ent;
353         time_t deadline = time(NULL) - 604800; // 1 week in the past
354
355         while((ent = readdir(dir))) {
356                 if(strlen(ent->d_name) != 24) {
357                         continue;
358                 }
359
360                 char invname[PATH_MAX];
361                 struct stat st;
362
363                 if((size_t)snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= sizeof(invname)) {
364                         fprintf(stderr, "Filename too long: %s" SLASH "%s\n", filename, ent->d_name);
365                         continue;
366                 }
367
368                 if(!stat(invname, &st)) {
369                         if(deadline < st.st_mtime) {
370                                 count++;
371                         } else {
372                                 unlink(invname);
373                         }
374                 } else {
375                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
376                         errno = 0;
377                 }
378         }
379
380         closedir(dir);
381
382         if(errno) {
383                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
384                 return 1;
385         }
386
387         ecdsa_t *key;
388         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
389
390         // Remove the key if there are no outstanding invitations.
391         if(!count) {
392                 unlink(filename);
393         }
394
395         // Create a new key if necessary.
396         FILE *f = fopen(filename, "r");
397
398         if(!f) {
399                 if(errno != ENOENT) {
400                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
401                         return 1;
402                 }
403
404                 key = ecdsa_generate();
405
406                 if(!key) {
407                         return 1;
408                 }
409
410                 f = fopen(filename, "w");
411
412                 if(!f) {
413                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
414                         free(key);
415                         return 1;
416                 }
417
418                 chmod(filename, 0600);
419
420                 if(!ecdsa_write_pem_private_key(key, f)) {
421                         fprintf(stderr, "Could not write ECDSA private key\n");
422                         fclose(f);
423                         free(key);
424                         return 1;
425                 }
426
427                 fclose(f);
428
429                 if(connect_tincd(true)) {
430                         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
431                 } else {
432                         fprintf(stderr, "Could not signal the tinc daemon. Please restart or reload it manually.\n");
433                 }
434         } else {
435                 key = ecdsa_read_pem_private_key(f);
436                 fclose(f);
437
438                 if(!key) {
439                         fprintf(stderr, "Could not read private key from %s\n", filename);
440                 }
441         }
442
443         if(!key) {
444                 return 1;
445         }
446
447         // Create a hash of the key.
448         char hash[64];
449         char *fingerprint = ecdsa_get_base64_public_key(key);
450         sha512(fingerprint, strlen(fingerprint), hash);
451         b64encode_urlsafe(hash, hash, 18);
452
453         free(key);
454
455         // Create a random cookie for this invitation.
456         char cookie[25];
457         randomize(cookie, 18);
458
459         // Create a filename that doesn't reveal the cookie itself
460         char buf[18 + strlen(fingerprint)];
461         char cookiehash[64];
462         memcpy(buf, cookie, 18);
463         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
464         sha512(buf, sizeof(buf), cookiehash);
465         b64encode_urlsafe(cookiehash, cookiehash, 18);
466
467         free(fingerprint);
468
469         b64encode_urlsafe(cookie, cookie, 18);
470
471         // Create a file containing the details of the invitation.
472         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
473         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
474
475         if(!ifd) {
476                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
477                 return 1;
478         }
479
480         f = fdopen(ifd, "w");
481
482         if(!f) {
483                 abort();
484         }
485
486         // Get the local address
487         char *address = get_my_hostname();
488
489         // Fill in the details.
490         fprintf(f, "Name = %s\n", argv[1]);
491
492         if(check_netname(netname, true)) {
493                 fprintf(f, "NetName = %s\n", netname);
494         }
495
496         fprintf(f, "ConnectTo = %s\n", myname);
497
498         // Copy Broadcast and Mode
499         FILE *tc = fopen(tinc_conf, "r");
500
501         if(tc) {
502                 char buf[1024];
503
504                 while(fgets(buf, sizeof(buf), tc)) {
505                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
506                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
507                                 fputs(buf, f);
508
509                                 // Make sure there is a newline character.
510                                 if(!strchr(buf, '\n')) {
511                                         fputc('\n', f);
512                                 }
513                         }
514                 }
515
516                 fclose(tc);
517         }
518
519         fprintf(f, "#---------------------------------------------------------------#\n");
520         fprintf(f, "Name = %s\n", myname);
521
522         char filename2[PATH_MAX];
523         snprintf(filename2, sizeof(filename2), "%s" SLASH "hosts" SLASH "%s", confbase, myname);
524         fcopy(f, filename2);
525         fclose(f);
526
527         // Create an URL from the local address, key hash and cookie
528         char *url;
529         xasprintf(&url, "%s/%s%s", address, hash, cookie);
530
531         // Call the inviation-created script
532         environment_t env;
533         environment_init(&env);
534         environment_add(&env, "NODE=%s", argv[1]);
535         environment_add(&env, "INVITATION_FILE=%s", filename);
536         environment_add(&env, "INVITATION_URL=%s", url);
537         execute_script("invitation-created", &env);
538         environment_exit(&env);
539
540         puts(url);
541         free(url);
542         free(address);
543
544         return 0;
545 }
546
547 static int sock;
548 static char cookie[18];
549 static sptps_t sptps;
550 static char *data;
551 static size_t datalen;
552 static bool success = false;
553
554 static char cookie[18], hash[18];
555
556 static char *get_line(const char **data) {
557         if(!data || !*data) {
558                 return NULL;
559         }
560
561         if(! **data) {
562                 *data = NULL;
563                 return NULL;
564         }
565
566         static char line[1024];
567         const char *end = strchr(*data, '\n');
568         size_t len = end ? (size_t)(end - *data) : strlen(*data);
569
570         if(len >= sizeof(line)) {
571                 fprintf(stderr, "Maximum line length exceeded!\n");
572                 return NULL;
573         }
574
575         if(len && !isprint(**data)) {
576                 abort();
577         }
578
579         memcpy(line, *data, len);
580         line[len] = 0;
581
582         if(end) {
583                 *data = end + 1;
584         } else {
585                 *data = NULL;
586         }
587
588         return line;
589 }
590
591 static char *get_value(const char *data, const char *var) {
592         char *line = get_line(&data);
593
594         if(!line) {
595                 return NULL;
596         }
597
598         char *sep = line + strcspn(line, " \t=");
599         char *val = sep + strspn(sep, " \t");
600
601         if(*val == '=') {
602                 val += 1 + strspn(val + 1, " \t");
603         }
604
605         *sep = 0;
606
607         if(strcasecmp(line, var)) {
608                 return NULL;
609         }
610
611         return val;
612 }
613
614 static char *grep(const char *data, const char *var) {
615         static char value[1024];
616
617         const char *p = data;
618         int varlen = strlen(var);
619
620         // Skip all lines not starting with var
621         while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
622                 p = strchr(p, '\n');
623
624                 if(!p) {
625                         break;
626                 } else {
627                         p++;
628                 }
629         }
630
631         if(!p) {
632                 return NULL;
633         }
634
635         p += varlen;
636         p += strspn(p, " \t");
637
638         if(*p == '=') {
639                 p += 1 + strspn(p + 1, " \t");
640         }
641
642         const char *e = strchr(p, '\n');
643
644         if(!e) {
645                 return xstrdup(p);
646         }
647
648         if((size_t)(e - p) >= sizeof(value)) {
649                 fprintf(stderr, "Maximum line length exceeded!\n");
650                 return NULL;
651         }
652
653         memcpy(value, p, e - p);
654         value[e - p] = 0;
655         return value;
656 }
657
658 static bool finalize_join(void) {
659         const char *temp_name = get_value(data, "Name");
660
661         if(!temp_name) {
662                 fprintf(stderr, "No Name found in invitation!\n");
663                 return false;
664         }
665
666         size_t len = strlen(temp_name);
667         char name[len + 1];
668         memcpy(name, temp_name, len);
669         name[len] = 0;
670
671         if(!check_id(name)) {
672                 fprintf(stderr, "Invalid Name found in invitation!\n");
673                 return false;
674         }
675
676         if(!netname) {
677                 netname = grep(data, "NetName");
678
679                 if(netname && !check_netname(netname, true)) {
680                         fprintf(stderr, "Unsafe NetName found in invitation!\n");
681                         return false;
682                 }
683         }
684
685         bool ask_netname = false;
686         char temp_netname[32];
687
688 make_names:
689
690         if(!confbasegiven) {
691                 free(confbase);
692                 confbase = NULL;
693         }
694
695         make_names(false);
696
697         free(tinc_conf);
698         free(hosts_dir);
699
700         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
701         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
702
703         if(!access(tinc_conf, F_OK)) {
704                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
705
706                 if(confbasegiven) {
707                         return false;
708                 }
709
710                 // Generate a random netname, ask for a better one later.
711                 ask_netname = true;
712                 snprintf(temp_netname, sizeof(temp_netname), "join_%x", rand());
713                 netname = temp_netname;
714                 goto make_names;
715         }
716
717         if(mkdir(confbase, 0777) && errno != EEXIST) {
718                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
719                 return false;
720         }
721
722         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
723                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
724                 return false;
725         }
726
727         FILE *f = fopen(tinc_conf, "w");
728
729         if(!f) {
730                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
731                 return false;
732         }
733
734         fprintf(f, "Name = %s\n", name);
735
736         char filename[PATH_MAX];
737         snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, name);
738         FILE *fh = fopen(filename, "w");
739
740         if(!fh) {
741                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
742                 fclose(f);
743                 return false;
744         }
745
746         snprintf(filename, sizeof(filename), "%s" SLASH "invitation-data", confbase);
747         FILE *finv = fopen(filename, "w");
748
749         if(!finv || fwrite(data, datalen, 1, finv) != 1) {
750                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
751                 fclose(fh);
752                 fclose(f);
753                 fclose(finv);
754                 return false;
755         }
756
757         fclose(finv);
758
759         snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
760         FILE *fup = fopen(filename, "w");
761
762         if(!fup) {
763                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
764                 fclose(f);
765                 fclose(fh);
766                 return false;
767         }
768
769         ifconfig_header(fup);
770
771         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
772         // Generate a tinc-up script from Ifconfig and Route keywords.
773         // Other chunks go unfiltered to their respective host config files
774         const char *p = data;
775         char *l, *value;
776
777         while((l = get_line(&p))) {
778                 // Ignore comments
779                 if(*l == '#') {
780                         continue;
781                 }
782
783                 // Split line into variable and value
784                 int len = strcspn(l, "\t =");
785                 value = l + len;
786                 value += strspn(value, "\t ");
787
788                 if(*value == '=') {
789                         value++;
790                         value += strspn(value, "\t ");
791                 }
792
793                 l[len] = 0;
794
795                 // Ignore lines with empty variable names
796                 if(!*l) {
797                         continue;
798                 }
799
800                 // Is it a Name?
801                 if(!strcasecmp(l, "Name")) {
802                         if(strcmp(value, name)) {
803                                 break;
804                         } else {
805                                 continue;
806                         }
807                 } else if(!strcasecmp(l, "NetName")) {
808                         continue;
809                 }
810
811                 // Check the list of known variables
812                 bool found = false;
813                 int i;
814
815                 for(i = 0; variables[i].name; i++) {
816                         if(strcasecmp(l, variables[i].name)) {
817                                 continue;
818                         }
819
820                         found = true;
821                         break;
822                 }
823
824                 // Handle Ifconfig and Route statements
825                 if(!found) {
826                         if(!strcasecmp(l, "Ifconfig")) {
827                                 if(!strcasecmp(value, "dhcp")) {
828                                         ifconfig_dhcp(fup);
829                                 } else if(!strcasecmp(value, "dhcp6")) {
830                                         ifconfig_dhcp6(fup);
831                                 } else if(!strcasecmp(value, "slaac")) {
832                                         ifconfig_slaac(fup);
833                                 } else {
834                                         ifconfig_address(fup, value);
835                                 }
836
837                                 continue;
838                         } else if(!strcasecmp(l, "Route")) {
839                                 ifconfig_route(fup, value);
840                                 continue;
841                         }
842                 }
843
844                 // Ignore unknown and unsafe variables
845                 if(!found) {
846                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
847                         continue;
848                 } else if(!(variables[i].type & VAR_SAFE)) {
849                         if(force) {
850                                 fprintf(stderr, "Warning: unsafe variable '%s' in invitation.\n", l);
851                         } else {
852                                 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
853                                 continue;
854                         }
855                 }
856
857                 // Copy the safe variable to the right config file
858                 fprintf((variables[i].type & VAR_HOST) ? fh : f, "%s = %s\n", l, value);
859         }
860
861         fclose(f);
862         bool valid_tinc_up = ifconfig_footer(fup);
863         fclose(fup);
864
865         while(l && !strcasecmp(l, "Name")) {
866                 if(!check_id(value)) {
867                         fprintf(stderr, "Invalid Name found in invitation.\n");
868                         return false;
869                 }
870
871                 if(!strcmp(value, name)) {
872                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
873                         return false;
874                 }
875
876                 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, value);
877                 f = fopen(filename, "w");
878
879                 if(!f) {
880                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
881                         return false;
882                 }
883
884                 while((l = get_line(&p))) {
885                         if(!strcmp(l, "#---------------------------------------------------------------#")) {
886                                 continue;
887                         }
888
889                         int len = strcspn(l, "\t =");
890
891                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
892                                 value = l + len;
893                                 value += strspn(value, "\t ");
894
895                                 if(*value == '=') {
896                                         value++;
897                                         value += strspn(value, "\t ");
898                                 }
899
900                                 l[len] = 0;
901                                 break;
902                         }
903
904                         fputs(l, f);
905                         fputc('\n', f);
906                 }
907
908                 fclose(f);
909         }
910
911         // Generate our key and send a copy to the server
912         ecdsa_t *key = ecdsa_generate();
913
914         if(!key) {
915                 return false;
916         }
917
918         char *b64key = ecdsa_get_base64_public_key(key);
919
920         if(!b64key) {
921                 return false;
922         }
923
924         snprintf(filename, sizeof(filename), "%s" SLASH "ed25519_key.priv", confbase);
925         f = fopenmask(filename, "w", 0600);
926
927         if(!f) {
928                 return false;
929         }
930
931         if(!ecdsa_write_pem_private_key(key, f)) {
932                 fprintf(stderr, "Error writing private key!\n");
933                 ecdsa_free(key);
934                 fclose(f);
935                 return false;
936         }
937
938         fclose(f);
939
940         fprintf(fh, "Ed25519PublicKey = %s\n", b64key);
941
942         sptps_send_record(&sptps, 1, b64key, strlen(b64key));
943         free(b64key);
944         ecdsa_free(key);
945
946 #ifndef DISABLE_LEGACY
947         rsa_t *rsa = rsa_generate(2048, 0x1001);
948         snprintf(filename, sizeof(filename), "%s" SLASH "rsa_key.priv", confbase);
949         f = fopenmask(filename, "w", 0600);
950
951         if(!f || !rsa_write_pem_private_key(rsa, f)) {
952                 fprintf(stderr, "Could not write private RSA key\n");
953         } else if(!rsa_write_pem_public_key(rsa, fh)) {
954                 fprintf(stderr, "Could not write public RSA key\n");
955         }
956
957         fclose(f);
958
959         fclose(fh);
960
961         rsa_free(rsa);
962 #endif
963
964         check_port(name);
965
966 ask_netname:
967
968         if(ask_netname && tty) {
969                 fprintf(stderr, "Enter a new netname: ");
970
971                 if(!fgets(line, sizeof(line), stdin)) {
972                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
973                         return false;
974                 }
975
976                 if(!*line || *line == '\n') {
977                         goto ask_netname;
978                 }
979
980                 line[strlen(line) - 1] = 0;
981
982                 char newbase[PATH_MAX];
983
984                 if((size_t)snprintf(newbase, sizeof(newbase), CONFDIR SLASH "tinc" SLASH "%s", line) >= sizeof(newbase)) {
985                         fprintf(stderr, "Filename too long: " CONFDIR SLASH "tinc" SLASH "%s\n", line);
986                         goto ask_netname;
987                 }
988
989                 if(rename(confbase, newbase)) {
990                         fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
991                         goto ask_netname;
992                 }
993
994                 netname = line;
995                 make_names(false);
996         }
997
998         char filename2[PATH_MAX];
999         snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
1000
1001 #ifdef HAVE_MINGW
1002         snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up.bat", confbase);
1003 #else
1004         snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up", confbase);
1005 #endif
1006
1007         if(valid_tinc_up) {
1008                 if(tty) {
1009                         FILE *fup = fopen(filename, "r");
1010
1011                         if(fup) {
1012                                 fprintf(stderr, "\nPlease review the following tinc-up script:\n\n");
1013
1014                                 char buf[MAXSIZE];
1015
1016                                 while(fgets(buf, sizeof(buf), fup)) {
1017                                         fputs(buf, stderr);
1018                                 }
1019
1020                                 fclose(fup);
1021
1022                                 int response = 0;
1023
1024                                 do {
1025                                         fprintf(stderr, "\nDo you want to use this script [y]es/[n]o/[e]dit? ");
1026                                         response = tolower(getchar());
1027                                 } while(!strchr("yne", response));
1028
1029                                 fprintf(stderr, "\n");
1030
1031                                 if(response == 'e') {
1032                                         char *command;
1033 #ifndef HAVE_MINGW
1034                                         const char *editor = getenv("VISUAL");
1035
1036                                         if(!editor) {
1037                                                 editor = getenv("EDITOR");
1038                                         }
1039
1040                                         if(!editor) {
1041                                                 editor = "vi";
1042                                         }
1043
1044                                         xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1045 #else
1046                                         xasprintf(&command, "edit \"%s\"", filename);
1047 #endif
1048
1049                                         if(system(command)) {
1050                                                 response = 'n';
1051                                         } else {
1052                                                 response = 'y';
1053                                         }
1054
1055                                         free(command);
1056                                 }
1057
1058                                 if(response == 'y') {
1059                                         rename(filename, filename2);
1060                                         chmod(filename2, 0755);
1061                                         fprintf(stderr, "tinc-up enabled.\n");
1062                                 } else {
1063                                         fprintf(stderr, "tinc-up has been left disabled.\n");
1064                                 }
1065                         }
1066                 } else {
1067                         if(force) {
1068                                 rename(filename, filename2);
1069                                 chmod(filename2, 0755);
1070                                 fprintf(stderr, "tinc-up enabled.\n");
1071                         } else {
1072                                 fprintf(stderr, "A tinc-up script was generated, but has been left disabled.\n");
1073                         }
1074                 }
1075         } else {
1076                 // A placeholder was generated.
1077                 rename(filename, filename2);
1078                 chmod(filename2, 0755);
1079         }
1080
1081         fprintf(stderr, "Configuration stored in: %s\n", confbase);
1082
1083         return true;
1084 }
1085
1086
1087 static bool invitation_send(void *handle, uint8_t type, const void *vdata, size_t len) {
1088         (void)handle;
1089         (void)type;
1090         const char *data = vdata;
1091
1092         while(len) {
1093                 int result = send(sock, data, len, 0);
1094
1095                 if(result == -1 && sockwouldblock(sockerrno)) {
1096                         continue;
1097                 } else if(result <= 0) {
1098                         return false;
1099                 }
1100
1101                 data += result;
1102                 len -= result;
1103         }
1104
1105         return true;
1106 }
1107
1108 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
1109         (void)handle;
1110
1111         switch(type) {
1112         case SPTPS_HANDSHAKE:
1113                 return sptps_send_record(&sptps, 0, cookie, sizeof(cookie));
1114
1115         case 0:
1116                 data = xrealloc(data, datalen + len + 1);
1117                 memcpy(data + datalen, msg, len);
1118                 datalen += len;
1119                 data[datalen] = 0;
1120                 break;
1121
1122         case 1:
1123                 return finalize_join();
1124
1125         case 2:
1126                 fprintf(stderr, "Invitation successfully accepted.\n");
1127                 shutdown(sock, SHUT_RDWR);
1128                 success = true;
1129                 break;
1130
1131         default:
1132                 return false;
1133         }
1134
1135         return true;
1136 }
1137
1138 int cmd_join(int argc, char *argv[]) {
1139         free(data);
1140         data = NULL;
1141         datalen = 0;
1142
1143         if(argc > 2) {
1144                 fprintf(stderr, "Too many arguments!\n");
1145                 return 1;
1146         }
1147
1148         // Make sure confbase exists and is accessible.
1149         if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1150                 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1151                 return 1;
1152         }
1153
1154         if(mkdir(confbase, 0777) && errno != EEXIST) {
1155                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1156                 return 1;
1157         }
1158
1159         if(access(confbase, R_OK | W_OK | X_OK)) {
1160                 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
1161                 return 1;
1162         }
1163
1164         // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
1165         if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
1166                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1167                 return 1;
1168         }
1169
1170         // Either read the invitation from the command line or from stdin.
1171         char *invitation;
1172
1173         if(argc > 1) {
1174                 invitation = argv[1];
1175         } else {
1176                 if(tty) {
1177                         fprintf(stderr, "Enter invitation URL: ");
1178                 }
1179
1180                 errno = EPIPE;
1181
1182                 if(!fgets(line, sizeof(line), stdin)) {
1183                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1184                         return false;
1185                 }
1186
1187                 invitation = line;
1188         }
1189
1190         // Parse the invitation URL.
1191         rstrip(line);
1192
1193         char *slash = strchr(invitation, '/');
1194
1195         if(!slash) {
1196                 goto invalid;
1197         }
1198
1199         *slash++ = 0;
1200
1201         if(strlen(slash) != 48) {
1202                 goto invalid;
1203         }
1204
1205         char *address = invitation;
1206         char *port = NULL;
1207
1208         if(*address == '[') {
1209                 address++;
1210                 char *bracket = strchr(address, ']');
1211
1212                 if(!bracket) {
1213                         goto invalid;
1214                 }
1215
1216                 *bracket = 0;
1217
1218                 if(bracket[1] == ':') {
1219                         port = bracket + 2;
1220                 }
1221         } else {
1222                 port = strchr(address, ':');
1223
1224                 if(port) {
1225                         *port++ = 0;
1226                 }
1227         }
1228
1229         if(!port || !*port) {
1230                 port = "655";
1231         }
1232
1233         if(!b64decode(slash, hash, 24) || !b64decode(slash + 24, cookie, 24)) {
1234                 goto invalid;
1235         }
1236
1237         // Generate a throw-away key for the invitation.
1238         ecdsa_t *key = ecdsa_generate();
1239
1240         if(!key) {
1241                 return 1;
1242         }
1243
1244         char *b64key = ecdsa_get_base64_public_key(key);
1245
1246         // Connect to the tinc daemon mentioned in the URL.
1247         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1248
1249         if(!ai) {
1250                 free(b64key);
1251                 return 1;
1252         }
1253
1254         struct addrinfo *aip = NULL;
1255
1256 next:
1257         if(!aip) {
1258                 aip = ai;
1259         } else {
1260                 aip = aip->ai_next;
1261
1262                 if(!aip) {
1263                         freeaddrinfo(ai);
1264                         free(b64key);
1265                         return 1;
1266                 }
1267         }
1268
1269         sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1270
1271         if(sock <= 0) {
1272                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1273                 goto next;
1274         }
1275
1276         if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
1277                 char *addrstr, *portstr;
1278                 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
1279                 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
1280                 free(addrstr);
1281                 free(portstr);
1282                 closesocket(sock);
1283                 goto next;
1284         }
1285
1286         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1287
1288         // Tell him we have an invitation, and give him our throw-away key.
1289         int len = snprintf(line, sizeof(line), "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
1290
1291         if(len <= 0 || (size_t)len >= sizeof(line)) {
1292                 abort();
1293         }
1294
1295         if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1296                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1297                 closesocket(sock);
1298                 goto next;
1299         }
1300
1301         char hisname[4096] = "";
1302         int code, hismajor, hisminor = 0;
1303
1304         if(!recvline(sock, line, sizeof(line)) || sscanf(line, "%d %4095s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(sock, line, sizeof(line)) || !rstrip(line) || sscanf(line, "%d ", &code) != 1 || code != ACK || strlen(line) < 3) {
1305                 fprintf(stderr, "Cannot read greeting from peer\n");
1306                 closesocket(sock);
1307                 goto next;
1308         }
1309
1310         freeaddrinfo(ai);
1311         ai = NULL;
1312         aip = NULL;
1313
1314         free(b64key);
1315         b64key = NULL;
1316
1317         // Check if the hash of the key he gave us matches the hash in the URL.
1318         char *fingerprint = line + 2;
1319         char hishash[64];
1320
1321         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1322                 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
1323                 return 1;
1324         }
1325
1326         if(memcmp(hishash, hash, 18)) {
1327                 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
1328                 return 1;
1329
1330         }
1331
1332         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1333
1334         if(!hiskey) {
1335                 return 1;
1336         }
1337
1338         // Start an SPTPS session
1339         if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive)) {
1340                 return 1;
1341         }
1342
1343         // Feed rest of input buffer to SPTPS
1344         if(!sptps_receive_data(&sptps, buffer, blen)) {
1345                 return 1;
1346         }
1347
1348         while((len = recv(sock, line, sizeof(line), 0))) {
1349                 if(len < 0) {
1350                         if(sockwouldblock(sockerrno)) {
1351                                 continue;
1352                         }
1353
1354 #if HAVE_MINGW
1355
1356                         // If socket has been shut down, recv() on Windows returns -1 and sets sockerrno
1357                         // to WSAESHUTDOWN, while on UNIX-like operating systems recv() returns 0, so we
1358                         // have to do an explicit check here.
1359                         if(sockshutdown(sockerrno)) {
1360                                 break;
1361                         }
1362
1363 #endif
1364                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, sockstrerror(sockerrno));
1365                         return 1;
1366                 }
1367
1368                 char *p = line;
1369
1370                 while(len) {
1371                         int done = sptps_receive_data(&sptps, p, len);
1372
1373                         if(!done) {
1374                                 return 1;
1375                         }
1376
1377                         len -= done;
1378                         p += done;
1379                 }
1380         }
1381
1382         sptps_stop(&sptps);
1383         ecdsa_free(hiskey);
1384         ecdsa_free(key);
1385         closesocket(sock);
1386
1387         if(!success) {
1388                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1389                 return 1;
1390         }
1391
1392         return 0;
1393
1394 invalid:
1395         fprintf(stderr, "Invalid invitation URL.\n");
1396         return 1;
1397 }