2 invitation.c -- Create and accept invitations
3 Copyright (C) 2013-2022 Guus Sliepen <guus@tinc-vpn.org>
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.
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.
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.
22 #include "control_common.h"
27 #include "invitation.h"
40 #include "ed25519/sha512.h"
42 int addressfamily = AF_UNSPEC;
44 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
45 if(!filename || (*hostname && *port)) {
49 FILE *f = fopen(filename, "r");
55 while(fgets(line, sizeof(line), f)) {
61 p += strcspn(p, "\t =");
67 q = p + strspn(p, "\t ");
70 q += 1 + strspn(q + 1, "\t ");
74 p = q + strcspn(q, "\t ");
80 p += strspn(p, "\t ");
81 p[strcspn(p, "\t ")] = 0;
83 if(!*port && !strcasecmp(line, "Port")) {
86 } else if(!*hostname && !strcasecmp(line, "Address")) {
88 *hostname = xstrdup(q);
96 if(*hostname && *port) {
104 static bool get_my_hostname(char **out_address, char **out_port) {
105 char *hostname = NULL;
107 char *hostport = NULL;
108 char *name = get_my_name(false);
109 char filename[PATH_MAX] = {0};
111 // Use first Address statement in own host config file
113 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, name);
114 scan_for_hostname(filename, &hostname, &port);
115 scan_for_hostname(tinc_conf, &hostname, &port);
121 if(!port || (is_decimal(port) && atoi(port) == 0)) {
122 pidfile_t *pidfile = read_pidfile();
126 port = xstrdup(pidfile->port);
129 fprintf(stderr, "tincd is using a dynamic port and is not running. Please start tincd or set the Port option to a non-zero value.\n");
138 // If that doesn't work, guess externally visible hostname
139 fprintf(stderr, "Trying to discover externally visible hostname...\n");
140 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
141 struct addrinfo *aip = ai;
142 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
145 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
148 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
155 send(s, request, sizeof(request) - 1, 0);
156 ssize_t len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
161 if(line[len - 1] == '\n') {
165 char *p = strrchr(line, '\n');
168 hostname = xstrdup(p + 1);
187 // Check that the hostname is reasonable
189 for(char *p = hostname; *p; p++) {
190 if(isalnum((uint8_t) *p) || *p == '-' || *p == '.' || *p == ':') {
194 // If not, forget it.
203 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
212 fprintf(stderr, "Please enter your host's external address or hostname");
215 fprintf(stderr, " [%s]", hostname);
218 fprintf(stderr, ": ");
220 if(!fgets(line, sizeof(line), stdin)) {
221 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
235 for(char *p = line; *p; p++) {
236 if(isalnum((uint8_t) *p) || *p == '-' || *p == '.') {
240 fprintf(stderr, "Invalid address or hostname.\n");
245 hostname = xstrdup(line);
250 FILE *f = fopen(filename, "a");
253 fprintf(f, "\nAddress = %s\n", hostname);
256 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
263 if(strchr(hostname, ':')) {
264 xasprintf(&hostport, "[%s]:%s", hostname, port);
266 xasprintf(&hostport, "%s:%s", hostname, port);
269 if(strchr(hostname, ':')) {
270 xasprintf(&hostport, "[%s]", hostname);
272 hostport = xstrdup(hostname);
279 if(hostport && port) {
280 *out_address = hostport;
290 // Copy host configuration file, replacing Port with the value passed here. Host
291 // configs may contain this clause: `Port = 0`, which means 'ask the operating
292 // system to allocate any available port'. This obviously won't do for invitation
293 // files, so replace it with an actual port we've obtained previously.
294 static bool copy_config_replacing_port(FILE *out, const char *filename, const char *port) {
295 FILE *in = fopen(filename, "r");
298 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
304 while(fgets(line, sizeof(line), in)) {
305 const char *var_beg = line + strspn(line, "\t ");
306 const char *var_end = var_beg + strcspn(var_beg, "\t ");
308 // Check the name of the variable we've read. If it's Port, replace it with
309 // a port we'll use in invitation URL. Otherwise, just copy the line.
310 if(var_end > var_beg && !strncasecmp(var_beg, "Port", var_end - var_beg)) {
311 fprintf(out, "Port = %s\n", port);
313 fprintf(out, "%s", line);
321 static bool append_host_config(FILE *f, const char *nodename, const char *port) {
323 snprintf(path, sizeof(path), "%s" SLASH "hosts" SLASH "%s", confbase, nodename);
324 bool success = copy_config_replacing_port(f, path, port);
329 int cmd_invite(int argc, char *argv[]) {
331 fprintf(stderr, "Not enough arguments!\n");
335 // Check validity of the new node's name
336 if(!check_id(argv[1])) {
337 fprintf(stderr, "Invalid name for node.\n");
342 myname = get_my_name(true);
348 // Ensure no host configuration file with that name exists
349 char filename[PATH_MAX];
350 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
352 if(!access(filename, F_OK)) {
353 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
357 // If a daemon is running, ensure no other nodes know about this name
358 if(connect_tincd(false)) {
360 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
362 while(recvline(fd, line, sizeof(line))) {
366 if(sscanf(line, "%d %d %4095s", &code, &req, node) != 3) {
370 if(!strcmp(node, argv[1])) {
376 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
381 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", confbase);
383 if(mkdir(filename, 0700) && errno != EEXIST) {
384 fprintf(stderr, "Could not create directory %s: %s\n", filename, strerror(errno));
388 // Count the number of valid invitations, clean up old ones
389 DIR *dir = opendir(filename);
392 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
399 time_t deadline = time(NULL) - 604800; // 1 week in the past
401 while((ent = readdir(dir))) {
402 if(strlen(ent->d_name) != 24) {
406 char invname[PATH_MAX];
409 if((size_t)snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= sizeof(invname)) {
410 fprintf(stderr, "Filename too long: %s" SLASH "%s\n", filename, ent->d_name);
414 if(!stat(invname, &st)) {
415 if(deadline < st.st_mtime) {
421 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
429 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
434 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
436 // Remove the key if there are no outstanding invitations.
441 // Create a new key if necessary.
442 FILE *f = fopen(filename, "r");
445 if(errno != ENOENT) {
446 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
450 key = ecdsa_generate();
456 f = fopen(filename, "w");
459 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
464 chmod(filename, 0600);
466 if(!ecdsa_write_pem_private_key(key, f)) {
467 fprintf(stderr, "Could not write ECDSA private key\n");
475 if(connect_tincd(true)) {
476 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
478 fprintf(stderr, "Could not signal the tinc daemon. Please restart or reload it manually.\n");
481 key = ecdsa_read_pem_private_key(f);
485 fprintf(stderr, "Could not read private key from %s\n", filename);
493 // Create a hash of the key.
495 char *fingerprint = ecdsa_get_base64_public_key(key);
496 sha512(fingerprint, strlen(fingerprint), hash);
497 b64encode_tinc_urlsafe(hash, hash, 18);
501 // Create a random cookie for this invitation.
503 randomize(cookie, 18);
505 // Create a filename that doesn't reveal the cookie itself
506 const size_t buflen = 18 + strlen(fingerprint);
507 uint8_t *buf = alloca(buflen);
510 memcpy(buf, cookie, 18);
511 memcpy(buf + 18, fingerprint, buflen - 18);
512 sha512(buf, buflen, cookiehash);
513 b64encode_tinc_urlsafe(cookiehash, cookiehash, 18);
517 b64encode_tinc_urlsafe(cookie, cookie, 18);
519 // Create a file containing the details of the invitation.
520 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
521 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
524 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
528 f = fdopen(ifd, "w");
534 // Get the local address
535 char *address = NULL;
538 if(!get_my_hostname(&address, &port)) {
542 // Fill in the details.
543 fprintf(f, "Name = %s\n", argv[1]);
545 if(check_netname(netname, true)) {
546 fprintf(f, "NetName = %s\n", netname);
549 fprintf(f, "ConnectTo = %s\n", myname);
551 // Copy Broadcast and Mode
552 FILE *tc = fopen(tinc_conf, "r");
557 while(fgets(buf, sizeof(buf), tc)) {
558 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
559 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
562 // Make sure there is a newline character.
563 if(!strchr(buf, '\n')) {
572 fprintf(f, "#---------------------------------------------------------------#\n");
573 fprintf(f, "Name = %s\n", myname);
575 bool appended = append_host_config(f, myname, port);
579 fprintf(stderr, "Could not append my config to invitation file: %s.\n", strerror(errno));
584 // Create an URL from the local address, key hash and cookie
586 xasprintf(&url, "%s/%s%s", address, hash, cookie);
588 // Call the inviation-created script
590 environment_init(&env);
591 environment_add(&env, "NODE=%s", argv[1]);
592 environment_add(&env, "INVITATION_FILE=%s", filename);
593 environment_add(&env, "INVITATION_URL=%s", url);
594 execute_script("invitation-created", &env);
595 environment_exit(&env);
605 static char cookie[18], hash[18];
606 static sptps_t sptps;
608 static size_t datalen;
609 static bool success = false;
611 static char *get_line(char *line, size_t linelen, const char **data) {
612 if(!data || !*data) {
621 const char *end = strchr(*data, '\n');
622 size_t len = end ? (size_t)(end - *data) : strlen(*data);
625 fprintf(stderr, "Maximum line length exceeded!\n");
629 if(len && !isprint((uint8_t) **data)) {
633 memcpy(line, *data, len);
645 static char *get_value(const char *data, const char *var) {
646 static char buf[1024];
648 char *line = get_line(buf, sizeof(buf), &data);
654 char *sep = line + strcspn(line, " \t=");
655 char *val = sep + strspn(sep, " \t");
658 val += 1 + strspn(val + 1, " \t");
663 if(strcasecmp(line, var)) {
670 static char *grep(const char *data, const char *var) {
671 static char value[1024];
673 const char *p = data;
674 size_t varlen = strlen(var);
676 // Skip all lines not starting with var
677 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
692 p += strspn(p, " \t");
695 p += 1 + strspn(p + 1, " \t");
698 const char *e = strchr(p, '\n');
704 if((size_t)(e - p) >= sizeof(value)) {
705 fprintf(stderr, "Maximum line length exceeded!\n");
709 memcpy(value, p, e - p);
714 static bool finalize_join(void) {
715 const char *name = get_value(data, "Name");
718 fprintf(stderr, "No Name found in invitation!\n");
722 if(!check_id(name)) {
723 fprintf(stderr, "Invalid Name found in invitation!\n");
728 const char *net = grep(data, "NetName");
731 netname = xstrdup(net);
733 if(!check_netname(netname, true)) {
734 fprintf(stderr, "Unsafe NetName found in invitation!\n");
740 bool ask_netname = false;
741 char temp_netname[32];
755 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
756 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
758 if(!access(tinc_conf, F_OK)) {
759 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
765 // Generate a random netname, ask for a better one later.
767 snprintf(temp_netname, sizeof(temp_netname), "join_%x", prng(UINT32_MAX));
768 netname = temp_netname;
772 if(mkdir(confbase, 0777) && errno != EEXIST) {
773 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
777 if(mkdir(hosts_dir, 0777) && errno != EEXIST) {
778 fprintf(stderr, "Could not create directory %s: %s\n", hosts_dir, strerror(errno));
782 FILE *f = fopen(tinc_conf, "w");
785 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
789 fprintf(f, "Name = %s\n", name);
791 char filename[PATH_MAX];
792 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, name);
793 FILE *fh = fopen(filename, "w");
796 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
801 snprintf(filename, sizeof(filename), "%s" SLASH "invitation-data", confbase);
802 FILE *finv = fopen(filename, "w");
804 if(!finv || fwrite(data, datalen, 1, finv) != 1) {
805 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
814 snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
815 FILE *fup = fopen(filename, "w");
818 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
824 ifconfig_header(fup);
826 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
827 // Generate a tinc-up script from Ifconfig and Route keywords.
828 // Other chunks go unfiltered to their respective host config files
829 const char *p = data;
832 static char line[1024];
834 while((l = get_line(line, sizeof(line), &p))) {
840 // Split line into variable and value
841 size_t len = strcspn(l, "\t =");
843 value += strspn(value, "\t ");
847 value += strspn(value, "\t ");
852 // Ignore lines with empty variable names
858 if(!strcasecmp(l, "Name")) {
859 if(strcmp(value, name)) {
864 } else if(!strcasecmp(l, "NetName")) {
868 // Check the list of known variables
872 for(i = 0; variables[i].name; i++) {
873 if(strcasecmp(l, variables[i].name)) {
881 // Handle Ifconfig and Route statements
883 if(!strcasecmp(l, "Ifconfig")) {
884 if(!strcasecmp(value, "dhcp")) {
886 } else if(!strcasecmp(value, "dhcp6")) {
888 } else if(!strcasecmp(value, "slaac")) {
891 ifconfig_address(fup, value);
895 } else if(!strcasecmp(l, "Route")) {
896 ifconfig_route(fup, value);
901 // Ignore unknown and unsafe variables
903 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
905 } else if(!(variables[i].type & VAR_SAFE)) {
907 fprintf(stderr, "Warning: unsafe variable '%s' in invitation.\n", l);
909 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
914 // Copy the safe variable to the right config file
915 fprintf((variables[i].type & VAR_HOST) ? fh : f, "%s = %s\n", l, value);
919 bool valid_tinc_up = ifconfig_footer(fup);
922 while(l && !strcasecmp(l, "Name")) {
923 if(!check_id(value)) {
924 fprintf(stderr, "Invalid Name found in invitation.\n");
928 if(!strcmp(value, name)) {
929 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
933 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, value);
934 f = fopen(filename, "w");
937 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
941 while((l = get_line(line, sizeof(line), &p))) {
942 if(!strcmp(l, "#---------------------------------------------------------------#")) {
946 size_t len = strcspn(l, "\t =");
948 if(len == 4 && !strncasecmp(l, "Name", 4)) {
950 value += strspn(value, "\t ");
954 value += strspn(value, "\t ");
968 // Generate our key and send a copy to the server
969 ecdsa_t *key = ecdsa_generate();
975 char *b64key = ecdsa_get_base64_public_key(key);
981 snprintf(filename, sizeof(filename), "%s" SLASH "ed25519_key.priv", confbase);
982 f = fopenmask(filename, "w", 0600);
988 if(!ecdsa_write_pem_private_key(key, f)) {
989 fprintf(stderr, "Error writing private key!\n");
997 fprintf(fh, "Ed25519PublicKey = %s\n", b64key);
999 sptps_send_record(&sptps, 1, b64key, strlen(b64key));
1003 #ifndef DISABLE_LEGACY
1004 rsa_t *rsa = rsa_generate(2048, 0x1001);
1005 snprintf(filename, sizeof(filename), "%s" SLASH "rsa_key.priv", confbase);
1006 f = fopenmask(filename, "w", 0600);
1008 if(!f || !rsa_write_pem_private_key(rsa, f)) {
1009 fprintf(stderr, "Could not write private RSA key\n");
1010 } else if(!rsa_write_pem_public_key(rsa, fh)) {
1011 fprintf(stderr, "Could not write public RSA key\n");
1025 if(ask_netname && tty) {
1026 fprintf(stderr, "Enter a new netname: ");
1028 if(!fgets(line, sizeof(line), stdin)) {
1029 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1033 if(!*line || *line == '\n') {
1037 line[strlen(line) - 1] = 0;
1039 char newbase[PATH_MAX];
1041 if((size_t)snprintf(newbase, sizeof(newbase), CONFDIR SLASH "tinc" SLASH "%s", line) >= sizeof(newbase)) {
1042 fprintf(stderr, "Filename too long: " CONFDIR SLASH "tinc" SLASH "%s\n", line);
1046 if(rename(confbase, newbase)) {
1047 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
1055 char filename2[PATH_MAX];
1056 snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
1059 snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up.bat", confbase);
1061 snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up", confbase);
1066 FILE *fup = fopen(filename, "r");
1069 fprintf(stderr, "\nPlease review the following tinc-up script:\n\n");
1073 while(fgets(buf, sizeof(buf), fup)) {
1082 fprintf(stderr, "\nDo you want to use this script [y]es/[n]o/[e]dit? ");
1083 response = tolower(getchar());
1084 } while(!strchr("yne", response));
1086 fprintf(stderr, "\n");
1088 if(response == 'e') {
1090 #ifndef HAVE_WINDOWS
1091 const char *editor = getenv("VISUAL");
1094 editor = getenv("EDITOR");
1101 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1103 xasprintf(&command, "edit \"%s\"", filename);
1106 if(system(command)) {
1115 if(response == 'y') {
1116 rename(filename, filename2);
1117 chmod(filename2, 0755);
1118 fprintf(stderr, "tinc-up enabled.\n");
1120 fprintf(stderr, "tinc-up has been left disabled.\n");
1125 rename(filename, filename2);
1126 chmod(filename2, 0755);
1127 fprintf(stderr, "tinc-up enabled.\n");
1129 fprintf(stderr, "A tinc-up script was generated, but has been left disabled.\n");
1133 // A placeholder was generated.
1134 rename(filename, filename2);
1135 chmod(filename2, 0755);
1138 fprintf(stderr, "Configuration stored in: %s\n", confbase);
1144 static bool invitation_send(void *handle, uint8_t type, const void *vdata, size_t len) {
1147 const char *data = vdata;
1150 ssize_t result = send(sock, data, len, 0);
1152 if(result == -1 && sockwouldblock(sockerrno)) {
1154 } else if(result <= 0) {
1165 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
1169 case SPTPS_HANDSHAKE:
1170 return sptps_send_record(&sptps, 0, cookie, sizeof(cookie));
1173 data = xrealloc(data, datalen + len + 1);
1174 memcpy(data + datalen, msg, len);
1180 return finalize_join();
1183 fprintf(stderr, "Invitation successfully accepted.\n");
1184 shutdown(sock, SHUT_RDWR);
1195 int cmd_join(int argc, char *argv[]) {
1201 fprintf(stderr, "Too many arguments!\n");
1205 // Make sure confbase exists and is accessible.
1206 if(!confbase_given && mkdir(confdir, 0755) && errno != EEXIST) {
1207 fprintf(stderr, "Could not create directory %s: %s\n", confdir, strerror(errno));
1211 if(mkdir(confbase, 0777) && errno != EEXIST) {
1212 fprintf(stderr, "Could not create directory %s: %s\n", confbase, strerror(errno));
1216 if(access(confbase, R_OK | W_OK | X_OK)) {
1217 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
1221 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
1222 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
1223 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1227 // Either read the invitation from the command line or from stdin.
1231 invitation = argv[1];
1234 fprintf(stderr, "Enter invitation URL: ");
1239 if(!fgets(line, sizeof(line), stdin)) {
1240 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1247 // Parse the invitation URL.
1250 char *slash = strchr(invitation, '/');
1258 if(strlen(slash) != 48) {
1262 char *address = invitation;
1265 if(*address == '[') {
1267 char *bracket = strchr(address, ']');
1275 if(bracket[1] == ':') {
1279 port = strchr(address, ':');
1286 if(!port || !*port) {
1287 static char default_port[] = "655";
1288 port = default_port;
1291 if(!b64decode_tinc(slash, hash, 24) || !b64decode_tinc(slash + 24, cookie, 24)) {
1295 // Generate a throw-away key for the invitation.
1296 ecdsa_t *key = ecdsa_generate();
1302 char *b64key = ecdsa_get_base64_public_key(key);
1304 // Connect to the tinc daemon mentioned in the URL.
1305 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1313 struct addrinfo *aip = NULL;
1329 sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1332 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1336 if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
1337 char *addrstr, *portstr;
1338 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
1339 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
1346 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1348 // Tell him we have an invitation, and give him our throw-away key.
1349 ssize_t len = snprintf(line, sizeof(line), "0 ?%s %d.%d\n", b64key, PROT_MAJOR, PROT_MINOR);
1351 if(len <= 0 || (size_t)len >= sizeof(line)) {
1355 if(!sendline(sock, "0 ?%s %d.%d", b64key, PROT_MAJOR, 1)) {
1356 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1361 char hisname[4096] = "";
1362 int code, hismajor, hisminor = 0;
1364 if(!recvline(sock, line, sizeof(line)) || sscanf(line, "%d %4095s %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) {
1365 fprintf(stderr, "Cannot read greeting from peer\n");
1377 // Check if the hash of the key he gave us matches the hash in the URL.
1378 char *fingerprint = line + 2;
1381 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1382 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
1387 if(memcmp(hishash, hash, 18)) {
1388 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
1394 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1401 // Start an SPTPS session
1402 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive)) {
1408 // Feed rest of input buffer to SPTPS
1409 if(!sptps_receive_data(&sptps, buffer, blen)) {
1414 while((len = recv(sock, line, sizeof(line), 0))) {
1416 if(sockwouldblock(sockerrno)) {
1422 // If socket has been shut down, recv() on Windows returns -1 and sets sockerrno
1423 // to WSAESHUTDOWN, while on UNIX-like operating systems recv() returns 0, so we
1424 // have to do an explicit check here.
1425 if(sockshutdown(sockerrno)) {
1430 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, sockstrerror(sockerrno));
1438 size_t done = sptps_receive_data(&sptps, p, len);
1445 len -= (ssize_t) done;
1457 fprintf(stderr, "Invitation cancelled.\n");
1464 fprintf(stderr, "Invalid invitation URL.\n");