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