]> git.meshlink.io Git - meshlink/blob - src/invitation.c
Remove support for calling external scripts.
[meshlink] / src / invitation.c
1 /*
2     invitation.c -- Create and accept invitations
3     Copyright (C) 2013-2014 Guus Sliepen <guus@tinc-vpn.org>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "control_common.h"
23 #include "crypto.h"
24 #include "ecdsa.h"
25 #include "ecdsagen.h"
26 #include "invitation.h"
27 #include "names.h"
28 #include "netutl.h"
29 #include "rsagen.h"
30 #include "sptps.h"
31 #include "tincctl.h"
32 #include "utils.h"
33 #include "xalloc.h"
34
35 int addressfamily = AF_UNSPEC;
36
37 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
38         if(!filename || (*hostname && *port))
39                 return;
40
41         FILE *f = fopen(filename, "r");
42         if(!f)
43                 return;
44
45         while(fgets(line, sizeof line, f)) {
46                 if(!rstrip(line))
47                         continue;
48                 char *p = line, *q;
49                 p += strcspn(p, "\t =");
50                 if(!*p)
51                         continue;
52                 q = p + strspn(p, "\t ");
53                 if(*q == '=')
54                         q += 1 + strspn(q + 1, "\t ");
55                 *p = 0;
56                 p = q + strcspn(q, "\t ");
57                 if(*p)
58                         *p++ = 0;
59                 p += strspn(p, "\t ");
60                 p[strcspn(p, "\t ")] = 0;
61
62                 if(!*port && !strcasecmp(line, "Port")) {
63                         *port = xstrdup(q);
64                 } else if(!*hostname && !strcasecmp(line, "Address")) {
65                         *hostname = xstrdup(q);
66                         if(*p) {
67                                 free(*port);
68                                 *port = xstrdup(p);
69                         }
70                 }
71
72                 if(*hostname && *port)
73                         break;
74         }
75
76         fclose(f);
77 }
78
79 char *get_my_hostname() {
80         char *hostname = NULL;
81         char *port = NULL;
82         char *hostport = NULL;
83         char *name = get_my_name(false);
84         char *filename = NULL;
85
86         // Use first Address statement in own host config file
87         if(check_id(name)) {
88                 xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, name);
89                 scan_for_hostname(filename, &hostname, &port);
90                 scan_for_hostname(tinc_conf, &hostname, &port);
91         }
92
93         if(hostname)
94                 goto done;
95
96         // If that doesn't work, guess externally visible hostname
97         fprintf(stderr, "Trying to discover externally visible hostname...\n");
98         struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
99         struct addrinfo *aip = ai;
100         static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
101
102         while(aip) {
103                 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
104                 if(s >= 0) {
105                         if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
106                                 closesocket(s);
107                                 s = -1;
108                         }
109                 }
110                 if(s >= 0) {
111                         send(s, request, sizeof request - 1, 0);
112                         int len = recv(s, line, sizeof line - 1, MSG_WAITALL);
113                         if(len > 0) {
114                                 line[len] = 0;
115                                 if(line[len - 1] == '\n')
116                                         line[--len] = 0;
117                                 char *p = strrchr(line, '\n');
118                                 if(p && p[1])
119                                         hostname = xstrdup(p + 1);
120                         }
121                         closesocket(s);
122                         if(hostname)
123                                 break;
124                 }
125                 aip = aip->ai_next;
126                 continue;
127         }
128
129         if(ai)
130                 freeaddrinfo(ai);
131
132         // Check that the hostname is reasonable
133         if(hostname) {
134                 for(char *p = hostname; *p; p++) {
135                         if(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')
136                                 continue;
137                         // If not, forget it.
138                         free(hostname);
139                         hostname = NULL;
140                         break;
141                 }
142         }
143
144         if(!tty) {
145                 if(!hostname) {
146                         fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
147                         return NULL;
148                 }
149                 goto save;
150         }
151
152 again:
153         fprintf(stderr, "Please enter your host's external address or hostname");
154         if(hostname)
155                 fprintf(stderr, " [%s]", hostname);
156         fprintf(stderr, ": ");
157
158         if(!fgets(line, sizeof line, stdin)) {
159                 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
160                 free(hostname);
161                 return NULL;
162         }
163
164         if(!rstrip(line)) {
165                 if(hostname)
166                         goto save;
167                 else
168                         goto again;
169         }
170
171         for(char *p = line; *p; p++) {
172                 if(isalnum(*p) || *p == '-' || *p == '.')
173                         continue;
174                 fprintf(stderr, "Invalid address or hostname.\n");
175                 goto again;
176         }
177
178         free(hostname);
179         hostname = xstrdup(line);
180
181 save:
182         if(filename) {
183                 FILE *f = fopen(filename, "a");
184                 if(f) {
185                         fprintf(f, "\nAddress = %s\n", hostname);
186                         fclose(f);
187                 } else {
188                         fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
189                 }
190         }
191
192 done:
193         if(port) {
194                 if(strchr(hostname, ':'))
195                         xasprintf(&hostport, "[%s]:%s", hostname, port);
196                 else
197                         xasprintf(&hostport, "%s:%s", hostname, port);
198         } else {
199                 hostport = hostname;
200                 hostname = NULL;
201         }
202
203         free(hostname);
204         free(port);
205         free(filename);
206         return hostport;
207 }
208
209 static bool fcopy(FILE *out, const char *filename) {
210         FILE *in = fopen(filename, "r");
211         if(!in) {
212                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
213                 return false;
214         }
215
216         char buf[1024];
217         size_t len;
218         while((len = fread(buf, 1, sizeof buf, in)))
219                 fwrite(buf, len, 1, out);
220         fclose(in);
221         return true;
222 }
223
224 int cmd_invite(int argc, char *argv[]) {
225         if(argc < 2) {
226                 fprintf(stderr, "Not enough arguments!\n");
227                 return 1;
228         }
229
230         // Check validity of the new node's name
231         if(!check_id(argv[1])) {
232                 fprintf(stderr, "Invalid name for node.\n");
233                 return 1;
234         }
235
236         char *myname = get_my_name(true);
237         if(!myname)
238                 return 1;
239
240         // Ensure no host configuration file with that name exists
241         char *filename = NULL;
242         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
243         if(!access(filename, F_OK)) {
244                 free(filename);
245                 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
246                 return 1;
247         }
248         free(filename);
249
250         // If a daemon is running, ensure no other nodes now about this name
251         bool found = false;
252         if(connect_tincd(false)) {
253                 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
254
255                 while(recvline(fd, line, sizeof line)) {
256                         char node[4096];
257                         int code, req;
258                         if(sscanf(line, "%d %d %s", &code, &req, node) != 3)
259                                 break;
260                         if(!strcmp(node, argv[1]))
261                                 found = true;
262                 }
263
264                 if(found) {
265                         fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
266                         return 1;
267                 }
268         }
269
270         char hash[25];
271
272         xasprintf(&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                 free(filename);
276                 return 1;
277         }
278
279         // Count the number of valid invitations, clean up old ones
280         DIR *dir = opendir(filename);
281         if(!dir) {
282                 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
283                 free(filename);
284                 return 1;
285         }
286
287         errno = 0;
288         int count = 0;
289         struct dirent *ent;
290         time_t deadline = time(NULL) - 604800; // 1 week in the past
291
292         while((ent = readdir(dir))) {
293                 if(strlen(ent->d_name) != 24)
294                         continue;
295                 char *invname;
296                 struct stat st;
297                 xasprintf(&invname, "%s" SLASH "%s", filename, ent->d_name);
298                 if(!stat(invname, &st)) {
299                         if(deadline < st.st_mtime)
300                                 count++;
301                         else
302                                 unlink(invname);
303                 } else {
304                         fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
305                         errno = 0;
306                 }
307                 free(invname);
308         }
309
310         if(errno) {
311                 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
312                 closedir(dir);
313                 free(filename);
314                 return 1;
315         }
316                 
317         closedir(dir);
318         free(filename);
319
320         ecdsa_t *key;
321         xasprintf(&filename, "%s" SLASH "invitations" SLASH "ecdsa_key.priv", confbase);
322
323         // Remove the key if there are no outstanding invitations.
324         if(!count)
325                 unlink(filename);
326
327         // Create a new key if necessary.
328         FILE *f = fopen(filename, "r");
329         if(!f) {
330                 if(errno != ENOENT) {
331                         fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
332                         free(filename);
333                         return 1;
334                 }
335
336                 key = ecdsa_generate();
337                 if(!key) {
338                         free(filename);
339                         return 1;
340                 }
341                 f = fopen(filename, "w");
342                 if(!f) {
343                         fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
344                         free(filename);
345                         return 1;
346                 }
347                 chmod(filename, 0600);
348                 ecdsa_write_pem_private_key(key, f);
349                 fclose(f);
350
351                 if(connect_tincd(false))
352                         sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
353         } else {
354                 key = ecdsa_read_pem_private_key(f);
355                 fclose(f);
356                 if(!key)
357                         fprintf(stderr, "Could not read private key from %s\n", filename);
358         }
359
360         free(filename);
361         if(!key)
362                 return 1;
363
364         // Create a hash of the key.
365         char *fingerprint = ecdsa_get_base64_public_key(key);
366         digest_t *digest = digest_open_by_name("sha256", 18);
367         if(!digest)
368                 abort();
369         digest_create(digest, fingerprint, strlen(fingerprint), hash);
370         b64encode_urlsafe(hash, hash, 18);
371
372         // Create a random cookie for this invitation.
373         char cookie[25];
374         randomize(cookie, 18);
375
376         // Create a filename that doesn't reveal the cookie itself
377         char buf[18 + strlen(fingerprint)];
378         char cookiehash[25];
379         memcpy(buf, cookie, 18);
380         memcpy(buf + 18, fingerprint, sizeof buf - 18);
381         digest_create(digest, buf, sizeof buf, cookiehash);
382         b64encode_urlsafe(cookiehash, cookiehash, 18);
383
384         b64encode_urlsafe(cookie, cookie, 18);
385
386         // Create a file containing the details of the invitation.
387         xasprintf(&filename, "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
388         int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
389         if(!ifd) {
390                 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
391                 free(filename);
392                 return 1;
393         }
394         f = fdopen(ifd, "w");
395         if(!f)
396                 abort();
397
398         // Get the local address
399         char *address = get_my_hostname();
400
401         // Fill in the details.
402         fprintf(f, "Name = %s\n", argv[1]);
403         if(netname)
404                 fprintf(f, "NetName = %s\n", netname);
405         fprintf(f, "ConnectTo = %s\n", myname);
406
407         // Copy Broadcast and Mode
408         FILE *tc = fopen(tinc_conf, "r");
409         if(tc) {
410                 char buf[1024];
411                 while(fgets(buf, sizeof buf, tc)) {
412                         if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
413                                         || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
414                                 fputs(buf, f);
415                                 // Make sure there is a newline character.
416                                 if(!strchr(buf, '\n'))
417                                         fputc('\n', f);
418                         }
419                 }
420                 fclose(tc);
421         }
422
423         fprintf(f, "#---------------------------------------------------------------#\n");
424         fprintf(f, "Name = %s\n", myname);
425
426         char *filename2;
427         xasprintf(&filename2, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
428         fcopy(f, filename2);
429         fclose(f);
430         free(filename2);
431
432         // Create an URL from the local address, key hash and cookie
433         char *url;
434         xasprintf(&url, "%s/%s%s", address, hash, cookie);
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();
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;
593         xasprintf(&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                 return false;
598         }
599
600         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
601         // Other chunks go unfiltered to their respective host config files
602         const char *p = data;
603         char *l, *value;
604
605         while((l = get_line(&p))) {
606                 // Ignore comments
607                 if(*l == '#')
608                         continue;
609
610                 // Split line into variable and value
611                 int len = strcspn(l, "\t =");
612                 value = l + len;
613                 value += strspn(value, "\t ");
614                 if(*value == '=') {
615                         value++;
616                         value += strspn(value, "\t ");
617                 }
618                 l[len] = 0;
619
620                 // Is it a Name?
621                 if(!strcasecmp(l, "Name"))
622                         if(strcmp(value, name))
623                                 break;
624                         else
625                                 continue;
626                 else if(!strcasecmp(l, "NetName"))
627                         continue;
628
629                 // Check the list of known variables
630                 bool found = false;
631                 int i;
632                 for(i = 0; variables[i].name; i++) {
633                         if(strcasecmp(l, variables[i].name))
634                                 continue;
635                         found = true;
636                         break;
637                 }
638
639                 // Ignore unknown and unsafe variables
640                 if(!found) {
641                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
642                         continue;
643                 } else if(!(variables[i].type & VAR_SAFE)) {
644                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
645                         continue;
646                 }
647
648                 // Copy the safe variable to the right config file
649                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
650         }
651
652         fclose(f);
653         free(filename);
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                 xasprintf(&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                 free(filename);
695         }
696
697         // Generate our key and send a copy to the server
698         ecdsa_t *key = ecdsa_generate();
699         if(!key)
700                 return false;
701
702         char *b64key = ecdsa_get_base64_public_key(key);
703         if(!b64key)
704                 return false;
705
706         xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
707         f = fopenmask(filename, "w", 0600);
708
709         if(!ecdsa_write_pem_private_key(key, f)) {
710                 fprintf(stderr, "Error writing private key!\n");
711                 ecdsa_free(key);
712                 fclose(f);
713                 return false;
714         }
715
716         fclose(f);
717
718         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
719
720         sptps_send_record(&sptps, 1, b64key, strlen(b64key));
721         free(b64key);
722
723
724         rsa_t *rsa = rsa_generate(2048, 0x1001);
725         xasprintf(&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         ecdsa_free(key);
735         rsa_free(rsa);
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;
752                 xasprintf(&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                         free(newbase);
756                         goto ask_netname;
757                 }
758
759                 free(newbase);
760                 netname = line;
761                 make_names();
762         }
763
764         fprintf(stderr, "Configuration stored in: %s\n", confbase);
765
766         return true;
767 }
768
769
770 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
771         while(len) {
772                 int result = send(sock, data, len, 0);
773                 if(result == -1 && errno == EINTR)
774                         continue;
775                 else if(result <= 0)
776                         return false;
777                 data += result;
778                 len -= result;
779         }
780         return true;
781 }
782
783 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
784         switch(type) {
785                 case SPTPS_HANDSHAKE:
786                         return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
787
788                 case 0:
789                         data = xrealloc(data, datalen + len + 1);
790                         memcpy(data + datalen, msg, len);
791                         datalen += len;
792                         data[datalen] = 0;
793                         break;
794
795                 case 1:
796                         return finalize_join();
797
798                 case 2:
799                         fprintf(stderr, "Invitation succesfully accepted.\n");
800                         shutdown(sock, SHUT_RDWR);
801                         success = true;
802                         break;
803
804                 default:
805                         return false;
806         }
807
808         return true;
809 }
810
811 int cmd_join(int argc, char *argv[]) {
812         free(data);
813         data = NULL;
814         datalen = 0;
815
816         if(argc > 2) {
817                 fprintf(stderr, "Too many arguments!\n");
818                 return 1;
819         }
820
821         // Make sure confbase exists and is accessible.
822         if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
823                 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
824                 return 1;
825         }
826
827         if(mkdir(confbase, 0777) && errno != EEXIST) {
828                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
829                 return 1;
830         }
831
832         if(access(confbase, R_OK | W_OK | X_OK)) {
833                 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
834                 return 1;
835         }
836
837         // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
838         if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
839                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
840                 return 1;
841         }
842
843         // Either read the invitation from the command line or from stdin.
844         char *invitation;
845
846         if(argc > 1) {
847                 invitation = argv[1];
848         } else {
849                 if(tty)
850                         fprintf(stderr, "Enter invitation URL: ");
851                 errno = EPIPE;
852                 if(!fgets(line, sizeof line, stdin)) {
853                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
854                         return false;
855                 }
856                 invitation = line;
857         }
858
859         // Parse the invitation URL.
860         rstrip(line);
861
862         char *slash = strchr(invitation, '/');
863         if(!slash)
864                 goto invalid;
865
866         *slash++ = 0;
867
868         if(strlen(slash) != 48)
869                 goto invalid;
870
871         char *address = invitation;
872         char *port = NULL;
873         if(*address == '[') {
874                 address++;
875                 char *bracket = strchr(address, ']');
876                 if(!bracket)
877                         goto invalid;
878                 *bracket = 0;
879                 if(bracket[1] == ':')
880                         port = bracket + 2;
881         } else {
882                 port = strchr(address, ':');
883                 if(port)
884                         *port++ = 0;
885         }
886
887         if(!port || !*port)
888                 port = "655";
889
890         if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
891                 goto invalid;
892
893         // Generate a throw-away key for the invitation.
894         ecdsa_t *key = ecdsa_generate();
895         if(!key)
896                 return 1;
897
898         char *b64key = ecdsa_get_base64_public_key(key);
899
900         // Connect to the tinc daemon mentioned in the URL.
901         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
902         if(!ai)
903                 return 1;
904
905         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
906         if(sock <= 0) {
907                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
908                 return 1;
909         }
910
911         if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
912                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
913                 closesocket(sock);
914                 return 1;
915         }
916
917         fprintf(stderr, "Connected to %s port %s...\n", address, port);
918
919         // Tell him we have an invitation, and give him our throw-away key.
920         int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
921         if(len <= 0 || len >= sizeof line)
922                 abort();
923
924         if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
925                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
926                 closesocket(sock);
927                 return 1;
928         }
929
930         char hisname[4096] = "";
931         int code, hismajor, hisminor = 0;
932
933         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) {
934                 fprintf(stderr, "Cannot read greeting from peer\n");
935                 closesocket(sock);
936                 return 1;
937         }
938
939         // Check if the hash of the key he gave us matches the hash in the URL.
940         char *fingerprint = line + 2;
941         digest_t *digest = digest_open_by_name("sha256", 18);
942         if(!digest)
943                 abort();
944         char hishash[18];
945         if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
946                 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
947                 return 1;
948         }
949         if(memcmp(hishash, hash, 18)) {
950                 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
951                 return 1;
952
953         }
954         
955         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
956         if(!hiskey)
957                 return 1;
958
959         // Start an SPTPS session
960         if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
961                 return 1;
962
963         // Feed rest of input buffer to SPTPS
964         if(!sptps_receive_data(&sptps, buffer, blen))
965                 return 1;
966
967         while((len = recv(sock, line, sizeof line, 0))) {
968                 if(len < 0) {
969                         if(errno == EINTR)
970                                 continue;
971                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
972                         return 1;
973                 }
974
975                 if(!sptps_receive_data(&sptps, line, len))
976                         return 1;
977         }
978         
979         sptps_stop(&sptps);
980         ecdsa_free(hiskey);
981         ecdsa_free(key);
982         closesocket(sock);
983
984         if(!success) {
985                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
986                 return 1;
987         }
988
989         return 0;
990
991 invalid:
992         fprintf(stderr, "Invalid invitation URL.\n");
993         return 1;
994 }