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