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