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