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