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