+#ifdef FD_CLOEXEC
+ fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
+#endif
+
+#ifdef HAVE_MINGW
+ // TODO: use _locking()?
+#else
+
+ if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
+ logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
+ fclose(lockfile);
+ meshlink_errno = MESHLINK_EBUSY;
+ return false;
+ }
+
+#endif
+
+ if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
+ logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
+ return false;
+ }
+
+ if(unlink(lockfilename)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
+ fclose(lockfile);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return false;
+ }
+
+ fclose(lockfile);
+
+ if(!sync_path(confbase)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return false;
+ }
+
+ return true;
+}
+
+void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->receive_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->connection_try_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->node_status_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->node_pmtu_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->node_duplicate_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
+ if(mesh) {
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->log_cb = cb;
+ mesh->log_level = cb ? level : 0;
+ pthread_mutex_unlock(&mesh->mutex);
+ } else {
+ global_log_cb = cb;
+ global_log_level = cb ? level : 0;
+ }
+}
+
+void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->error_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
+ meshlink_packethdr_t *hdr;
+
+ if(len >= MAXSIZE - sizeof(*hdr)) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ node_t *n = (node_t *)destination;
+
+ if(n->status.blacklisted) {
+ logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
+ meshlink_errno = MESHLINK_EBLACKLISTED;
+ return false;
+ }
+
+ // Prepare the packet
+ packet->probe = false;
+ packet->tcp = false;
+ packet->len = len + sizeof(*hdr);
+
+ hdr = (meshlink_packethdr_t *)packet->data;
+ memset(hdr, 0, sizeof(*hdr));
+ // leave the last byte as 0 to make sure strings are always
+ // null-terminated if they are longer than the buffer
+ strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
+ strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
+
+ memcpy(packet->data + sizeof(*hdr), data, len);
+
+ return true;
+}
+
+static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
+ assert(mesh);
+ assert(destination);
+ assert(data);
+ assert(len);
+
+ // Prepare the packet
+ if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
+ return false;
+ }
+
+ // Send it immediately
+ route(mesh, mesh->self, mesh->packet);
+
+ return true;
+}
+
+bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
+ // Validate arguments
+ if(!mesh || !destination) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(!len) {
+ return true;
+ }
+
+ if(!data) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ // Prepare the packet
+ vpn_packet_t *packet = malloc(sizeof(*packet));
+
+ if(!packet) {
+ meshlink_errno = MESHLINK_ENOMEM;
+ return false;
+ }
+
+ if(!prepare_packet(mesh, destination, data, len, packet)) {
+ free(packet);
+ }
+
+ // Queue it
+ if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
+ free(packet);
+ meshlink_errno = MESHLINK_ENOMEM;
+ return false;
+ }
+
+ logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
+
+ // Notify event loop
+ signal_trigger(&mesh->loop, &mesh->datafromapp);
+
+ return true;
+}
+
+void meshlink_send_from_queue(event_loop_t *loop, void *data) {
+ (void)loop;
+ meshlink_handle_t *mesh = data;
+
+ logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
+
+ for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
+ logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
+ mesh->self->in_packets++;
+ mesh->self->in_bytes += packet->len;
+ route(mesh, mesh->self, packet);
+ free(packet);
+ }
+}
+
+ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
+ if(!mesh || !destination) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return -1;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ node_t *n = (node_t *)destination;
+
+ if(!n->status.reachable) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return 0;
+
+ } else if(n->mtuprobes > 30 && n->minmtu) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return n->minmtu;
+ } else {
+ pthread_mutex_unlock(&mesh->mutex);
+ return MTU;
+ }
+}
+
+char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ node_t *n = (node_t *)node;
+
+ if(!node_read_public_key(mesh, n) || !n->ecdsa) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
+
+ if(!fingerprint) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+ return fingerprint;
+}
+
+meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ return (meshlink_node_t *)mesh->self;
+}
+
+meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
+ if(!mesh || !name) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ node_t *n = NULL;
+
+ pthread_mutex_lock(&mesh->mutex);
+ n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
+ pthread_mutex_unlock(&mesh->mutex);
+
+ if(!n) {
+ meshlink_errno = MESHLINK_ENOENT;
+ }
+
+ return (meshlink_node_t *)n;
+}
+
+meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
+ if(!mesh || !name) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ meshlink_submesh_t *submesh = NULL;
+
+ pthread_mutex_lock(&mesh->mutex);
+ submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
+ pthread_mutex_unlock(&mesh->mutex);
+
+ if(!submesh) {
+ meshlink_errno = MESHLINK_ENOENT;
+ }
+
+ return submesh;
+}
+
+meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
+ if(!mesh || !nmemb || (*nmemb && !nodes)) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ meshlink_node_t **result;
+
+ //lock mesh->nodes
+ pthread_mutex_lock(&mesh->mutex);
+
+ *nmemb = mesh->nodes->count;
+ result = realloc(nodes, *nmemb * sizeof(*nodes));
+
+ if(result) {
+ meshlink_node_t **p = result;
+
+ for splay_each(node_t, n, mesh->nodes) {
+ *p++ = (meshlink_node_t *)n;
+ }
+ } else {
+ *nmemb = 0;
+ free(nodes);
+ meshlink_errno = MESHLINK_ENOMEM;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return result;
+}
+
+static meshlink_node_t **meshlink_get_all_nodes_by_condition(meshlink_handle_t *mesh, const void *condition, meshlink_node_t **nodes, size_t *nmemb, search_node_by_condition_t search_node) {
+ meshlink_node_t **result;
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ *nmemb = 0;
+
+ for splay_each(node_t, n, mesh->nodes) {
+ if(search_node(n, condition)) {
+ ++*nmemb;
+ }
+ }
+
+ if(*nmemb == 0) {
+ free(nodes);
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ result = realloc(nodes, *nmemb * sizeof(*nodes));
+
+ if(result) {
+ meshlink_node_t **p = result;
+
+ for splay_each(node_t, n, mesh->nodes) {
+ if(search_node(n, condition)) {
+ *p++ = (meshlink_node_t *)n;
+ }
+ }
+ } else {
+ *nmemb = 0;
+ free(nodes);
+ meshlink_errno = MESHLINK_ENOMEM;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return result;
+}
+
+static bool search_node_by_dev_class(const node_t *node, const void *condition) {
+ dev_class_t *devclass = (dev_class_t *)condition;
+
+ if(*devclass == (dev_class_t)node->devclass) {
+ return true;
+ }
+
+ return false;
+}
+
+static bool search_node_by_submesh(const node_t *node, const void *condition) {
+ if(condition == node->submesh) {
+ return true;
+ }
+
+ return false;
+}
+
+struct time_range {
+ time_t start;
+ time_t end;
+};
+
+static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
+ const struct time_range *range = condition;
+ time_t start = node->last_reachable;
+ time_t end = node->last_unreachable;
+
+ if(end < start) {
+ end = time(NULL);
+
+ if(end < start) {
+ start = end;
+ }
+ }
+
+ if(range->end >= range->start) {
+ return start <= range->end && end >= range->start;
+ } else {
+ return start > range->start || end < range->end;
+ }
+}
+
+meshlink_node_t **meshlink_get_all_nodes_by_dev_class(meshlink_handle_t *mesh, dev_class_t devclass, meshlink_node_t **nodes, size_t *nmemb) {
+ if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
+}
+
+meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
+ if(!mesh || !submesh || !nmemb) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
+}
+
+meshlink_node_t **meshlink_get_all_nodes_by_last_reachable(meshlink_handle_t *mesh, time_t start, time_t end, meshlink_node_t **nodes, size_t *nmemb) {
+ if(!mesh || !nmemb) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ struct time_range range = {start, end};
+
+ return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
+}
+
+dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return -1;
+ }
+
+ dev_class_t devclass;
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ devclass = ((node_t *)node)->devclass;
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return devclass;
+}
+
+meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ node_t *n = (node_t *)node;
+
+ meshlink_submesh_t *s;
+
+ s = (meshlink_submesh_t *)n->submesh;
+
+ return s;
+}
+
+bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ node_t *n = (node_t *)node;
+ bool reachable;
+
+ pthread_mutex_lock(&mesh->mutex);
+ reachable = n->status.reachable && !n->status.blacklisted;
+
+ if(last_reachable) {
+ *last_reachable = n->last_reachable;
+ }
+
+ if(last_unreachable) {
+ *last_unreachable = n->last_unreachable;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return reachable;
+}
+
+bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
+ if(!mesh || !data || !len || !signature || !siglen) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(*siglen < MESHLINK_SIGLEN) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ *siglen = MESHLINK_SIGLEN;
+ pthread_mutex_unlock(&mesh->mutex);
+ return true;
+}
+
+bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
+ if(!mesh || !source || !data || !len || !signature) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(siglen != MESHLINK_SIGLEN) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ bool rval = false;
+
+ struct node_t *n = (struct node_t *)source;
+
+ if(!node_read_public_key(mesh, n)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ rval = false;
+ } else {
+ rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+ return rval;
+}
+
+static bool refresh_invitation_key(meshlink_handle_t *mesh) {
+ pthread_mutex_lock(&mesh->mutex);
+
+ size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
+
+ if(!count) {
+ // TODO: Update invitation key if necessary?
+ }
+
+ pthread_mutex_unlock(&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->mutex);
+
+ node_t *n = (node_t *)node;
+ free(n->canonical_address);
+ n->canonical_address = canonical_address;
+
+ if(!node_write_config(mesh, n)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return config_sync(mesh, "current");
+}
+
+bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
+ if(!mesh || !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 *combo;
+
+ if(port) {
+ xasprintf(&combo, "%s/%s", address, port);
+ } else {
+ combo = xstrdup(address);
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ if(!mesh->invitation_addresses) {
+ mesh->invitation_addresses = list_alloc((list_action_t)free);
+ }
+
+ list_insert_tail(mesh->invitation_addresses, combo);
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return true;
+}
+
+void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ if(mesh->invitation_addresses) {
+ list_delete_list(mesh->invitation_addresses);
+ mesh->invitation_addresses = NULL;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+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 = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
+ 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;
+ }
+
+ int port;
+
+ pthread_mutex_lock(&mesh->mutex);
+ port = atoi(mesh->myport);
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return port;
+}
+
+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(mesh, port)) {
+ meshlink_errno = MESHLINK_ENETWORK;
+ return false;
+ }
+
+ devtool_trybind_probe();
+
+ bool rval = false;
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ if(mesh->threadstarted) {
+ meshlink_errno = MESHLINK_EINVAL;
+ goto done;
+ }
+
+ free(mesh->myport);
+ xasprintf(&mesh->myport, "%d", port);
+
+ /* Close down the network. This also deletes mesh->self. */
+ close_network_connections(mesh);
+
+ /* Recreate mesh->self. */
+ mesh->self = new_node();
+ mesh->self->name = xstrdup(mesh->name);
+ mesh->self->devclass = mesh->devclass;
+ mesh->self->session_id = mesh->session_id;
+ xasprintf(&mesh->myport, "%d", port);
+
+ if(!node_read_public_key(mesh, mesh->self)) {
+ logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
+ meshlink_errno = MESHLINK_ESTORAGE;
+ free_node(mesh->self);
+ mesh->self = NULL;
+ goto done;
+ } else if(!setup_network(mesh)) {
+ meshlink_errno = MESHLINK_ENETWORK;
+ goto done;
+ }
+
+ /* Rebuild our own list of recent addresses */
+ memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
+ add_local_addresses(mesh);
+
+ /* Write meshlink.conf with the updated port number */
+ write_main_config_files(mesh);
+
+ rval = config_sync(mesh, "current");
+
+done:
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return rval && meshlink_get_port(mesh) == port;
+}
+
+void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
+ mesh->invitation_timeout = timeout;
+}
+
+char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
+ meshlink_submesh_t *s = NULL;
+
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ if(submesh) {
+ s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
+
+ if(s != submesh) {
+ logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+ } else {
+ s = (meshlink_submesh_t *)mesh->self->submesh;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ // Check validity of the new node's name
+ if(!check_id(name)) {
+ logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ // Ensure no host configuration file with that name exists
+ if(config_exists(mesh, "current", name)) {
+ logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
+ meshlink_errno = MESHLINK_EEXIST;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ // Ensure no other nodes know about this name
+ if(lookup_node(mesh, name)) {
+ logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
+ meshlink_errno = MESHLINK_EEXIST;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ // Get the local address
+ char *address = get_my_hostname(mesh, flags);
+
+ if(!address) {
+ logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
+ meshlink_errno = MESHLINK_ERESOLV;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ if(!refresh_invitation_key(mesh)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ // If we changed our own host config file, write it out now
+ if(mesh->self->status.dirty) {
+ if(!node_write_config(mesh, mesh->self)) {
+ logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
+ pthread_mutex_unlock(&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);
+
+ /* Construct the invitation file */
+ uint8_t outbuf[4096];
+ packmsg_output_t inv = {outbuf, sizeof(outbuf)};
+
+ packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
+ packmsg_add_str(&inv, name);
+ packmsg_add_str(&inv, s ? s->name : CORE_MESH);
+ packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
+
+ /* TODO: Add several host config files to bootstrap connections.
+ * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
+ * and are not blacklisted.
+ */
+ config_t configs[5];
+ memset(configs, 0, sizeof(configs));
+ int count = 0;
+
+ if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
+ count++;
+ }
+
+ /* Append host config files to the invitation file */
+ packmsg_add_array(&inv, count);
+
+ for(int i = 0; i < count; i++) {
+ packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
+ config_free(&configs[i]);
+ }
+
+ config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
+
+ if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
+ logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ // 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->mutex);
+ return url;
+}
+
+char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
+ return meshlink_invite_ex(mesh, submesh, name, 0);
+}
+
+bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
+ if(!mesh || !invitation) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ join_state_t state = {
+ .mesh = mesh,
+ .sock = -1,
+ };
+
+ ecdsa_t *key = NULL;
+ ecdsa_t *hiskey = NULL;
+
+ //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
+ char copy[strlen(invitation) + 1];
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ //Before doing meshlink_join make sure we are not connected to another mesh
+ if(mesh->threadstarted) {
+ logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ goto exit;
+ }
+
+ // Refuse to join a mesh if we are already part of one. We are part of one if we know at least one other node.
+ if(mesh->nodes->count > 1) {
+ logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ goto exit;
+ }
+
+ 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, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
+ goto invalid;
+ }
+
+ if(mesh->inviter_commits_first) {
+ memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
+ }
+
+ // Generate a throw-away key for the invitation.
+ key = ecdsa_generate();
+
+ if(!key) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ goto exit;
+ }
+
+ char *b64key = ecdsa_get_base64_public_key(key);
+ char *comma;
+
+ 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 = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), 5);
+
+ if(ai) {
+ for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
+ state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
+
+ if(state.sock == -1) {
+ logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
+ meshlink_errno = MESHLINK_ENETWORK;
+ continue;
+ }
+
+ set_timeout(state.sock, 5000);
+
+ if(connect(state.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(state.sock);
+ state.sock = -1;
+ continue;
+ }
+
+ break;
+ }
+
+ freeaddrinfo(ai);
+ } else {
+ meshlink_errno = MESHLINK_ERESOLV;
+ }
+
+ if(state.sock != -1 || !comma) {
+ break;
+ }
+
+ address = comma;
+ }
+
+ if(state.sock == -1) {
+ goto exit;
+ }
+
+ 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.
+
+ state.blen = 0;
+
+ if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
+ logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
+ meshlink_errno = MESHLINK_ENETWORK;
+ goto exit;
+ }
+
+ free(b64key);
+
+ char hisname[4096] = "";
+ int code, hismajor, hisminor = 0;
+
+ if(!recvline(&state) || sscanf(state.line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(&state) || !rstrip(state.line) || sscanf(state.line, "%d ", &code) != 1 || code != ACK || strlen(state.line) < 3) {
+ logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
+ meshlink_errno = MESHLINK_ENETWORK;
+ goto exit;
+ }
+
+ // Check if the hash of the key he gave us matches the hash in the URL.
+ char *fingerprint = state.line + 2;
+ char hishash[64];
+
+ if(sha512(fingerprint, strlen(fingerprint), hishash)) {
+ logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
+ meshlink_errno = MESHLINK_EINTERNAL;
+ goto exit;
+ }
+
+ if(memcmp(hishash, state.hash, 18)) {
+ logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
+ meshlink_errno = MESHLINK_EPEER;
+ goto exit;
+ }
+
+ hiskey = ecdsa_set_base64_public_key(fingerprint);
+
+ if(!hiskey) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ goto exit;
+ }
+
+ // Start an SPTPS session
+ if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ goto exit;
+ }
+
+ // Feed rest of input buffer to SPTPS
+ if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
+ meshlink_errno = MESHLINK_EPEER;
+ goto exit;
+ }
+
+ ssize_t len;
+ logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
+
+ while((len = recv(state.sock, state.line, sizeof(state.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;
+ goto exit;
+ }
+
+ if(!sptps_receive_data(&state.sptps, state.line, len)) {
+ meshlink_errno = MESHLINK_EPEER;
+ goto exit;
+ }
+ }
+
+ if(!state.success) {
+ logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
+ meshlink_errno = MESHLINK_EPEER;
+ goto exit;
+ }
+
+ sptps_stop(&state.sptps);
+ ecdsa_free(hiskey);
+ ecdsa_free(key);
+ closesocket(state.sock);
+
+ pthread_mutex_unlock(&mesh->mutex);
+ return true;
+
+invalid:
+ logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
+ meshlink_errno = MESHLINK_EINVAL;
+exit:
+ sptps_stop(&state.sptps);
+ ecdsa_free(hiskey);
+ ecdsa_free(key);
+
+ if(state.sock != -1) {
+ closesocket(state.sock);
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+}
+
+char *meshlink_export(meshlink_handle_t *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ // Create a config file on the fly.
+
+ uint8_t buf[4096];
+ packmsg_output_t out = {buf, sizeof(buf)};
+ packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
+ packmsg_add_str(&out, mesh->name);
+ packmsg_add_str(&out, CORE_MESH);
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ packmsg_add_int32(&out, mesh->self->devclass);
+ packmsg_add_bool(&out, mesh->self->status.blacklisted);
+ packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
+ packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
+
+ uint32_t count = 0;
+
+ for(uint32_t i = 0; i < MAX_RECENT; i++) {
+ if(mesh->self->recent[i].sa.sa_family) {
+ count++;
+ } else {
+ break;
+ }
+ }
+
+ packmsg_add_array(&out, count);
+
+ for(uint32_t i = 0; i < count; i++) {
+ packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
+ }
+
+ packmsg_add_int64(&out, 0);
+ packmsg_add_int64(&out, 0);
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ if(!packmsg_output_ok(&out)) {
+ logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
+ meshlink_errno = MESHLINK_EINTERNAL;
+ return NULL;
+ }
+
+ // Prepare a base64-encoded packmsg array containing our config file
+
+ uint32_t len = packmsg_output_size(&out, buf);
+ uint32_t len2 = ((len + 4) * 4) / 3 + 4;
+ uint8_t *buf2 = xmalloc(len2);
+ packmsg_output_t out2 = {buf2, len2};
+ packmsg_add_array(&out2, 1);
+ packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
+
+ if(!packmsg_output_ok(&out2)) {
+ logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
+ meshlink_errno = MESHLINK_EINTERNAL;
+ free(buf2);
+ return NULL;
+ }
+
+ b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
+
+ return (char *)buf2;
+}
+
+bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
+ if(!mesh || !data) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ size_t datalen = strlen(data);
+ uint8_t *buf = xmalloc(datalen);
+ int buflen = b64decode(data, buf, datalen);
+
+ if(!buflen) {
+ logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
+ meshlink_errno = MESHLINK_EPEER;
+ return false;
+ }
+
+ packmsg_input_t in = {buf, buflen};
+ uint32_t count = packmsg_get_array(&in);
+
+ if(!count) {
+ logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
+ meshlink_errno = MESHLINK_EPEER;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ while(count--) {
+ const void *data;
+ uint32_t len = packmsg_get_bin_raw(&in, &data);
+
+ if(!len) {
+ break;
+ }
+
+ packmsg_input_t in2 = {data, len};
+ uint32_t version = packmsg_get_uint32(&in2);
+ char *name = packmsg_get_str_dup(&in2);
+
+ if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
+ free(name);
+ packmsg_input_invalidate(&in);
+ break;
+ }
+
+ if(!check_id(name)) {
+ free(name);
+ break;
+ }
+
+ node_t *n = lookup_node(mesh, name);
+
+ if(n) {
+ logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
+ free(name);
+ continue;
+ }
+
+ n = new_node();
+ n->name = name;
+
+ config_t config = {data, len};
+
+ if(!node_read_from_config(mesh, n, &config)) {
+ free_node(n);
+ packmsg_input_invalidate(&in);
+ break;
+ }
+
+ /* Clear the reachability times, since we ourself have never seen these nodes yet */
+ n->last_reachable = 0;
+ n->last_unreachable = 0;
+
+ if(!node_write_config(mesh, n)) {
+ free_node(n);
+ return false;
+ }
+
+ node_add(mesh, n);
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ free(buf);
+
+ if(!packmsg_done(&in)) {
+ logger(mesh, MESHLINK_ERROR, "Invalid data\n");
+ meshlink_errno = MESHLINK_EPEER;
+ return false;
+ }
+
+ if(!config_sync(mesh, "current")) {
+ return false;
+ }
+
+ return true;
+}
+
+static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
+ if(n == mesh->self) {
+ logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(n->status.blacklisted) {
+ logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
+ return true;
+ }
+
+ n->status.blacklisted = true;
+
+ /* Immediately shut down any connections we have with the blacklisted node.
+ * We can't call terminate_connection(), because we might be called from a callback function.
+ */
+ for list_each(connection_t, c, mesh->connections) {
+ if(c->node == n) {
+ shutdown(c->socket, SHUT_RDWR);
+ }
+ }
+
+ utcp_abort_all_connections(n->utcp);
+
+ n->mtu = 0;
+ n->minmtu = 0;
+ n->maxmtu = MTU;
+ n->mtuprobes = 0;
+ n->status.udp_confirmed = false;
+
+ if(n->status.reachable) {
+ n->last_unreachable = time(NULL);
+ }
+
+ /* Graph updates will suppress status updates for blacklisted nodes, so we need to
+ * manually call the status callback if necessary.
+ */
+ if(n->status.reachable && mesh->node_status_cb) {
+ mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
+ }
+
+ return node_write_config(mesh, n) && config_sync(mesh, "current");
+}
+
+bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ if(!blacklist(mesh, (node_t *)node)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
+ return true;
+}
+
+bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
+ if(!mesh || !name) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ node_t *n = lookup_node(mesh, (char *)name);
+
+ if(!n) {
+ n = new_node();
+ n->name = xstrdup(name);
+ node_add(mesh, n);
+ }
+
+ if(!blacklist(mesh, (node_t *)n)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
+ return true;
+}
+
+static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
+ if(n == mesh->self) {
+ logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ if(!n->status.blacklisted) {
+ logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
+ return true;
+ }
+
+ n->status.blacklisted = false;
+
+ if(n->status.reachable) {
+ n->last_reachable = time(NULL);
+ update_node_status(mesh, n);
+ }
+
+ return node_write_config(mesh, n) && config_sync(mesh, "current");
+}
+
+bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ if(!whitelist(mesh, (node_t *)node)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
+ return true;
+}
+
+bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
+ if(!mesh || !name) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ node_t *n = lookup_node(mesh, (char *)name);
+
+ if(!n) {
+ n = new_node();
+ n->name = xstrdup(name);
+ node_add(mesh, n);
+ }
+
+ if(!whitelist(mesh, (node_t *)n)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
+ return true;
+}
+
+void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
+ mesh->default_blacklist = blacklist;
+}
+
+bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
+
+ node_t *n = (node_t *)node;
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ /* Check that the node is not reachable */
+ if(n->status.reachable || n->connection) {
+ pthread_mutex_unlock(&mesh->mutex);
+ logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
+ return false;
+ }
+
+ /* Check that we don't have any active UTCP connections */
+ if(n->utcp && utcp_is_active(n->utcp)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
+ return false;
+ }
+
+ /* Check that we have no active connections to this node */
+ for list_each(connection_t, c, mesh->connections) {
+ if(c->node == n) {
+ pthread_mutex_unlock(&mesh->mutex);
+ logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
+ return false;
+ }
+ }
+
+ /* Remove any pending outgoings to this node */
+ if(mesh->outgoings) {
+ for list_each(outgoing_t, outgoing, mesh->outgoings) {
+ if(outgoing->node == n) {
+ list_delete_node(mesh->outgoings, node);
+ }
+ }
+ }
+
+ /* Delete the config file for this node */
+ if(!config_delete(mesh, "current", n->name)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
+
+ /* Delete the node struct and any remaining edges referencing this node */
+ node_del(mesh, n);
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ return config_sync(mesh, "current");
+}
+
+/* Hint that a hostname may be found at an address
+ * See header file for detailed comment.
+ */
+void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
+ if(!mesh || !node || !addr) {
+ meshlink_errno = EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ node_t *n = (node_t *)node;
+
+ if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
+ if(!node_write_config(mesh, n)) {
+ logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
+ }
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+ // @TODO do we want to fire off a connection attempt right away?
+}
+
+static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
+ (void)port;
+ node_t *n = utcp->priv;
+ meshlink_handle_t *mesh = n->mesh;
+ return mesh->channel_accept_cb;
+}
+
+static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
+ if(aio->data) {
+ if(aio->cb.buffer) {
+ aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
+ }
+ } else {
+ if(aio->cb.fd) {
+ aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
+ }
+ }
+}
+
+static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
+ meshlink_channel_t *channel = connection->priv;
+
+ if(!channel) {
+ abort();
+ }
+
+ node_t *n = channel->node;
+ meshlink_handle_t *mesh = n->mesh;
+
+ if(n->status.destroyed) {
+ meshlink_channel_close(mesh, channel);
+ return len;
+ }
+
+ const char *p = data;
+ size_t left = len;
+
+ while(channel->aio_receive) {
+ meshlink_aio_buffer_t *aio = channel->aio_receive;
+ size_t todo = aio->len - aio->done;
+
+ if(todo > left) {
+ todo = left;
+ }
+
+ if(aio->data) {
+ memcpy((char *)aio->data + aio->done, p, todo);
+ } else {
+ ssize_t result = write(aio->fd, p, todo);
+
+ if(result > 0) {
+ todo = result;
+ }
+ }
+
+ aio->done += todo;
+
+ if(aio->done == aio->len) {
+ channel->aio_receive = aio->next;
+ aio_signal(mesh, channel, aio);
+ free(aio);
+ }
+
+ p += todo;
+ left -= todo;
+
+ if(!left && len) {
+ return len;
+ }
+ }
+
+ if(channel->receive_cb) {
+ channel->receive_cb(mesh, channel, p, left);
+ }
+
+ return len;
+}
+
+static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
+ node_t *n = utcp_connection->utcp->priv;
+
+ if(!n) {
+ abort();
+ }
+
+ meshlink_handle_t *mesh = n->mesh;
+
+ if(!mesh->channel_accept_cb) {
+ return;
+ }
+
+ meshlink_channel_t *channel = xzalloc(sizeof(*channel));
+ channel->node = n;
+ channel->c = utcp_connection;
+
+ if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
+ utcp_accept(utcp_connection, channel_recv, channel);
+ } else {
+ free(channel);
+ }
+}
+
+static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
+ node_t *n = utcp->priv;
+
+ if(n->status.destroyed) {
+ return -1;
+ }
+
+ meshlink_handle_t *mesh = n->mesh;
+ return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
+}
+
+void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
+ if(!mesh || !channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ channel->receive_cb = cb;
+}
+
+static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
+ (void)mesh;
+ node_t *n = (node_t *)source;
+
+ if(!n->utcp) {
+ abort();
+ }
+
+ utcp_recv(n->utcp, data, len);
+}
+
+static void channel_poll(struct utcp_connection *connection, size_t len) {
+ meshlink_channel_t *channel = connection->priv;
+
+ if(!channel) {
+ abort();
+ }
+
+ node_t *n = channel->node;
+ meshlink_handle_t *mesh = n->mesh;
+ meshlink_aio_buffer_t *aio = channel->aio_send;
+
+ if(aio) {
+ /* We at least one AIO buffer. Send as much as possible form the first buffer. */
+ size_t left = aio->len - aio->done;
+ ssize_t sent;
+
+ if(len > left) {
+ len = left;
+ }
+
+ if(aio->data) {
+ sent = utcp_send(connection, (char *)aio->data + aio->done, len);
+ } else {
+ char buf[65536];
+ size_t todo = utcp_get_sndbuf_free(connection);
+
+ if(todo > left) {
+ todo = left;
+ }
+
+ if(todo > sizeof(buf)) {
+ todo = sizeof(buf);
+ }
+
+ ssize_t result = read(aio->fd, buf, todo);
+
+ if(result > 0) {
+ sent = utcp_send(connection, buf, result);
+ } else {
+ sent = result;
+ }
+ }
+
+ if(sent >= 0) {
+ aio->done += sent;
+ }
+
+ /* If the buffer is now completely sent, call the callback and dispose of it. */
+ if(aio->done >= aio->len) {
+ channel->aio_send = aio->next;
+ aio_signal(mesh, channel, aio);
+ free(aio);
+ }
+ } else {
+ if(channel->poll_cb) {
+ channel->poll_cb(mesh, channel, len);
+ } else {
+ utcp_set_poll_cb(connection, NULL);
+ }
+ }
+}
+
+void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
+ if(!mesh || !channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ channel->poll_cb = cb;
+ utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ mesh->channel_accept_cb = cb;
+ mesh->receive_cb = channel_receive;
+
+ for splay_each(node_t, n, mesh->nodes) {
+ if(!n->utcp && n != mesh->self) {
+ n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
+ utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
+ }
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
+ (void)mesh;
+
+ if(!channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ utcp_set_sndbuf(channel->c, size);
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
+ (void)mesh;
+
+ if(!channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ utcp_set_rcvbuf(channel->c, size);
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
+ if(data && len) {
+ abort(); // TODO: handle non-NULL data
+ }
+
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ node_t *n = (node_t *)node;
+
+ if(!n->utcp) {
+ n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
+ utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
+ mesh->receive_cb = channel_receive;
+
+ if(!n->utcp) {
+ meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+ }
+
+ if(n->status.blacklisted) {
+ logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
+ meshlink_errno = MESHLINK_EBLACKLISTED;
+ pthread_mutex_unlock(&mesh->mutex);
+ return NULL;
+ }
+
+ meshlink_channel_t *channel = xzalloc(sizeof(*channel));
+ channel->node = n;
+ channel->receive_cb = cb;
+
+ if(data && !len) {
+ channel->priv = (void *)data;
+ }
+
+ channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ if(!channel->c) {
+ meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
+ free(channel);
+ return NULL;
+ }
+
+ return channel;
+}
+
+meshlink_channel_t *meshlink_channel_open(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len) {
+ return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
+}
+
+void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
+ if(!mesh || !channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+ utcp_shutdown(channel->c, direction);
+ pthread_mutex_unlock(&mesh->mutex);
+}
+
+void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
+ if(!mesh || !channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ utcp_close(channel->c);
+
+ /* Clean up any outstanding AIO buffers. */
+ for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
+ next = aio->next;
+ aio_signal(mesh, channel, aio);
+ free(aio);
+ }
+
+ for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
+ next = aio->next;
+ aio_signal(mesh, channel, aio);
+ free(aio);
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ free(channel);
+}
+
+ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
+ if(!mesh || !channel) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return -1;
+ }
+
+ if(!len) {
+ return 0;
+ }
+
+ if(!data) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return -1;
+ }
+
+ // TODO: more finegrained locking.
+ // Ideally we want to put the data into the UTCP connection's send buffer.
+ // Then, preferably only if there is room in the receiver window,
+ // kick the meshlink thread to go send packets.
+
+ ssize_t retval;
+
+ pthread_mutex_lock(&mesh->mutex);
+
+ /* Disallow direct calls to utcp_send() while we still have AIO active. */
+ if(channel->aio_send) {
+ retval = 0;
+ } else {
+ retval = utcp_send(channel->c, data, len);
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+
+ if(retval < 0) {
+ meshlink_errno = MESHLINK_ENETWORK;
+ }
+
+ return retval;
+}
+
+bool meshlink_channel_aio_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
+ if(!mesh || !channel) {
+ meshlink_errno = MESHLINK_EINVAL;