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