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