bcb79a489b72bc654686e062cdbf341ef9dc6a50
[oweals/tinc.git] / 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(false)) {
418                         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
419                 }
420         } else {
421                 key = ecdsa_read_pem_private_key(f);
422                 fclose(f);
423
424                 if(!key) {
425                         fprintf(stderr, "Could not read private key from %s\n", filename);
426                 }
427         }
428
429         if(!key) {
430                 return 1;
431         }
432
433         // Create a hash of the key.
434         char hash[64];
435         char *fingerprint = ecdsa_get_base64_public_key(key);
436         sha512(fingerprint, strlen(fingerprint), hash);
437         b64encode_urlsafe(hash, hash, 18);
438
439         // Create a random cookie for this invitation.
440         char cookie[25];
441         randomize(cookie, 18);
442
443         // Create a filename that doesn't reveal the cookie itself
444         char buf[18 + strlen(fingerprint)];
445         char cookiehash[64];
446         memcpy(buf, cookie, 18);
447         memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
448         sha512(buf, sizeof(buf), cookiehash);
449         b64encode_urlsafe(cookiehash, cookiehash, 18);
450
451         b64encode_urlsafe(cookie, cookie, 18);
452
453         // Create a file containing the details of the invitation.
454         snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
455         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
456
457         if(!ifd) {
458                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
459                 return 1;
460         }
461
462         f = fdopen(ifd, "w");
463
464         if(!f) {
465                 abort();
466         }
467
468         // Get the local address
469         char *address = get_my_hostname();
470
471         // Fill in the details.
472         fprintf(f, "Name = %s\n", argv[1]);
473
474         if(check_netname(netname, true)) {
475                 fprintf(f, "NetName = %s\n", netname);
476         }
477
478         fprintf(f, "ConnectTo = %s\n", myname);
479
480         // Copy Broadcast and Mode
481         FILE *tc = fopen(tinc_conf, "r");
482
483         if(tc) {
484                 char buf[1024];
485
486                 while(fgets(buf, sizeof(buf), tc)) {
487                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
488                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
489                                 fputs(buf, f);
490
491                                 // Make sure there is a newline character.
492                                 if(!strchr(buf, '\n')) {
493                                         fputc('\n', f);
494                                 }
495                         }
496                 }
497
498                 fclose(tc);
499         }
500
501         fprintf(f, "#---------------------------------------------------------------#\n");
502         fprintf(f, "Name = %s\n", myname);
503
504         char filename2[PATH_MAX];
505         snprintf(filename2, sizeof(filename2), "%s" SLASH "hosts" SLASH "%s", confbase, myname);
506         fcopy(f, filename2);
507         fclose(f);
508
509         // Create an URL from the local address, key hash and cookie
510         char *url;
511         xasprintf(&url, "%s/%s%s", address, hash, cookie);
512
513         // Call the inviation-created script
514         environment_t env;
515         environment_init(&env);
516         environment_add(&env, "NODE=%s", argv[1]);
517         environment_add(&env, "INVITATION_FILE=%s", filename);
518         environment_add(&env, "INVITATION_URL=%s", url);
519         execute_script("invitation-created", &env);
520         environment_exit(&env);
521
522         puts(url);
523         free(url);
524         free(address);
525
526         return 0;
527 }
528
529 static int sock;
530 static char cookie[18];
531 static sptps_t sptps;
532 static char *data;
533 static size_t datalen;
534 static bool success = false;
535
536 static char cookie[18], hash[18];
537
538 static char *get_line(const char **data) {
539         if(!data || !*data) {
540                 return NULL;
541         }
542
543         if(! **data) {
544                 *data = NULL;
545                 return NULL;
546         }
547
548         static char line[1024];
549         const char *end = strchr(*data, '\n');
550         size_t len = end ? end - *data : strlen(*data);
551
552         if(len >= sizeof(line)) {
553                 fprintf(stderr, "Maximum line length exceeded!\n");
554                 return NULL;
555         }
556
557         if(len && !isprint(**data)) {
558                 abort();
559         }
560
561         memcpy(line, *data, len);
562         line[len] = 0;
563
564         if(end) {
565                 *data = end + 1;
566         } else {
567                 *data = NULL;
568         }
569
570         return line;
571 }
572
573 static char *get_value(const char *data, const char *var) {
574         char *line = get_line(&data);
575
576         if(!line) {
577                 return NULL;
578         }
579
580         char *sep = line + strcspn(line, " \t=");
581         char *val = sep + strspn(sep, " \t");
582
583         if(*val == '=') {
584                 val += 1 + strspn(val + 1, " \t");
585         }
586
587         *sep = 0;
588
589         if(strcasecmp(line, var)) {
590                 return NULL;
591         }
592
593         return val;
594 }
595
596 static char *grep(const char *data, const char *var) {
597         static char value[1024];
598
599         const char *p = data;
600         int varlen = strlen(var);
601
602         // Skip all lines not starting with var
603         while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
604                 p = strchr(p, '\n');
605
606                 if(!p) {
607                         break;
608                 } else {
609                         p++;
610                 }
611         }
612
613         if(!p) {
614                 return NULL;
615         }
616
617         p += varlen;
618         p += strspn(p, " \t");
619
620         if(*p == '=') {
621                 p += 1 + strspn(p + 1, " \t");
622         }
623
624         const char *e = strchr(p, '\n');
625
626         if(!e) {
627                 return xstrdup(p);
628         }
629
630         if(e - p >= sizeof(value)) {
631                 fprintf(stderr, "Maximum line length exceeded!\n");
632                 return NULL;
633         }
634
635         memcpy(value, p, e - p);
636         value[e - p] = 0;
637         return value;
638 }
639
640 static bool finalize_join(void) {
641         char *name = xstrdup(get_value(data, "Name"));
642
643         if(!name) {
644                 fprintf(stderr, "No Name found in invitation!\n");
645                 return false;
646         }
647
648         if(!check_id(name)) {
649                 fprintf(stderr, "Invalid Name found in invitation!\n");
650                 return false;
651         }
652
653         if(!netname) {
654                 netname = grep(data, "NetName");
655
656                 if(netname && !check_netname(netname, true)) {
657                         fprintf(stderr, "Unsafe NetName found in invitation!\n");
658                         return false;
659                 }
660         }
661
662         bool ask_netname = false;
663         char temp_netname[32];
664
665 make_names:
666
667         if(!confbasegiven) {
668                 free(confbase);
669                 confbase = NULL;
670         }
671
672         make_names(false);
673
674         free(tinc_conf);
675         free(hosts_dir);
676
677         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
678         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
679
680         if(!access(tinc_conf, F_OK)) {
681                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
682
683                 if(confbasegiven) {
684                         return false;
685                 }
686
687                 // Generate a random netname, ask for a better one later.
688                 ask_netname = true;
689                 snprintf(temp_netname, sizeof(temp_netname), "join_%x", rand());
690                 netname = temp_netname;
691                 goto make_names;
692         }
693
694         if(mkdir(confbase, 0777) && errno != EEXIST) {
695                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
696                 return false;
697         }
698
699         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
700                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
701                 return false;
702         }
703
704         FILE *f = fopen(tinc_conf, "w");
705
706         if(!f) {
707                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
708                 return false;
709         }
710
711         fprintf(f, "Name = %s\n", name);
712
713         char filename[PATH_MAX];
714         snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, name);
715         FILE *fh = fopen(filename, "w");
716
717         if(!fh) {
718                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
719                 fclose(f);
720                 return false;
721         }
722
723         snprintf(filename, sizeof(filename), "%s" SLASH "invitation-data", confbase);
724         FILE *finv = fopen(filename, "w");
725
726         if(!finv || fwrite(data, datalen, 1, finv) != 1) {
727                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
728                 fclose(fh);
729                 fclose(f);
730                 fclose(finv);
731                 return false;
732         }
733
734         fclose(finv);
735
736         snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
737         FILE *fup = fopen(filename, "w");
738
739         if(!fup) {
740                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
741                 fclose(f);
742                 fclose(fh);
743                 return false;
744         }
745
746         ifconfig_header(fup);
747
748         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
749         // Generate a tinc-up script from Ifconfig and Route keywords.
750         // Other chunks go unfiltered to their respective host config files
751         const char *p = data;
752         char *l, *value;
753
754         while((l = get_line(&p))) {
755                 // Ignore comments
756                 if(*l == '#') {
757                         continue;
758                 }
759
760                 // Split line into variable and value
761                 int len = strcspn(l, "\t =");
762                 value = l + len;
763                 value += strspn(value, "\t ");
764
765                 if(*value == '=') {
766                         value++;
767                         value += strspn(value, "\t ");
768                 }
769
770                 l[len] = 0;
771
772                 // Is it a Name?
773                 if(!strcasecmp(l, "Name"))
774                         if(strcmp(value, name)) {
775                                 break;
776                         } else {
777                                 continue;
778                         } else if(!strcasecmp(l, "NetName")) {
779                         continue;
780                 }
781
782                 // Check the list of known variables
783                 bool found = false;
784                 int i;
785
786                 for(i = 0; variables[i].name; i++) {
787                         if(strcasecmp(l, variables[i].name)) {
788                                 continue;
789                         }
790
791                         found = true;
792                         break;
793                 }
794
795                 // Handle Ifconfig and Route statements
796                 if(!found) {
797                         if(!strcasecmp(l, "Ifconfig")) {
798                                 if(!strcasecmp(value, "dhcp")) {
799                                         ifconfig_dhcp(fup);
800                                 } else if(!strcasecmp(value, "dhcp6")) {
801                                         ifconfig_dhcp6(fup);
802                                 } else if(!strcasecmp(value, "slaac")) {
803                                         ifconfig_slaac(fup);
804                                 } else {
805                                         ifconfig_address(fup, value);
806                                 }
807
808                                 continue;
809                         } else if(!strcasecmp(l, "Route")) {
810                                 ifconfig_route(fup, value);
811                                 continue;
812                         }
813                 }
814
815                 // Ignore unknown and unsafe variables
816                 if(!found) {
817                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
818                         continue;
819                 } else if(!(variables[i].type & VAR_SAFE)) {
820                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
821                         continue;
822                 }
823
824                 // Copy the safe variable to the right config file
825                 fprintf((variables[i].type & VAR_HOST) ? fh : f, "%s = %s\n", l, value);
826         }
827
828         fclose(f);
829         bool valid_tinc_up = ifconfig_footer(fup);
830         fclose(fup);
831
832         while(l && !strcasecmp(l, "Name")) {
833                 if(!check_id(value)) {
834                         fprintf(stderr, "Invalid Name found in invitation.\n");
835                         return false;
836                 }
837
838                 if(!strcmp(value, name)) {
839                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
840                         return false;
841                 }
842
843                 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, value);
844                 f = fopen(filename, "w");
845
846                 if(!f) {
847                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
848                         return false;
849                 }
850
851                 while((l = get_line(&p))) {
852                         if(!strcmp(l, "#---------------------------------------------------------------#")) {
853                                 continue;
854                         }
855
856                         int len = strcspn(l, "\t =");
857
858                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
859                                 value = l + len;
860                                 value += strspn(value, "\t ");
861
862                                 if(*value == '=') {
863                                         value++;
864                                         value += strspn(value, "\t ");
865                                 }
866
867                                 l[len] = 0;
868                                 break;
869                         }
870
871                         fputs(l, f);
872                         fputc('\n', f);
873                 }
874
875                 fclose(f);
876         }
877
878         // Generate our key and send a copy to the server
879         ecdsa_t *key = ecdsa_generate();
880
881         if(!key) {
882                 return false;
883         }
884
885         char *b64key = ecdsa_get_base64_public_key(key);
886
887         if(!b64key) {
888                 return false;
889         }
890
891         snprintf(filename, sizeof(filename), "%s" SLASH "ed25519_key.priv", confbase);
892         f = fopenmask(filename, "w", 0600);
893
894         if(!f) {
895                 return false;
896         }
897
898         if(!ecdsa_write_pem_private_key(key, f)) {
899                 fprintf(stderr, "Error writing private key!\n");
900                 ecdsa_free(key);
901                 fclose(f);
902                 return false;
903         }
904
905         fclose(f);
906
907         fprintf(fh, "Ed25519PublicKey = %s\n", b64key);
908
909         sptps_send_record(&sptps, 1, b64key, strlen(b64key));
910         free(b64key);
911         ecdsa_free(key);
912
913 #ifndef DISABLE_LEGACY
914         rsa_t *rsa = rsa_generate(2048, 0x1001);
915         snprintf(filename, sizeof(filename), "%s" SLASH "rsa_key.priv", confbase);
916         f = fopenmask(filename, "w", 0600);
917
918         if(!f || !rsa_write_pem_private_key(rsa, f)) {
919                 fprintf(stderr, "Could not write private RSA key\n");
920         } else if(!rsa_write_pem_public_key(rsa, fh)) {
921                 fprintf(stderr, "Could not write public RSA key\n");
922         }
923
924         fclose(f);
925
926         fclose(fh);
927
928         rsa_free(rsa);
929 #endif
930
931         check_port(name);
932
933 ask_netname:
934
935         if(ask_netname && tty) {
936                 fprintf(stderr, "Enter a new netname: ");
937
938                 if(!fgets(line, sizeof(line), stdin)) {
939                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
940                         return false;
941                 }
942
943                 if(!*line || *line == '\n') {
944                         goto ask_netname;
945                 }
946
947                 line[strlen(line) - 1] = 0;
948
949                 char newbase[PATH_MAX];
950                 snprintf(newbase, sizeof(newbase), CONFDIR SLASH "tinc" SLASH "%s", line);
951
952                 if(rename(confbase, newbase)) {
953                         fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
954                         goto ask_netname;
955                 }
956
957                 netname = line;
958                 make_names(false);
959         }
960
961         char filename2[PATH_MAX];
962         snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
963         snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up", confbase);
964
965         if(valid_tinc_up) {
966                 if(tty) {
967                         FILE *fup = fopen(filename, "r");
968
969                         if(fup) {
970                                 fprintf(stderr, "\nPlease review the following tinc-up script:\n\n");
971
972                                 char buf[MAXSIZE];
973
974                                 while(fgets(buf, sizeof(buf), fup)) {
975                                         fputs(buf, stderr);
976                                 }
977
978                                 fclose(fup);
979
980                                 int response = 0;
981
982                                 do {
983                                         fprintf(stderr, "\nDo you want to use this script [y]es/[n]o/[e]dit? ");
984                                         response = tolower(getchar());
985                                 } while(!strchr("yne", response));
986
987                                 fprintf(stderr, "\n");
988
989                                 if(response == 'e') {
990                                         char *command;
991 #ifndef HAVE_MINGW
992                                         xasprintf(&command, "\"%s\" \"%s\"", getenv("VISUAL") ? : getenv("EDITOR") ? : "vi", filename);
993 #else
994                                         xasprintf(&command, "edit \"%s\"", filename);
995 #endif
996
997                                         if(system(command)) {
998                                                 response = 'n';
999                                         } else {
1000                                                 response = 'y';
1001                                         }
1002
1003                                         free(command);
1004                                 }
1005
1006                                 if(response == 'y') {
1007                                         rename(filename, filename2);
1008                                         chmod(filename2, 0755);
1009                                         fprintf(stderr, "tinc-up enabled.\n");
1010                                 } else {
1011                                         fprintf(stderr, "tinc-up has been left disabled.\n");
1012                                 }
1013                         }
1014                 } else {
1015                         fprintf(stderr, "A tinc-up script was generated, but has been left disabled.\n");
1016                 }
1017         } else {
1018                 // A placeholder was generated.
1019                 rename(filename, filename2);
1020                 chmod(filename2, 0755);
1021         }
1022
1023         fprintf(stderr, "Configuration stored in: %s\n", confbase);
1024
1025         return true;
1026 }
1027
1028
1029 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
1030         while(len) {
1031                 int result = send(sock, data, len, 0);
1032
1033                 if(result == -1 && errno == EINTR) {
1034                         continue;
1035                 } else if(result <= 0) {
1036                         return false;
1037                 }
1038
1039                 data += result;
1040                 len -= result;
1041         }
1042
1043         return true;
1044 }
1045
1046 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
1047         switch(type) {
1048         case SPTPS_HANDSHAKE:
1049                 return sptps_send_record(&sptps, 0, cookie, sizeof(cookie));
1050
1051         case 0:
1052                 data = xrealloc(data, datalen + len + 1);
1053                 memcpy(data + datalen, msg, len);
1054                 datalen += len;
1055                 data[datalen] = 0;
1056                 break;
1057
1058         case 1:
1059                 return finalize_join();
1060
1061         case 2:
1062                 fprintf(stderr, "Invitation succesfully accepted.\n");
1063                 shutdown(sock, SHUT_RDWR);
1064                 success = true;
1065                 break;
1066
1067         default:
1068                 return false;
1069         }
1070
1071         return true;
1072 }
1073
1074 int cmd_join(int argc, char *argv[]) {
1075         free(data);
1076         data = NULL;
1077         datalen = 0;
1078
1079         if(argc > 2) {
1080                 fprintf(stderr, "Too many arguments!\n");
1081                 return 1;
1082         }
1083
1084         // Make sure confbase exists and is accessible.
1085         if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1086                 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1087                 return 1;
1088         }
1089
1090         if(mkdir(confbase, 0777) && errno != EEXIST) {
1091                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1092                 return 1;
1093         }
1094
1095         if(access(confbase, R_OK | W_OK | X_OK)) {
1096                 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
1097                 return 1;
1098         }
1099
1100         // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
1101         if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
1102                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1103                 return 1;
1104         }
1105
1106         // Either read the invitation from the command line or from stdin.
1107         char *invitation;
1108
1109         if(argc > 1) {
1110                 invitation = argv[1];
1111         } else {
1112                 if(tty) {
1113                         fprintf(stderr, "Enter invitation URL: ");
1114                 }
1115
1116                 errno = EPIPE;
1117
1118                 if(!fgets(line, sizeof(line), stdin)) {
1119                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1120                         return false;
1121                 }
1122
1123                 invitation = line;
1124         }
1125
1126         // Parse the invitation URL.
1127         rstrip(line);
1128
1129         char *slash = strchr(invitation, '/');
1130
1131         if(!slash) {
1132                 goto invalid;
1133         }
1134
1135         *slash++ = 0;
1136
1137         if(strlen(slash) != 48) {
1138                 goto invalid;
1139         }
1140
1141         char *address = invitation;
1142         char *port = NULL;
1143
1144         if(*address == '[') {
1145                 address++;
1146                 char *bracket = strchr(address, ']');
1147
1148                 if(!bracket) {
1149                         goto invalid;
1150                 }
1151
1152                 *bracket = 0;
1153
1154                 if(bracket[1] == ':') {
1155                         port = bracket + 2;
1156                 }
1157         } else {
1158                 port = strchr(address, ':');
1159
1160                 if(port) {
1161                         *port++ = 0;
1162                 }
1163         }
1164
1165         if(!port || !*port) {
1166                 port = "655";
1167         }
1168
1169         if(!b64decode(slash, hash, 24) || !b64decode(slash + 24, cookie, 24)) {
1170                 goto invalid;
1171         }
1172
1173         // Generate a throw-away key for the invitation.
1174         ecdsa_t *key = ecdsa_generate();
1175
1176         if(!key) {
1177                 return 1;
1178         }
1179
1180         char *b64key = ecdsa_get_base64_public_key(key);
1181
1182         // Connect to the tinc daemon mentioned in the URL.
1183         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1184
1185         if(!ai) {
1186                 return 1;
1187         }
1188
1189         struct addrinfo *aip = NULL;
1190
1191 next:
1192         if(!aip) {
1193                 aip = ai;
1194         } else {
1195                 aip = aip->ai_next;
1196
1197                 if(!aip) {
1198                         return 1;
1199                 }
1200         }
1201
1202         sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1203
1204         if(sock <= 0) {
1205                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1206                 goto next;
1207         }
1208
1209         if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
1210                 char *addrstr, *portstr;
1211                 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
1212                 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
1213                 free(addrstr);
1214                 free(portstr);
1215                 closesocket(sock);
1216                 goto next;
1217         }
1218
1219         fprintf(stderr, "Connected to %s port %s...\n", address, port);
1220
1221         // Tell him we have an invitation, and give him our throw-away key.
1222         int len = snprintf(line, sizeof(line), "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
1223
1224         if(len <= 0 || len >= sizeof(line)) {
1225                 abort();
1226         }
1227
1228         if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1229                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1230                 closesocket(sock);
1231                 goto next;
1232         }
1233
1234         char hisname[4096] = "";
1235         int code, hismajor, hisminor = 0;
1236
1237         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) {
1238                 fprintf(stderr, "Cannot read greeting from peer\n");
1239                 closesocket(sock);
1240                 goto next;
1241         }
1242
1243         // Check if the hash of the key he gave us matches the hash in the URL.
1244         char *fingerprint = line + 2;
1245         char hishash[64];
1246
1247         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1248                 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
1249                 return 1;
1250         }
1251
1252         if(memcmp(hishash, hash, 18)) {
1253                 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
1254                 return 1;
1255
1256         }
1257
1258         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1259
1260         if(!hiskey) {
1261                 return 1;
1262         }
1263
1264         // Start an SPTPS session
1265         if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive)) {
1266                 return 1;
1267         }
1268
1269         // Feed rest of input buffer to SPTPS
1270         if(!sptps_receive_data(&sptps, buffer, blen)) {
1271                 return 1;
1272         }
1273
1274         while((len = recv(sock, line, sizeof(line), 0))) {
1275                 if(len < 0) {
1276                         if(errno == EINTR) {
1277                                 continue;
1278                         }
1279
1280                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1281                         return 1;
1282                 }
1283
1284                 char *p = line;
1285
1286                 while(len) {
1287                         int done = sptps_receive_data(&sptps, p, len);
1288
1289                         if(!done) {
1290                                 return 1;
1291                         }
1292
1293                         len -= done;
1294                         p += done;
1295                 }
1296         }
1297
1298         sptps_stop(&sptps);
1299         ecdsa_free(hiskey);
1300         ecdsa_free(key);
1301         closesocket(sock);
1302
1303         if(!success) {
1304                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1305                 return 1;
1306         }
1307
1308         return 0;
1309
1310 invalid:
1311         fprintf(stderr, "Invalid invitation URL.\n");
1312         return 1;
1313 }