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