+ logger(mesh, MESHLINK_DEBUG, "Could not read directory %s: %s\n", filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ errno = 0;
+ int count = 0;
+ struct dirent *ent;
+ time_t deadline = time(NULL) - 604800; // 1 week in the past
+
+ while((ent = readdir(dir))) {
+ if(strlen(ent->d_name) != 24) {
+ continue;
+ }
+
+ char invname[PATH_MAX];
+ struct stat st;
+
+ if(snprintf(invname, sizeof(invname), "%s" SLASH "%s", filename, ent->d_name) >= PATH_MAX) {
+ logger(mesh, MESHLINK_DEBUG, "Filename too long: %s" SLASH "%s", filename, ent->d_name);
+ continue;
+ }
+
+ if(!stat(invname, &st)) {
+ if(mesh->invitation_key && deadline < st.st_mtime) {
+ count++;
+ } else {
+ unlink(invname);
+ }
+ } else {
+ logger(mesh, MESHLINK_DEBUG, "Could not stat %s: %s\n", invname, strerror(errno));
+ errno = 0;
+ }
+ }
+
+ if(errno) {
+ logger(mesh, MESHLINK_DEBUG, "Error while reading directory %s: %s\n", filename, strerror(errno));
+ closedir(dir);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ closedir(dir);
+
+ snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "ecdsa_key.priv", mesh->confbase);
+
+ // Remove the key if there are no outstanding invitations.
+ if(!count) {
+ unlink(filename);
+
+ if(mesh->invitation_key) {
+ ecdsa_free(mesh->invitation_key);
+ mesh->invitation_key = NULL;
+ }
+ }
+
+ if(mesh->invitation_key) {
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return true;
+ }
+
+ // Create a new key if necessary.
+ FILE *f = fopen(filename, "rb");
+
+ if(!f) {
+ if(errno != ENOENT) {
+ logger(mesh, MESHLINK_DEBUG, "Could not read %s: %s\n", filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ mesh->invitation_key = ecdsa_generate();
+
+ if(!mesh->invitation_key) {
+ logger(mesh, MESHLINK_DEBUG, "Could not generate a new key!\n");
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ f = fopen(filename, "wb");
+
+ if(!f) {
+ logger(mesh, MESHLINK_DEBUG, "Could not write %s: %s\n", filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ chmod(filename, 0600);
+ ecdsa_write_pem_private_key(mesh->invitation_key, f);
+ fclose(f);
+ } else {
+ mesh->invitation_key = ecdsa_read_pem_private_key(f);
+ fclose(f);
+
+ if(!mesh->invitation_key) {
+ logger(mesh, MESHLINK_DEBUG, "Could not read private key from %s\n", filename);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ }
+ }
+
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return mesh->invitation_key;
+}
+
+bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
+ if(!mesh || !node || !address) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(!is_valid_hostname(address)) {
+ logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(port && !is_valid_port(port)) {
+ logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ char *canonical_address;
+
+ if(port) {
+ xasprintf(&canonical_address, "%s %s", address, port);
+ } else {
+ canonical_address = xstrdup(address);
+ }
+
+ pthread_mutex_lock(&(mesh->mesh_mutex));
+ bool rval = modify_config_file(mesh, node->name, "CanonicalAddress", canonical_address, 1);
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+
+ free(canonical_address);
+ return rval;
+}
+
+bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
+ return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
+}
+
+bool meshlink_add_external_address(meshlink_handle_t *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ char *address = meshlink_get_external_address(mesh);
+
+ if(!address) {
+ return false;
+ }
+
+ bool rval = false;
+
+ pthread_mutex_lock(&(mesh->mesh_mutex));
+ rval = append_config_file(mesh, mesh->self->name, "Address", address);
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+
+ free(address);
+ return rval;
+}
+
+int meshlink_get_port(meshlink_handle_t *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return -1;
+ }
+
+ if(!mesh->myport) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ return -1;
+ }
+
+ return atoi(mesh->myport);
+}
+
+bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
+ if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(mesh->myport && port == atoi(mesh->myport)) {
+ return true;
+ }
+
+ if(!try_bind(port)) {
+ meshlink_errno = MESHLINK_ENETWORK;
+ return false;
+ }
+
+ bool rval = false;
+
+ pthread_mutex_lock(&(mesh->mesh_mutex));
+
+ if(mesh->threadstarted) {
+ meshlink_errno = MESHLINK_EINVAL;
+ goto done;
+ }
+
+ close_network_connections(mesh);
+ exit_configuration(&mesh->config);
+
+ char portstr[10];
+ snprintf(portstr, sizeof(portstr), "%d", port);
+ portstr[sizeof(portstr) - 1] = 0;
+
+ modify_config_file(mesh, mesh->name, "Port", portstr, true);
+
+ init_configuration(&mesh->config);
+
+ if(!read_server_config(mesh)) {
+ meshlink_errno = MESHLINK_ESTORAGE;
+ } else if(!setup_network(mesh)) {
+ meshlink_errno = MESHLINK_ENETWORK;
+ } else {
+ rval = true;
+ }
+
+done:
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+
+ return rval;
+}
+
+void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
+ mesh->invitation_timeout = timeout;
+}
+
+char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ pthread_mutex_lock(&(mesh->mesh_mutex));
+
+ // Check validity of the new node's name
+ if(!check_id(name)) {
+ logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ // Ensure no host configuration file with that name exists
+ char filename[PATH_MAX];
+ snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, name);
+
+ if(!access(filename, F_OK)) {
+ logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
+ meshlink_errno = MESHLINK_EEXIST;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ // Ensure no other nodes know about this name
+ if(meshlink_get_node(mesh, name)) {
+ logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
+ meshlink_errno = MESHLINK_EEXIST;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ // Get the local address
+ char *address = get_my_hostname(mesh, flags);
+
+ if(!address) {
+ logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
+ meshlink_errno = MESHLINK_ERESOLV;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ if(!refresh_invitation_key(mesh)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ char hash[64];
+
+ // Create a hash of the key.
+ char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
+ sha512(fingerprint, strlen(fingerprint), hash);
+ b64encode_urlsafe(hash, hash, 18);
+
+ // Create a random cookie for this invitation.
+ char cookie[25];
+ randomize(cookie, 18);
+
+ // Create a filename that doesn't reveal the cookie itself
+ char buf[18 + strlen(fingerprint)];
+ char cookiehash[64];
+ memcpy(buf, cookie, 18);
+ memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
+ sha512(buf, sizeof(buf), cookiehash);
+ b64encode_urlsafe(cookiehash, cookiehash, 18);
+
+ b64encode_urlsafe(cookie, cookie, 18);
+
+ free(fingerprint);
+
+ // Create a file containing the details of the invitation.
+ snprintf(filename, sizeof(filename), "%s" SLASH "invitations" SLASH "%s", mesh->confbase, cookiehash);
+ int ifd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
+
+ if(!ifd) {
+ logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ FILE *f = fdopen(ifd, "w");
+
+ if(!f) {
+ abort();
+ }
+
+ // Fill in the details.
+ fprintf(f, "Name = %s\n", name);
+ fprintf(f, "ConnectTo = %s\n", mesh->self->name);
+
+ // Copy Broadcast and Mode
+ snprintf(filename, sizeof(filename), "%s" SLASH "meshlink.conf", mesh->confbase);
+ FILE *tc = fopen(filename, "r");
+
+ if(tc) {
+ char buf[1024];
+
+ while(fgets(buf, sizeof(buf), tc)) {
+ if((!strncasecmp(buf, "Mode", 4) && strchr(" \t=", buf[4]))
+ || (!strncasecmp(buf, "Broadcast", 9) && strchr(" \t=", buf[9]))) {
+ fputs(buf, f);
+
+ // Make sure there is a newline character.
+ if(!strchr(buf, '\n')) {
+ fputc('\n', f);
+ }
+ }
+ }
+
+ fclose(tc);
+ } else {
+ logger(mesh, MESHLINK_DEBUG, "Could not create %s: %s\n", filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ fprintf(f, "#---------------------------------------------------------------#\n");
+ fprintf(f, "Name = %s\n", mesh->self->name);
+
+ snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
+ fcopy(f, filename);
+ fclose(f);
+
+ // Create an URL from the local address, key hash and cookie
+ char *url;
+ xasprintf(&url, "%s/%s%s", address, hash, cookie);
+ free(address);
+
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return url;
+}
+
+char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
+ return meshlink_invite_ex(mesh, name, 0);
+}
+
+bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
+ if(!mesh || !invitation) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&(mesh->mesh_mutex));
+
+ //Before doing meshlink_join make sure we are not connected to another mesh
+ if(mesh->threadstarted) {
+ logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
+ char copy[strlen(invitation) + 1];
+ strcpy(copy, invitation);
+
+ // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
+
+ char *slash = strchr(copy, '/');
+
+ if(!slash) {
+ goto invalid;
+ }
+
+ *slash++ = 0;
+
+ if(strlen(slash) != 48) {
+ goto invalid;
+ }
+
+ char *address = copy;
+ char *port = NULL;
+
+ if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
+ goto invalid;
+ }
+
+ // Generate a throw-away key for the invitation.
+ ecdsa_t *key = ecdsa_generate();
+
+ if(!key) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ char *b64key = ecdsa_get_base64_public_key(key);
+ char *comma;
+ mesh->sock = -1;
+
+ while(address && *address) {
+ // We allow commas in the address part to support multiple addresses in one invitation URL.
+ comma = strchr(address, ',');
+
+ if(comma) {
+ *comma++ = 0;
+ }
+
+ // Split of the port
+ port = strrchr(address, ':');
+
+ if(!port) {
+ goto invalid;
+ }
+
+ *port++ = 0;
+
+ // IPv6 address are enclosed in brackets, per RFC 3986
+ if(*address == '[') {
+ address++;
+ char *bracket = strchr(address, ']');
+
+ if(!bracket) {
+ goto invalid;
+ }
+
+ *bracket++ = 0;
+
+ if(*bracket) {
+ goto invalid;
+ }
+ }
+
+ // Connect to the meshlink daemon mentioned in the URL.
+ struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
+
+ if(ai) {
+ for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
+ mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
+
+ if(mesh->sock == -1) {
+ logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
+ meshlink_errno = MESHLINK_ENETWORK;
+ continue;
+ }
+
+ set_timeout(mesh->sock, 5000);
+
+ if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
+ logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
+ meshlink_errno = MESHLINK_ENETWORK;
+ closesocket(mesh->sock);
+ mesh->sock = -1;
+ continue;
+ }
+ }
+
+ freeaddrinfo(ai);
+ } else {
+ meshlink_errno = MESHLINK_ERESOLV;
+ }
+
+ if(mesh->sock != -1 || !comma) {
+ break;
+ }
+
+ address = comma;
+ }
+
+ if(mesh->sock == -1) {
+ pthread_mutex_unlock(&mesh->mesh_mutex);
+ return false;
+ }
+
+ logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
+
+ // Tell him we have an invitation, and give him our throw-away key.
+
+ mesh->blen = 0;
+
+ if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
+ logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
+ closesocket(mesh->sock);
+ meshlink_errno = MESHLINK_ENETWORK;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ free(b64key);
+
+ char hisname[4096] = "";
+ int code, hismajor, hisminor = 0;
+
+ if(!recvline(mesh, sizeof(mesh)->line) || sscanf(mesh->line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(mesh, sizeof(mesh)->line) || !rstrip(mesh->line) || sscanf(mesh->line, "%d ", &code) != 1 || code != ACK || strlen(mesh->line) < 3) {
+ logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
+ closesocket(mesh->sock);
+ meshlink_errno = MESHLINK_ENETWORK;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ // Check if the hash of the key he gave us matches the hash in the URL.
+ char *fingerprint = mesh->line + 2;
+ char hishash[64];
+
+ if(sha512(fingerprint, strlen(fingerprint), hishash)) {
+ logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ if(memcmp(hishash, mesh->hash, 18)) {
+ logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
+ meshlink_errno = MESHLINK_EPEER;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+
+ }
+
+ ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
+
+ if(!hiskey) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ // Start an SPTPS session
+ if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ // Feed rest of input buffer to SPTPS
+ if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
+ meshlink_errno = MESHLINK_EPEER;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ int len;
+
+ while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
+ if(len < 0) {
+ if(errno == EINTR) {
+ continue;
+ }
+
+ logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
+ meshlink_errno = MESHLINK_ENETWORK;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
+ meshlink_errno = MESHLINK_EPEER;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+ }
+
+ sptps_stop(&mesh->sptps);
+ ecdsa_free(hiskey);
+ ecdsa_free(key);
+ closesocket(mesh->sock);
+
+ if(!mesh->success) {
+ logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
+ meshlink_errno = MESHLINK_EPEER;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+ }
+
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return true;
+
+invalid:
+ logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return false;
+}
+
+char *meshlink_export(meshlink_handle_t *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ pthread_mutex_lock(&(mesh->mesh_mutex));
+
+ char filename[PATH_MAX];
+ snprintf(filename, sizeof(filename), "%s" SLASH "hosts" SLASH "%s", mesh->confbase, mesh->self->name);
+ FILE *f = fopen(filename, "r");
+
+ if(!f) {
+ logger(mesh, MESHLINK_DEBUG, "Could not open %s: %s\n", filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ fseek(f, 0, SEEK_END);
+ int fsize = ftell(f);
+ rewind(f);
+
+ size_t len = fsize + 9 + strlen(mesh->self->name);
+ char *buf = xmalloc(len);
+ snprintf(buf, len, "Name = %s\n", mesh->self->name);
+
+ if(fread(buf + len - fsize - 1, fsize, 1, f) != 1) {
+ logger(mesh, MESHLINK_DEBUG, "Error reading from %s: %s\n", filename, strerror(errno));
+ fclose(f);
+ free(buf);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return NULL;
+ }
+
+ fclose(f);
+ buf[len - 1] = 0;
+
+ pthread_mutex_unlock(&(mesh->mesh_mutex));
+ return buf;
+}
+
+bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
+ if(!mesh || !data) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;