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"
41 #include "ed25519/sha512.h"
43 int addressfamily = AF_UNSPEC;
45 static void scan_for_hostname(const char *filename, char **hostname, char **port) {
46 if(!filename || (*hostname && *port)) {
50 FILE *f = fopen(filename, "r");
56 while(fgets(line, sizeof(line), f)) {
62 p += strcspn(p, "\t =");
68 q = p + strspn(p, "\t ");
71 q += 1 + strspn(q + 1, "\t ");
75 p = q + strcspn(q, "\t ");
81 p += strspn(p, "\t ");
82 p[strcspn(p, "\t ")] = 0;
84 if(!*port && !strcasecmp(line, "Port")) {
87 } else if(!*hostname && !strcasecmp(line, "Address")) {
89 *hostname = xstrdup(q);
97 if(*hostname && *port) {
105 static bool get_my_hostname(char **out_address, char **out_port) {
106 char *hostname = NULL;
108 char *hostport = NULL;
109 char *name = get_my_name(false);
110 char filename[PATH_MAX] = {0};
112 // Use first Address statement in own host config file
114 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, name);
115 scan_for_hostname(filename, &hostname, &port);
116 scan_for_hostname(tinc_conf, &hostname, &port);
122 if(!port || (is_decimal(port) && atoi(port) == 0)) {
123 pidfile_t *pidfile = read_pidfile();
127 port = xstrdup(pidfile->port);
130 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");
139 // If that doesn't work, guess externally visible hostname
140 fprintf(stderr, "Trying to discover externally visible hostname...\n");
141 struct addrinfo *ai = str2addrinfo("tinc-vpn.org", "80", SOCK_STREAM);
142 struct addrinfo *aip = ai;
143 static const char request[] = "GET http://tinc-vpn.org/host.cgi HTTP/1.0\r\n\r\n";
146 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
149 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
156 send(s, request, sizeof(request) - 1, 0);
157 ssize_t len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
162 if(line[len - 1] == '\n') {
166 char *p = strrchr(line, '\n');
169 hostname = xstrdup(p + 1);
188 // Check that the hostname is reasonable
190 for(char *p = hostname; *p; p++) {
191 if(isalnum((uint8_t) *p) || *p == '-' || *p == '.' || *p == ':') {
195 // If not, forget it.
204 fprintf(stderr, "Could not determine the external address or hostname. Please set Address manually.\n");
213 fprintf(stderr, "Please enter your host's external address or hostname");
216 fprintf(stderr, " [%s]", hostname);
219 fprintf(stderr, ": ");
221 if(!fgets(line, sizeof(line), stdin)) {
222 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
236 for(char *p = line; *p; p++) {
237 if(isalnum((uint8_t) *p) || *p == '-' || *p == '.') {
241 fprintf(stderr, "Invalid address or hostname.\n");
246 hostname = xstrdup(line);
251 FILE *f = fopen(filename, "a");
254 fprintf(f, "\nAddress = %s\n", hostname);
257 fprintf(stderr, "Could not append Address to %s: %s\n", filename, strerror(errno));
264 if(strchr(hostname, ':')) {
265 xasprintf(&hostport, "[%s]:%s", hostname, port);
267 xasprintf(&hostport, "%s:%s", hostname, port);
270 if(strchr(hostname, ':')) {
271 xasprintf(&hostport, "[%s]", hostname);
273 hostport = xstrdup(hostname);
280 if(hostport && port) {
281 *out_address = hostport;
291 // Copy host configuration file, replacing Port with the value passed here. Host
292 // configs may contain this clause: `Port = 0`, which means 'ask the operating
293 // system to allocate any available port'. This obviously won't do for invitation
294 // files, so replace it with an actual port we've obtained previously.
295 static bool copy_config_replacing_port(FILE *out, const char *filename, const char *port) {
296 FILE *in = fopen(filename, "r");
299 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
305 while(fgets(line, sizeof(line), in)) {
306 const char *var_beg = line + strspn(line, "\t ");
307 const char *var_end = var_beg + strcspn(var_beg, "\t ");
309 // Check the name of the variable we've read. If it's Port, replace it with
310 // a port we'll use in invitation URL. Otherwise, just copy the line.
311 if(var_end > var_beg && !strncasecmp(var_beg, "Port", var_end - var_beg)) {
312 fprintf(out, "Port = %s\n", port);
314 fprintf(out, "%s", line);
318 memzero(line, sizeof(line));
323 static bool append_host_config(FILE *f, const char *nodename, const char *port) {
325 snprintf(path, sizeof(path), "%s" SLASH "hosts" SLASH "%s", confbase, nodename);
326 bool success = copy_config_replacing_port(f, path, port);
331 int cmd_invite(int argc, char *argv[]) {
333 fprintf(stderr, "Not enough arguments!\n");
338 fprintf(stderr, "Too many arguments!\n");
342 // Check validity of the new node's name
343 if(!check_id(argv[1])) {
344 fprintf(stderr, "Invalid name for node.\n");
349 myname = get_my_name(true);
355 // Ensure no host configuration file with that name exists
356 char filename[PATH_MAX];
357 snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", confbase, argv[1]);
359 if(!access(filename, F_OK)) {
360 fprintf(stderr, "A host config file for %s already exists!\n", argv[1]);
364 // If a daemon is running, ensure no other nodes know about this name
365 if(connect_tincd(false)) {
367 sendline(fd, "%d %d", CONTROL, REQ_DUMP_NODES);
369 while(recvline(fd, line, sizeof(line))) {
373 if(sscanf(line, "%d %d %4095s", &code, &req, node) != 3) {
377 if(!strcmp(node, argv[1])) {
383 fprintf(stderr, "A node with name %s is already known!\n", argv[1]);
388 if(!makedirs(DIR_INVITATIONS)) {
392 snprintf(filename, sizeof(filename), "%s" SLASH "invitations", confbase);
394 // Count the number of valid invitations, clean up old ones
395 DIR *dir = opendir(filename);
398 fprintf(stderr, "Could not read directory %s: %s\n", filename, strerror(errno));
405 time_t deadline = time(NULL) - 604800; // 1 week in the past
407 while((ent = readdir(dir))) {
408 if(strlen(ent->d_name) != 24) {
412 char invname[PATH_MAX];
415 if((size_t)snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= sizeof(invname)) {
416 fprintf(stderr, "Filename too long: %s" SLASH "%s\n", filename, ent->d_name);
420 if(!stat(invname, &st)) {
421 if(deadline < st.st_mtime) {
427 fprintf(stderr, "Could not stat %s: %s\n", invname, strerror(errno));
435 fprintf(stderr, "Error while reading directory %s: %s\n", filename, strerror(errno));
440 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ed25519_key.priv", confbase);
442 // Remove the key if there are no outstanding invitations.
447 // Create a new key if necessary.
448 FILE *f = fopen(filename, "r");
451 if(errno != ENOENT) {
452 fprintf(stderr, "Could not read %s: %s\n", filename, strerror(errno));
456 key = ecdsa_generate();
462 f = fopen(filename, "w");
465 fprintf(stderr, "Could not write %s: %s\n", filename, strerror(errno));
470 chmod(filename, 0600);
472 if(!ecdsa_write_pem_private_key(key, f)) {
473 fprintf(stderr, "Could not write ECDSA private key\n");
481 if(connect_tincd(true)) {
482 sendline(fd, "%d %d", CONTROL, REQ_RELOAD);
484 fprintf(stderr, "Could not signal the tinc daemon. Please restart or reload it manually.\n");
487 key = ecdsa_read_pem_private_key(f);
491 fprintf(stderr, "Could not read private key from %s\n", filename);
499 // Create a hash of the key.
501 char *fingerprint = ecdsa_get_base64_public_key(key);
502 sha512(fingerprint, strlen(fingerprint), hash);
503 b64encode_tinc_urlsafe(hash, hash, 18);
507 // Create a random cookie for this invitation.
509 randomize(cookie, 18);
511 // Create a filename that doesn't reveal the cookie itself
512 const size_t buflen = 18 + strlen(fingerprint);
513 uint8_t *buf = alloca(buflen);
516 memcpy(buf, cookie, 18);
517 memcpy(buf + 18, fingerprint, buflen - 18);
518 sha512(buf, buflen, cookiehash);
519 b64encode_tinc_urlsafe(cookiehash, cookiehash, 18);
523 b64encode_tinc_urlsafe(cookie, cookie, 18);
525 // Create a file containing the details of the invitation.
526 snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", confbase, cookiehash);
527 int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
530 memzero(cookie, sizeof(cookie));
531 fprintf(stderr, "Could not create invitation file %s: %s\n", filename, strerror(errno));
535 f = fdopen(ifd, "w");
541 // Get the local address
542 char *address = NULL;
545 if(!get_my_hostname(&address, &port)) {
546 memzero(cookie, sizeof(cookie));
550 // Create an URL from the local address, key hash and cookie
552 xasprintf(&url, "%s/%s%s", address, hash, cookie);
554 memzero(cookie, sizeof(cookie));
557 // Fill in the details.
558 fprintf(f, "Name = %s\n", argv[1]);
560 if(check_netname(netname, true)) {
561 fprintf(f, "NetName = %s\n", netname);
564 fprintf(f, "ConnectTo = %s\n", myname);
566 // Copy Broadcast and Mode
567 FILE *tc = fopen(tinc_conf, "r");
572 while(fgets(buf, sizeof(buf), tc)) {
573 if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
574 || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
577 // Make sure there is a newline character.
578 if(!strchr(buf, '\n')) {
587 fprintf(f, "#---------------------------------------------------------------#\n");
588 fprintf(f, "Name = %s\n", myname);
590 bool appended = append_host_config(f, myname, port);
594 fprintf(stderr, "Could not append my config to invitation file: %s.\n", strerror(errno));
599 // Call the inviation-created script
601 environment_init(&env);
602 environment_add(&env, "NODE=%s", argv[1]);
603 environment_add(&env, "INVITATION_FILE=%s", filename);
604 environment_add(&env, "INVITATION_URL=%s", url);
605 execute_script("invitation-created", &env);
606 environment_exit(&env);
615 static char cookie[18], hash[18];
616 static sptps_t sptps;
618 static size_t datalen;
619 static bool success = false;
621 static char *get_line(char *line, size_t linelen, const char **data) {
622 if(!data || !*data) {
631 const char *end = strchr(*data, '\n');
632 size_t len = end ? (size_t)(end - *data) : strlen(*data);
635 fprintf(stderr, "Maximum line length exceeded!\n");
639 if(len && !isprint((uint8_t) **data)) {
643 memcpy(line, *data, len);
655 static char *get_value(const char *data, const char *var) {
656 static char buf[1024];
658 char *line = get_line(buf, sizeof(buf), &data);
664 char *sep = line + strcspn(line, " \t=");
665 char *val = sep + strspn(sep, " \t");
668 val += 1 + strspn(val + 1, " \t");
673 if(strcasecmp(line, var)) {
680 static char *grep(const char *data, const char *var) {
683 const char *p = data;
684 size_t varlen = strlen(var);
686 // Skip all lines not starting with var
687 while(strncasecmp(p, var, varlen) || !strchr(" \t=", p[varlen])) {
702 p += strspn(p, " \t");
705 p += 1 + strspn(p + 1, " \t");
708 const char *e = strchr(p, '\n');
714 if((size_t)(e - p) >= sizeof(value)) {
715 fprintf(stderr, "Maximum line length exceeded!\n");
719 memcpy(value, p, e - p);
721 return xstrdup(value);
724 static bool finalize_join(void) {
725 const char *name = get_value(data, "Name");
728 fprintf(stderr, "No Name found in invitation!\n");
732 if(!check_id(name)) {
733 fprintf(stderr, "Invalid Name found in invitation!\n");
738 char *net = grep(data, "NetName");
743 if(!check_netname(netname, true)) {
744 fprintf(stderr, "Unsafe NetName found in invitation!\n");
750 bool ask_netname = false;
751 char temp_netname[32];
765 xasprintf(&tinc_conf, "%s" SLASH "tinc.conf", confbase);
766 xasprintf(&hosts_dir, "%s" SLASH "hosts", confbase);
768 if(!access(tinc_conf, F_OK)) {
769 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
775 // Generate a random netname, ask for a better one later.
777 snprintf(temp_netname, sizeof(temp_netname), "join_%x", prng(UINT32_MAX));
778 netname = temp_netname;
782 if(!makedirs(DIR_HOSTS | DIR_CONFBASE | DIR_CACHE)) {
786 FILE *f = fopen(tinc_conf, "w");
789 fprintf(stderr, "Could not create file %s: %s\n", tinc_conf, strerror(errno));
793 fprintf(f, "Name = %s\n", name);
795 char filename[PATH_MAX];
796 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, name);
797 FILE *fh = fopen(filename, "w");
800 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
805 snprintf(filename, sizeof(filename), "%s" SLASH "invitation-data", confbase);
806 FILE *finv = fopen(filename, "w");
808 if(!finv || fwrite(data, datalen, 1, finv) != 1) {
809 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
818 snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
819 FILE *fup = fopen(filename, "w");
822 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
828 ifconfig_header(fup);
830 // Filter first chunk on approved keywords, split between tinc.conf and hosts/Name
831 // Generate a tinc-up script from Ifconfig and Route keywords.
832 // Other chunks go unfiltered to their respective host config files
833 const char *p = data;
836 static char line[1024];
838 while((l = get_line(line, sizeof(line), &p))) {
844 // Split line into variable and value
845 size_t len = strcspn(l, "\t =");
847 value += strspn(value, "\t ");
851 value += strspn(value, "\t ");
856 // Ignore lines with empty variable names
862 if(!strcasecmp(l, "Name")) {
863 if(strcmp(value, name)) {
868 } else if(!strcasecmp(l, "NetName")) {
872 // Check the list of known variables
876 for(i = 0; variables[i].name; i++) {
877 if(strcasecmp(l, variables[i].name)) {
885 // Handle Ifconfig and Route statements
887 if(!strcasecmp(l, "Ifconfig")) {
888 if(!strcasecmp(value, "dhcp")) {
890 } else if(!strcasecmp(value, "dhcp6")) {
892 } else if(!strcasecmp(value, "slaac")) {
895 ifconfig_address(fup, value);
899 } else if(!strcasecmp(l, "Route")) {
900 ifconfig_route(fup, value);
905 // Ignore unknown and unsafe variables
907 fprintf(stderr, "Ignoring unknown variable '%s' in invitation.\n", l);
909 } else if(!(variables[i].type & VAR_SAFE)) {
911 fprintf(stderr, "Warning: unsafe variable '%s' in invitation.\n", l);
913 fprintf(stderr, "Ignoring unsafe variable '%s' in invitation.\n", l);
918 // Copy the safe variable to the right config file
919 fprintf((variables[i].type & VAR_HOST) ? fh : f, "%s = %s\n", l, value);
923 bool valid_tinc_up = ifconfig_footer(fup);
926 while(l && !strcasecmp(l, "Name")) {
927 if(!check_id(value)) {
928 fprintf(stderr, "Invalid Name found in invitation.\n");
932 if(!strcmp(value, name)) {
933 fprintf(stderr, "Secondary chunk would overwrite our own host config file.\n");
937 snprintf(filename, sizeof(filename), "%s" SLASH "%s", hosts_dir, value);
938 f = fopen(filename, "w");
941 fprintf(stderr, "Could not create file %s: %s\n", filename, strerror(errno));
945 while((l = get_line(line, sizeof(line), &p))) {
946 if(!strcmp(l, "#---------------------------------------------------------------#")) {
950 size_t len = strcspn(l, "\t =");
952 if(len == 4 && !strncasecmp(l, "Name", 4)) {
954 value += strspn(value, "\t ");
958 value += strspn(value, "\t ");
972 // Generate our key and send a copy to the server
973 ecdsa_t *key = ecdsa_generate();
979 char *b64_pubkey = ecdsa_get_base64_public_key(key);
985 snprintf(filename, sizeof(filename), "%s" SLASH "ed25519_key.priv", confbase);
986 f = fopenmask(filename, "w", 0600);
992 if(!ecdsa_write_pem_private_key(key, f)) {
993 fprintf(stderr, "Error writing private key!\n");
1001 fprintf(fh, "Ed25519PublicKey = %s\n", b64_pubkey);
1003 sptps_send_record(&sptps, 1, b64_pubkey, strlen(b64_pubkey));
1007 #ifndef DISABLE_LEGACY
1008 rsa_t *rsa = rsa_generate(2048, 0x1001);
1009 snprintf(filename, sizeof(filename), "%s" SLASH "rsa_key.priv", confbase);
1010 f = fopenmask(filename, "w", 0600);
1012 if(!f || !rsa_write_pem_private_key(rsa, f)) {
1013 fprintf(stderr, "Could not write private RSA key\n");
1014 } else if(!rsa_write_pem_public_key(rsa, fh)) {
1015 fprintf(stderr, "Could not write public RSA key\n");
1029 if(ask_netname && tty) {
1030 fprintf(stderr, "Enter a new netname: ");
1032 if(!fgets(line, sizeof(line), stdin)) {
1033 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1037 if(!*line || *line == '\n') {
1041 line[strlen(line) - 1] = 0;
1043 char newbase[PATH_MAX];
1045 if((size_t)snprintf(newbase, sizeof(newbase), CONFDIR SLASH "tinc" SLASH "%s", line) >= sizeof(newbase)) {
1046 fprintf(stderr, "Filename too long: " CONFDIR SLASH "tinc" SLASH "%s\n", line);
1050 if(rename(confbase, newbase)) {
1051 fprintf(stderr, "Error trying to rename %s to %s: %s\n", confbase, newbase, strerror(errno));
1059 char filename2[PATH_MAX];
1060 snprintf(filename, sizeof(filename), "%s" SLASH "tinc-up.invitation", confbase);
1063 snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up.bat", confbase);
1065 snprintf(filename2, sizeof(filename2), "%s" SLASH "tinc-up", confbase);
1070 FILE *fup = fopen(filename, "r");
1073 fprintf(stderr, "\nPlease review the following tinc-up script:\n\n");
1077 while(fgets(buf, sizeof(buf), fup)) {
1086 fprintf(stderr, "\nDo you want to use this script [y]es/[n]o/[e]dit? ");
1087 response = tolower(getchar());
1088 } while(!strchr("yne", response));
1090 fprintf(stderr, "\n");
1092 if(response == 'e') {
1094 #ifndef HAVE_WINDOWS
1095 const char *editor = getenv("VISUAL");
1098 editor = getenv("EDITOR");
1105 xasprintf(&command, "\"%s\" \"%s\"", editor, filename);
1107 xasprintf(&command, "edit \"%s\"", filename);
1110 if(system(command)) {
1119 if(response == 'y') {
1120 rename(filename, filename2);
1121 chmod(filename2, 0755);
1122 fprintf(stderr, "tinc-up enabled.\n");
1124 fprintf(stderr, "tinc-up has been left disabled.\n");
1129 rename(filename, filename2);
1130 chmod(filename2, 0755);
1131 fprintf(stderr, "tinc-up enabled.\n");
1133 fprintf(stderr, "A tinc-up script was generated, but has been left disabled.\n");
1137 // A placeholder was generated.
1138 rename(filename, filename2);
1139 chmod(filename2, 0755);
1142 fprintf(stderr, "Configuration stored in: %s\n", confbase);
1148 static bool invitation_send(void *handle, uint8_t type, const void *vdata, size_t len) {
1151 const char *data = vdata;
1154 ssize_t result = send(sock, data, len, 0);
1156 if(result == -1 && sockwouldblock(sockerrno)) {
1158 } else if(result <= 0) {
1169 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
1173 case SPTPS_HANDSHAKE:
1174 return sptps_send_record(&sptps, 0, cookie, sizeof(cookie));
1177 data = xrealloc(data, datalen + len + 1);
1178 memcpy(data + datalen, msg, len);
1184 return finalize_join();
1187 fprintf(stderr, "Invitation successfully accepted.\n");
1188 shutdown(sock, SHUT_RDWR);
1199 int cmd_join(int argc, char *argv[]) {
1205 fprintf(stderr, "Too many arguments!\n");
1209 // Make sure confbase exists and is accessible.
1210 if(!makedirs(DIR_CONFDIR | DIR_CONFBASE)) {
1214 if(access(confbase, R_OK | W_OK | X_OK)) {
1215 fprintf(stderr, "No permission to write in directory %s: %s\n", confbase, strerror(errno));
1219 // If a netname or explicit configuration directory is specified, check for an existing tinc.conf.
1220 if((netname || confbasegiven) && !access(tinc_conf, F_OK)) {
1221 fprintf(stderr, "Configuration file %s already exists!\n", tinc_conf);
1225 // Either read the invitation from the command line or from stdin.
1229 invitation = argv[1];
1232 fprintf(stderr, "Enter invitation URL: ");
1237 if(!fgets(line, sizeof(line), stdin)) {
1238 fprintf(stderr, "Error while reading stdin: %s\n", strerror(errno));
1245 // Parse the invitation URL.
1248 char *slash = strchr(invitation, '/');
1256 if(strlen(slash) != 48) {
1260 char *address = invitation;
1263 if(*address == '[') {
1265 char *bracket = strchr(address, ']');
1273 if(bracket[1] == ':') {
1277 port = strchr(address, ':');
1284 if(!port || !*port) {
1285 static char default_port[] = "655";
1286 port = default_port;
1289 if(!b64decode_tinc(slash, hash, 24) || !b64decode_tinc(slash + 24, cookie, 24)) {
1293 // Generate a throw-away key for the invitation.
1294 ecdsa_t *key = ecdsa_generate();
1300 char *b64_pubkey = ecdsa_get_base64_public_key(key);
1302 // Connect to the tinc daemon mentioned in the URL.
1303 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1311 struct addrinfo *aip = NULL;
1327 sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1330 fprintf(stderr, "Could not open socket: %s\n", strerror(errno));
1334 if(connect(sock, aip->ai_addr, aip->ai_addrlen)) {
1335 char *addrstr, *portstr;
1336 sockaddr2str((sockaddr_t *)aip->ai_addr, &addrstr, &portstr);
1337 fprintf(stderr, "Could not connect to %s port %s: %s\n", addrstr, portstr, strerror(errno));
1344 fprintf(stderr, "Connected to %s port %s...\n", address, port);
1346 // Tell him we have an invitation, and give him our throw-away key.
1347 ssize_t len = snprintf(line, sizeof(line), "0 ?%s %d.%d\n", b64_pubkey, PROT_MAJOR, PROT_MINOR);
1349 if(len <= 0 || (size_t)len >= sizeof(line)) {
1353 if(!sendline(sock, "0 ?%s %d.%d", b64_pubkey, PROT_MAJOR, 1)) {
1354 fprintf(stderr, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1359 char hisname[4096] = "";
1360 int code, hismajor, hisminor = 0;
1362 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) {
1363 fprintf(stderr, "Cannot read greeting from peer\n");
1375 // Check if the hash of the key he gave us matches the hash in the URL.
1376 char *fingerprint = line + 2;
1379 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1380 fprintf(stderr, "Could not create digest\n%s\n", line + 2);
1385 if(memcmp(hishash, hash, 18)) {
1386 fprintf(stderr, "Peer has an invalid key!\n%s\n", line + 2);
1392 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1399 // Start an SPTPS session
1400 if(!sptps_start(&sptps, NULL, true, false, key, hiskey, "tinc invitation", 15, invitation_send, invitation_receive)) {
1406 // Feed rest of input buffer to SPTPS
1407 if(!sptps_receive_data(&sptps, buffer, blen)) {
1412 while((len = recv(sock, line, sizeof(line), 0))) {
1414 if(sockwouldblock(sockerrno)) {
1420 // If socket has been shut down, recv() on Windows returns -1 and sets sockerrno
1421 // to WSAESHUTDOWN, while on UNIX-like operating systems recv() returns 0, so we
1422 // have to do an explicit check here.
1423 if(sockshutdown(sockerrno)) {
1428 fprintf(stderr, "Error reading data from %s port %s: %s\n", address, port, sockstrerror(sockerrno));
1436 size_t done = sptps_receive_data(&sptps, p, len);
1443 len -= (ssize_t) done;
1455 fprintf(stderr, "Invitation cancelled.\n");
1462 fprintf(stderr, "Invalid invitation URL.\n");