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