Don't force a .bat extension for scripts under Windows.
[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         // Fill in the details.
360         fprintf(f, "Name = %s\n", argv[1]);
361         if(netname)
362                 fprintf(f, "NetName = %s\n", netname);
363         fprintf(f, "ConnectTo = %s\n", myname);
364         // TODO: copy Broadcast and Mode
365         fprintf(f, "#---------------------------------------------------------------#\n");
366         fprintf(f, "Name = %s\n", myname);
367
368         xasprintf(&filename, "%s" SLASH "hosts" SLASH "%s", confbase, myname);
369         fcopy(f, filename);
370         fclose(f);
371
372         // Create an URL from the local address, key hash and cookie
373         char *address = get_my_hostname();
374         printf("%s/%s%s\n", address, hash, cookie);
375         free(filename);
376         free(address);
377
378         return 0;
379 }
380
381 static int sock;
382 static char cookie[18];
383 static sptps_t sptps;
384 static char *data;
385 static size_t datalen;
386 static bool success = false;
387
388 static char cookie[18], hash[18];
389
390 static char *get_line(const char **data) {
391         if(!data || !*data)
392                 return NULL;
393
394         if(!**data) {
395                 *data = NULL;
396                 return NULL;
397         }
398
399         static char line[1024];
400         const char *end = strchr(*data, '\n');
401         size_t len = end ? end - *data : strlen(*data);
402         if(len >= sizeof line) {
403                 fprintf(stderr, "Maximum line length exceeded!\n");
404                 return NULL;
405         }
406         if(len && !isprint(**data))
407                 abort();
408
409         memcpy(line, *data, len);
410         line[len] = 0;
411
412         if(end)
413                 *data = end + 1;
414         else
415                 *data = NULL;
416
417         return line;
418 }
419
420 static char *get_value(const char *data, const char *var) {
421         char *line = get_line(&data);
422         if(!line)
423                 return NULL;
424
425         char *sep = line + strcspn(line, " \t=");
426         char *val = sep + strspn(sep, " \t");
427         if(*val == '=')
428                 val += 1 + strspn(val + 1, " \t");
429         *sep = 0;
430         if(strcasecmp(line, var))
431                 return NULL;
432         return val;
433 }
434
435 static char *grep(const char *data, const char *var) {
436         static char value[1024];
437
438         const char *p = data;
439         int varlen = strlen(var);
440
441         // Skip all lines not starting with var
442         while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
443                 p = strchr(p, '\n');
444                 if(!p)
445                         break;
446                 else
447                         p++;
448         }
449
450         if(!p)
451                 return NULL;
452
453         p += varlen;
454         p += strspn(p, " \t");
455         if(*p == '=')
456                 p += 1 + strspn(p + 1, " \t");
457
458         const char *e = strchr(p, '\n');
459         if(!e)
460                 return xstrdup(p);
461
462         if(e - p >= sizeof value) {
463                 fprintf(stderr, "Maximum line length exceeded!\n");
464                 return NULL;
465         }
466
467         memcpy(value, p, e - p);
468         value[e - p] = 0;
469         return value;
470 }
471
472 static bool finalize_join(void) {
473         char *name = xstrdup(get_value(data, "Name"));
474         if(!name) {
475                 fprintf(stderr, "No Name found in invitation!\n");
476                 return false;
477         }
478
479         if(!check_id(name)) {
480                 fprintf(stderr, "Invalid Name found in invitation: %s!\n", name);
481                 return false;
482         }
483
484         if(!netname)
485                 netname = grep(data, "NetName");
486
487         bool ask_netname = false;
488         char temp_netname[32];
489
490 make_names:
491         if(!confbasegiven) {
492                 free(confbase);
493                 confbase = NULL;
494         }
495
496         make_names();
497
498         free(tinc_conf);
499         free(hosts_dir);
500
501         xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
502         xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
503
504         if(!access(tinc_conf, F_OK)) {
505                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
506                 if(!tty || confbasegiven)
507                         return false;
508
509                 // Generate a random netname, ask for a better one later.
510                 ask_netname = true;
511                 snprintf(temp_netname, sizeof temp_netname, "join_%x", rand());
512                 netname = temp_netname;
513                 goto make_names;
514         }       
515
516         if(mkdir(confbase, 0777) && errno != EEXIST) {
517                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
518                 return false;
519         }
520
521         if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
522                 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
523                 return false;
524         }
525
526         FILE *f = fopen(tinc_conf, "w");
527         if(!f) {
528                 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
529                 return false;
530         }
531
532         fprintf(f, "Name = %s\n", name);
533
534         char *filename;
535         xasprintf(&filename, "%s" SLASH "%s", hosts_dir, name);
536         FILE *fh = fopen(filename, "w");
537         if(!fh) {
538                 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
539                 return false;
540         }
541
542         // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
543         // Other chunks go unfiltered to their respective host config files
544         const char *p = data;
545         char *l, *value;
546
547         while((l = get_line(&p))) {
548                 // Ignore comments
549                 if(*l == '#')
550                         continue;
551
552                 // Split line into variable and value
553                 int len = strcspn(l, "\t =");
554                 value = l + len;
555                 value += strspn(value, "\t ");
556                 if(*value == '=') {
557                         value++;
558                         value += strspn(value, "\t ");
559                 }
560                 l[len] = 0;
561
562                 // Is it a Name?
563                 if(!strcasecmp(l, "Name"))
564                         if(strcmp(value, name))
565                                 break;
566                         else
567                                 continue;
568                 else if(!strcasecmp(l, "NetName"))
569                         continue;
570
571                 // Check the list of known variables
572                 bool found = false;
573                 int i;
574                 for(i = 0; variables[i].name; i++) {
575                         if(strcasecmp(l, variables[i].name))
576                                 continue;
577                         found = true;
578                         break;
579                 }
580
581                 // Ignore unknown and unsafe variables
582                 if(!found) {
583                         fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
584                         continue;
585                 } else if(!(variables[i].type & VAR_SAFE)) {
586                         fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
587                         continue;
588                 }
589
590                 // Copy the safe variable to the right config file
591                 fprintf(variables[i].type & VAR_HOST ? fh : f, "%s = %s\n", l, value);
592         }
593
594         fclose(f);
595         free(filename);
596
597         while(l && !strcasecmp(l, "Name")) {
598                 if(!check_id(value)) {
599                         fprintf(stderr, "Invalid Name found in invitation.\n");
600                         return false;
601                 }
602
603                 if(!strcmp(value, name)) {
604                         fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
605                         return false;
606                 }
607
608                 xasprintf(&filename, "%s" SLASH "%s", hosts_dir, value);
609                 f = fopen(filename, "w");
610
611                 if(!f) {
612                         fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
613                         return false;
614                 }
615
616                 while((l = get_line(&p))) {
617                         if(!strcmp(l, "#---------------------------------------------------------------#"))
618                                 continue;
619                         int len = strcspn(l, "\t =");
620                         if(len == 4 && !strncasecmp(l, "Name", 4)) {
621                                 value = l + len;
622                                 value += strspn(value, "\t ");
623                                 if(*value == '=') {
624                                         value++;
625                                         value += strspn(value, "\t ");
626                                 }
627                                 l[len] = 0;
628                                 break;
629                         }
630
631                         fputs(l, f);
632                         fputc('\n', f);
633                 }
634
635                 fclose(f);
636                 free(filename);
637         }
638
639         // Generate our key and send a copy to the server
640         ecdsa_t *key = ecdsa_generate();
641         if(!key)
642                 return false;
643
644         char *b64key = ecdsa_get_base64_public_key(key);
645         if(!b64key)
646                 return false;
647
648         xasprintf(&filename, "%s" SLASH "ecdsa_key.priv", confbase);
649         f = fopenmask(filename, "w", 0600);
650
651         if(!ecdsa_write_pem_private_key(key, f)) {
652                 fprintf(stderr, "Error writing private key!\n");
653                 ecdsa_free(key);
654                 fclose(f);
655                 return false;
656         }
657
658         fclose(f);
659
660         fprintf(fh, "ECDSAPublicKey = %s\n", b64key);
661
662         sptps_send_record(&sptps, 1, b64key, strlen(b64key));
663         free(b64key);
664
665
666         rsa_t *rsa = rsa_generate(2048, 0x1001);
667         xasprintf(&filename, "%s" SLASH "rsa_key.priv", confbase);
668         f = fopenmask(filename, "w", 0600);
669
670         rsa_write_pem_private_key(rsa, f);
671         fclose(f);
672
673         rsa_write_pem_public_key(rsa, fh);
674         fclose(fh);
675
676         ecdsa_free(key);
677         rsa_free(rsa);
678
679         check_port(name);
680
681         fprintf(stderr, "Invitation succesfully accepted.\n");
682         shutdown(sock, SHUT_RDWR);
683         success = true;
684
685 ask_netname:
686         if(ask_netname) {
687                 fprintf(stderr, "Enter a new netname: ");
688                 if(!fgets(line, sizeof line, stdin)) {
689                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
690                         return false;
691                 }
692                 if(!*line || *line == '\n')
693                         goto ask_netname;
694
695                 line[strlen(line) - 1] = 0;
696
697                 char *newbase;
698                 xasprintf(&newbase, CONFDIR SLASH "tinc" SLASH "%s", line);
699                 if(rename(confbase, newbase)) {
700                         fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
701                         free(newbase);
702                         goto ask_netname;
703                 }
704
705                 free(newbase);
706                 netname = line;
707                 make_names();
708         }
709
710         return true;
711 }
712
713 static bool invitation_send(void *handle, uint8_t type, const char *data, size_t len) {
714         while(len) {
715                 int result = send(sock, data, len, 0);
716                 if(result == -1 && errno == EINTR)
717                         continue;
718                 else if(result <= 0)
719                         return false;
720                 data += result;
721                 len -= result;
722         }
723         return true;
724 }
725
726 static bool invitation_receive(void *handle, uint8_t type, const char *msg, uint16_t len) {
727         switch(type) {
728                 case SPTPS_HANDSHAKE:
729                         return sptps_send_record(&sptps, 0, cookie, sizeof cookie);
730
731                 case 0:
732                         data = xrealloc(data, datalen + len + 1);
733                         memcpy(data + datalen, msg, len);
734                         datalen += len;
735                         data[datalen] = 0;
736                         break;
737
738                 case 1:
739                         return finalize_join();
740
741                 default:
742                         return false;
743         }
744
745         return true;
746 }
747
748 int cmd_join(int argc, char *argv[]) {
749         free(data);
750         data = NULL;
751         datalen = 0;
752
753         if(argc > 2) {
754                 fprintf(stderr, "Too many arguments!\n");
755                 return 1;
756         }
757
758         // Make sure confbase exists and is accessible.
759         if(strcmp(confdir, confbase) && mkdir(confdir, 0755) && errno != EEXIST) {
760                 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
761                 return 1;
762         }
763
764         if(mkdir(confbase, 0777) && errno != EEXIST) {
765                 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
766                 return 1;
767         }
768
769         if(access(confbase, R_OK | W_OK | X_OK)) {
770                 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
771                 return 1;
772         }
773
774         // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
775         if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
776                 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
777                 return 1;
778         }
779
780         // Either read the invitation from the command line or from stdin.
781         char *invitation;
782
783         if(argc > 1) {
784                 invitation = argv[1];
785         } else {
786                 if(tty) {
787                         printf("Enter invitation URL: ");
788                         fflush(stdout);
789                 }
790                 errno = EPIPE;
791                 if(!fgets(line, sizeof line, stdin)) {
792                         fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
793                         return false;
794                 }
795                 invitation = line;
796         }
797
798         // Parse the invitation URL.
799         rstrip(line);
800
801         char *slash = strchr(invitation, '/');
802         if(!slash)
803                 goto invalid;
804
805         *slash++ = 0;
806
807         if(strlen(slash) != 48)
808                 goto invalid;
809
810         char *address = invitation;
811         char *port = NULL;
812         if(*address == '[') {
813                 address++;
814                 char *bracket = strchr(address, ']');
815                 if(!bracket)
816                         goto invalid;
817                 *bracket = 0;
818                 if(bracket[1] == ':')
819                         port = bracket + 2;
820         } else {
821                 port = strchr(address, ':');
822                 if(port)
823                         *port++ = 0;
824         }
825
826         if(!port || !*port)
827                 port = "655";
828
829         if(!b64decode(slash, hash, 18) || !b64decode(slash + 24, cookie, 18))
830                 goto invalid;
831
832         // Generate a throw-away key for the invitation.
833         ecdsa_t *key = ecdsa_generate();
834         if(!key)
835                 return 1;
836
837         char *b64key = ecdsa_get_base64_public_key(key);
838
839         // Connect to the tinc daemon mentioned in the URL.
840         struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
841         if(!ai)
842                 return 1;
843
844         sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
845         if(sock <= 0) {
846                 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
847                 return 1;
848         }
849
850         if(connect(sock, ai->ai_addr, ai->ai_addrlen)) {
851                 fprintf(stderr, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
852                 closesocket(sock);
853                 return 1;
854         }
855
856         fprintf(stderr, "Connected to %s port %s...\n", address, port);
857
858         // Tell him we have an invitation, and give him our throw-away key.
859         int len = snprintf(line, sizeof line, "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
860         if(len <= 0 || len >= sizeof line)
861                 abort();
862
863         if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
864                 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
865                 closesocket(sock);
866                 return 1;
867         }
868
869         char hisname[4096] = "";
870         int code, hismajor, hisminor = 0;
871
872         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) {
873                 fprintf(stderr, "Cannot read greeting from peer\n");
874                 closesocket(sock);
875                 return 1;
876         }
877
878         // Check if the hash of the key he gave us matches the hash in the URL.
879         char *fingerprint = line + 2;
880         digest_t *digest = digest_open_by_name("sha256", 18);
881         if(!digest)
882                 abort();
883         char hishash[18];
884         if(!digest_create(digest, fingerprint, strlen(fingerprint), hishash)) {
885                 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
886                 return 1;
887         }
888         if(memcmp(hishash, hash, 18)) {
889                 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
890                 return 1;
891
892         }
893         
894         ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
895         if(!hiskey)
896                 return 1;
897
898         // Start an SPTPS session
899         if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive))
900                 return 1;
901
902         // Feed rest of input buffer to SPTPS
903         if(!sptps_receive_data(&sptps, buffer, blen))
904                 return 1;
905
906         while((len = recv(sock, line, sizeof line, 0))) {
907                 if(len < 0) {
908                         if(errno == EINTR)
909                                 continue;
910                         fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
911                         return 1;
912                 }
913
914                 if(!sptps_receive_data(&sptps, line, len))
915                         return 1;
916         }
917         
918         sptps_stop(&sptps);
919         ecdsa_free(hiskey);
920         ecdsa_free(key);
921         closesocket(sock);
922
923         if(!success) {
924                 fprintf(stderr, "Connection closed by peer, invitation cancelled.\n");
925                 return 1;
926         }
927
928         return 0;
929
930 invalid:
931         fprintf(stderr, "Invalid invitation URL.\n");
932         return 1;
933 }