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