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