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