Fix invitations.
[tinc] / 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 #include "ed25519/sha512.h"
37
38 int addressfamily = AF_UNSPEC;
39
40 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
41         if(!filename || (*hostname && *port))
42                 return;
43
44         FILE *f = fopen(filename, "r");
45         if(!f)
46                 return;
47
48         while(fgets(line, sizeof line, f)) {
49                 if(!rstrip(line))
50                         continue;
51                 char *p = line, *q;
52                 p += strcspn(p, "\t =");
53                 if(!*p)
54                         continue;
55                 q = p + strspn(p, "\t ");
56                 if(*q == '=')
57                         q += 1 + strspn(q + 1, "\t ");
58                 *p = 0;
59                 p = q + strcspn(q, "\t ");
60                 if(*p)
61                         *p++ = 0;
62                 p += strspn(p, "\t ");
63                 p[strcspn(p, "\t ")] = 0;
64
65                 if(!*port && !strcasecmp(line, "Port")) {
66                         *port = xstrdup(q);
67                 } else if(!*hostname && !strcasecmp(line, "Address")) {
68                         *hostname = xstrdup(q);
69                         if(*p) {
70                                 free(*port);
71                                 *port = xstrdup(p);
72                         }
73                 }
74
75                 if(*hostname && *port)
76                         break;
77         }
78
79         fclose(f);
80 }
81
82 char *get_my_hostname() {
83         char *hostname = NULL;
84         char *port = NULL;
85         char *hostport = NULL;
86         char *name = get_my_name(false);
87         char *filename = NULL;
88
89         // Use first Address statement in own host config file
90         if(check_id(name)) {
91                 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
92                 scan_for_hostname(filename, &hostname, &port);
93                 scan_for_hostname(tinc_conf, &hostname, &port);
94         }
95
96         if(hostname)
97                 goto done;
98
99         // If that doesn't work, guess externally visible hostname
100         fprintf(stderr, "Trying to discover externally visible hostname...\n");
101         struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
102         struct addrinfo *aip = ai;
103         static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
104
105         while(aip) {
106                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
107                 if(s >= 0) {
108                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
109                                 closesocket(s);
110                                 s = -1;
111                         }
112                 }
113                 if(s >= 0) {
114                         send(s, request, sizeof request - 1, 0);
115                         int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
116                         if(len > 0) {
117                                 line[len] = 0;
118                                 if(line[len - 1] == '\n')
119                                         line[--len] = 0;
120                                 char *p = strrchr(line, '\n');
121                                 if(p && p[1])
122                                         hostname = xstrdup(p + 1);
123                         }
124                         closesocket(s);
125                         if(hostname)
126                                 break;
127                 }
128                 aip = aip->ai_next;
129                 continue;
130         }
131
132         if(ai)
133                 freeaddrinfo(ai);
134
135         // Check that the hostname is reasonable
136         if(hostname) {
137                 for(char *p = hostname; *p; p++) {
138                         if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
139                                 continue;
140                         // If not, forget it.
141                         free(hostname);
142                         hostname = NULL;
143                         break;
144                 }
145         }
146
147         if(!tty) {
148                 if(!hostname) {
149                         fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
150                         return NULL;
151                 }
152                 goto save;
153         }
154
155 again:
156         fprintf(stderr, "Please enter your host's external address or hostname");
157         if(hostname)
158                 fprintf(stderr, " [%s]", hostname);
159         fprintf(stderr, ": ");
160
161         if(!fgets(line, sizeof line, stdin)) {
162                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
163                 free(hostname);
164                 return NULL;
165         }
166
167         if(!rstrip(line)) {
168                 if(hostname)
169                         goto save;
170                 else
171                         goto again;
172         }
173
174         for(char *p = line; *p; p++) {
175                 if(isalnum(*p) || *p == '-' || *p == '.')
176                         continue;
177                 fprintf(stderr, "Invalid address or hostname.\n");
178                 goto again;
179         }
180
181         free(hostname);
182         hostname = xstrdup(line);
183
184 save:
185         if(filename) {
186                 FILE *f = fopen(filename, "a");
187                 if(f) {
188                         fprintf(f, "\nAddress = %s\n", hostname);
189                         fclose(f);
190                 } else {
191                         fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
192                 }
193         }
194
195 done:
196         if(port) {
197                 if(strchr(hostname, ':'))
198                         xasprintf(&hostport, "[%s]:%s", hostname, port);
199                 else
200                         xasprintf(&hostport, "%s:%s", hostname, port);
201         } else {
202                 if(strchr(hostname, ':'))
203                         xasprintf(&hostport, "[%s]", hostname);
204                 else
205                         hostport = xstrdup(hostname);
206         }
207
208         free(hostname);
209         free(port);
210         free(filename);
211         return hostport;
212 }
213
214 static bool fcopy(FILE *out, const char *filename) {
215         FILE *in = fopen(filename, "r");
216         if(!in) {
217                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
218                 return false;
219         }
220
221         char buf[1024];
222         size_t len;
223         while((len = fread(buf, 1, sizeof buf, in)))
224                 fwrite(buf, len, 1, out);
225         fclose(in);
226         return true;
227 }
228
229 int cmd_invite(int argc, char *argv[]) {
230         if(argc < 2) {
231                 fprintf(stderr, "Not enough arguments!\n");
232                 return 1;
233         }
234
235         // Check validity of the new node's name
236         if(!check_id(argv[1])) {
237                 fprintf(stderr, "Invalid name for node.\n");
238                 return 1;
239         }
240
241         char *myname = get_my_name(true);
242         if(!myname)
243                 return 1;
244
245         // Ensure no host configuration file with that name exists
246         char *filename = NULL;
247         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
248         if(!access(filename, F_OK)) {
249                 free(filename);
250                 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
251                 return 1;
252         }
253         free(filename);
254
255         // If a daemon is running, ensure no other nodes know about this name
256         bool found = false;
257         if(connect_tincd(false)) {
258                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
259
260                 while(recvline(fd, line, sizeof line)) {
261                         char node[4096];
262                         int code, req;
263                         if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
264                                 break;
265                         if(!strcmp(node, argv[1]))
266                                 found = true;
267                 }
268
269                 if(found) {
270                         fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
271                         return 1;
272                 }
273         }
274
275         xasprintf(&filename, "%s" SLASH "invitations", confbase);
276         if(mkdir(filename, 0700) && errno != EEXIST) {
277                 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
278                 free(filename);
279                 return 1;
280         }
281
282         // Count the number of valid invitations, clean up old ones
283         DIR *dir = opendir(filename);
284         if(!dir) {
285                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
286                 free(filename);
287                 return 1;
288         }
289
290         errno = 0;
291         int count = 0;
292         struct dirent *ent;
293         time_t deadline = time(NULL) - 604800; // 1 week in the past
294
295         while((ent = readdir(dir))) {
296                 if(strlen(ent->d_name) != 24)
297                         continue;
298                 char *invname;
299                 struct stat st;
300                 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
301                 if(!stat(invname, &st)) {
302                         if(deadline < st.st_mtime)
303                                 count++;
304                         else
305                                 unlink(invname);
306                 } else {
307                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
308                         errno = 0;
309                 }
310                 free(invname);
311         }
312
313         if(errno) {
314                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
315                 closedir(dir);
316                 free(filename);
317                 return 1;
318         }
319                 
320         closedir(dir);
321         free(filename);
322
323         ecdsa_t *key;
324         xasprintf(&filename, "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
325
326         // Remove the key if there are no outstanding invitations.
327         if(!count)
328                 unlink(filename);
329
330         // Create a new key if necessary.
331         FILE *f = fopen(filename, "r");
332         if(!f) {
333                 if(errno != ENOENT) {
334                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
335                         free(filename);
336                         return 1;
337                 }
338
339                 key = ecdsa_generate();
340                 if(!key) {
341                         free(filename);
342                         return 1;
343                 }
344                 f = fopen(filename, "w");
345                 if(!f) {
346                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
347                         free(filename);
348                         return 1;
349                 }
350                 chmod(filename, 0600);
351                 ecdsa_write_pem_private_key(key, f);
352                 fclose(f);
353
354                 if(connect_tincd(false))
355                         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
356         } else {
357                 key = ecdsa_read_pem_private_key(f);
358                 fclose(f);
359                 if(!key)
360                         fprintf(stderr, "Could not read private key from %s\n", filename);
361         }
362
363         free(filename);
364         if(!key)
365                 return 1;
366
367         // Create a hash of the key.
368         char hash[64];
369         char *fingerprint = ecdsa_get_base64_public_key(key);
370         sha512(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[64];
380         memcpy(buf, cookie, 18);
381         memcpy(buf + 18, fingerprint, sizeof buf - 18);
382         sha512(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                 fclose(f);
615                 return false;
616         }
617
618         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
619         // Other chunks go unfiltered to their respective host config files
620         const char *p = data;
621         char *l, *value;
622
623         while((l = get_line(&p))) {
624                 // Ignore comments
625                 if(*l == '#')
626                         continue;
627
628                 // Split line into variable and value
629                 int len = strcspn(l, "\t =");
630                 value = l + len;
631                 value += strspn(value, "\t ");
632                 if(*value == '=') {
633                         value++;
634                         value += strspn(value, "\t ");
635                 }
636                 l[len] = 0;
637
638                 // Is it a Name?
639                 if(!strcasecmp(l, "Name"))
640                         if(strcmp(value, name))
641                                 break;
642                         else
643                                 continue;
644                 else if(!strcasecmp(l, "NetName"))
645                         continue;
646
647                 // Check the list of known variables
648                 bool found = false;
649                 int i;
650                 for(i = 0; variables[i].name; i++) {
651                         if(strcasecmp(l, variables[i].name))
652                                 continue;
653                         found = true;
654                         break;
655                 }
656
657                 // Ignore unknown and unsafe variables
658                 if(!found) {
659                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
660                         continue;
661                 } else if(!(variables[i].type & VAR_SAFE)) {
662                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
663                         continue;
664                 }
665
666                 // Copy the safe variable to the right config file
667                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
668         }
669
670         fclose(f);
671         free(filename);
672
673         while(l && !strcasecmp(l, "Name")) {
674                 if(!check_id(value)) {
675                         fprintf(stderr, "Invalid Name found in invitation.\n");
676                         return false;
677                 }
678
679                 if(!strcmp(value, name)) {
680                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
681                         return false;
682                 }
683
684                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
685                 f = fopen(filename, "w");
686
687                 if(!f) {
688                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
689                         return false;
690                 }
691
692                 while((l = get_line(&p))) {
693                         if(!strcmp(l, "#---------------------------------------------------------------#"))
694                                 continue;
695                         int len = strcspn(l, "\t =");
696                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
697                                 value = l + len;
698                                 value += strspn(value, "\t ");
699                                 if(*value == '=') {
700                                         value++;
701                                         value += strspn(value, "\t ");
702                                 }
703                                 l[len] = 0;
704                                 break;
705                         }
706
707                         fputs(l, f);
708                         fputc('\n', f);
709                 }
710
711                 fclose(f);
712                 free(filename);
713         }
714
715         // Generate our key and send a copy to the server
716         ecdsa_t *key = ecdsa_generate();
717         if(!key)
718                 return false;
719
720         char *b64key = ecdsa_get_base64_public_key(key);
721         if(!b64key)
722                 return false;
723
724         xasprintf(&filename, "%s" SLASH "ed25519_key.priv", confbase);
725         f = fopenmask(filename, "w", 0600);
726
727         if(!ecdsa_write_pem_private_key(key, f)) {
728                 fprintf(stderr, "Error writing private key!\n");
729                 ecdsa_free(key);
730                 fclose(f);
731                 return false;
732         }
733
734         fclose(f);
735
736         fprintf(fh, "Ed25519PublicKey = %s\n", b64key);
737
738         sptps_send_record(&sptps, 1, b64key, strlen(b64key));
739         free(b64key);
740         ecdsa_free(key);
741
742 #ifndef DISABLE_LEGACY
743         rsa_t *rsa = rsa_generate(2048, 0x1001);
744         xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
745         f = fopenmask(filename, "w", 0600);
746
747         rsa_write_pem_private_key(rsa, f);
748         fclose(f);
749
750         rsa_write_pem_public_key(rsa, fh);
751         fclose(fh);
752
753         rsa_free(rsa);
754 #endif
755
756         check_port(name);
757
758 ask_netname:
759         if(ask_netname && tty) {
760                 fprintf(stderr, "Enter a new netname: ");
761                 if(!fgets(line, sizeof line, stdin)) {
762                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
763                         return false;
764                 }
765                 if(!*line || *line == '\n')
766                         goto ask_netname;
767
768                 line[strlen(line) - 1] = 0;
769
770                 char *newbase;
771                 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
772                 if(rename(confbase, newbase)) {
773                         fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
774                         free(newbase);
775                         goto ask_netname;
776                 }
777
778                 free(newbase);
779                 netname = line;
780                 make_names();
781         }
782
783         fprintf(stderr, "Configuration stored in: %s\n", confbase);
784
785         return true;
786 }
787
788
789 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
790         while(len) {
791                 int result = send(sock, data, len, 0);
792                 if(result == -1 && errno == EINTR)
793                         continue;
794                 else if(result <= 0)
795                         return false;
796                 data += result;
797                 len -= result;
798         }
799         return true;
800 }
801
802 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
803         switch(type) {
804                 case SPTPS_HANDSHAKE:
805                         return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
806
807                 case 0:
808                         data = xrealloc(data, datalen + len + 1);
809                         memcpy(data + datalen, msg, len);
810                         datalen += len;
811                         data[datalen] = 0;
812                         break;
813
814                 case 1:
815                         return finalize_join();
816
817                 case 2:
818                         fprintf(stderr, "Invitation succesfully accepted.\n");
819                         shutdown(sock, SHUT_RDWR);
820                         success = true;
821                         break;
822
823                 default:
824                         return false;
825         }
826
827         return true;
828 }
829
830 int cmd_join(int argc, char *argv[]) {
831         free(data);
832         data = NULL;
833         datalen = 0;
834
835         if(argc > 2) {
836                 fprintf(stderr, "Too many arguments!\n");
837                 return 1;
838         }
839
840         // Make sure confbase exists and is accessible.
841         if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
842                 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
843                 return 1;
844         }
845
846         if(mkdir(confbase, 0777) && errno != EEXIST) {
847                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
848                 return 1;
849         }
850
851         if(access(confbase, R_OK | W_OK | X_OK)) {
852                 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
853                 return 1;
854         }
855
856         // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
857         if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
858                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
859                 return 1;
860         }
861
862         // Either read the invitation from the command line or from stdin.
863         char *invitation;
864
865         if(argc > 1) {
866                 invitation = argv[1];
867         } else {
868                 if(tty)
869                         fprintf(stderr, "Enter invitation URL: ");
870                 errno = EPIPE;
871                 if(!fgets(line, sizeof line, stdin)) {
872                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
873                         return false;
874                 }
875                 invitation = line;
876         }
877
878         // Parse the invitation URL.
879         rstrip(line);
880
881         char *slash = strchr(invitation, '/');
882         if(!slash)
883                 goto invalid;
884
885         *slash++ = 0;
886
887         if(strlen(slash) != 48)
888                 goto invalid;
889
890         char *address = invitation;
891         char *port = NULL;
892         if(*address == '[') {
893                 address++;
894                 char *bracket = strchr(address, ']');
895                 if(!bracket)
896                         goto invalid;
897                 *bracket = 0;
898                 if(bracket[1] == ':')
899                         port = bracket + 2;
900         } else {
901                 port = strchr(address, ':');
902                 if(port)
903                         *port++ = 0;
904         }
905
906         if(!port || !*port)
907                 port = "655";
908
909         if(!b64decode(slash, hash, 24) || !b64decode(slash + 24, cookie, 24))
910                 goto invalid;
911
912         // Generate a throw-away key for the invitation.
913         ecdsa_t *key = ecdsa_generate();
914         if(!key)
915                 return 1;
916
917         char *b64key = ecdsa_get_base64_public_key(key);
918
919         // Connect to the tinc daemon mentioned in the URL.
920         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
921         if(!ai)
922                 return 1;
923
924         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
925         if(sock <= 0) {
926                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
927                 return 1;
928         }
929
930         if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
931                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
932                 closesocket(sock);
933                 return 1;
934         }
935
936         fprintf(stderr, "Connected to %s port %s...\n", address, port);
937
938         // Tell him we have an invitation, and give him our throw-away key.
939         int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
940         if(len <= 0 || len >= sizeof line)
941                 abort();
942
943         if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
944                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
945                 closesocket(sock);
946                 return 1;
947         }
948
949         char hisname[4096] = "";
950         int code, hismajor, hisminor = 0;
951
952         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) {
953                 fprintf(stderr, "Cannot read greeting from peer\n");
954                 closesocket(sock);
955                 return 1;
956         }
957
958         // Check if the hash of the key he gave us matches the hash in the URL.
959         char *fingerprint = line + 2;
960         char hishash[64];
961         if(sha512(fingerprint, strlen(fingerprint), hishash)) {
962                 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
963                 return 1;
964         }
965         if(memcmp(hishash, hash, 18)) {
966                 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
967                 return 1;
968
969         }
970         
971         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
972         if(!hiskey)
973                 return 1;
974
975         // Start an SPTPS session
976         if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
977                 return 1;
978
979         // Feed rest of input buffer to SPTPS
980         if(!sptps_receive_data(&sptps, buffer, blen))
981                 return 1;
982
983         while((len = recv(sock, line, sizeof line, 0))) {
984                 if(len < 0) {
985                         if(errno == EINTR)
986                                 continue;
987                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
988                         return 1;
989                 }
990
991                 char *p = line;
992                 while(len) {
993                         int done = sptps_receive_data(&sptps, p, len);
994                         if(!done)
995                                 return 1;
996                         len -= done;
997                         p += done;
998                 }
999         }
1000         
1001         sptps_stop(&sptps);
1002         ecdsa_free(hiskey);
1003         ecdsa_free(key);
1004         closesocket(sock);
1005
1006         if(!success) {
1007                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
1008                 return 1;
1009         }
1010
1011         return 0;
1012
1013 invalid:
1014         fprintf(stderr, "Invalid invitation URL.\n");
1015         return 1;
1016 }