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