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