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