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