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