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