#include "system.h"
#include <pthread.h>
-#include "adns.h"
#include "crypto.h"
#include "ecdsagen.h"
#include "logger.h"
#include "net.h"
#include "netutl.h"
#include "node.h"
-#include "submesh.h"
#include "packmsg.h"
#include "prf.h"
#include "protocol.h"
#include "utils.h"
#include "xalloc.h"
#include "ed25519/sha512.h"
-#include "discovery.h"
#include "devtools.h"
-#include "graph.h"
#ifndef MSG_NOSIGNAL
#define MSG_NOSIGNAL 0
return len;
}
-static void get_canonical_address(node_t *n, char **hostname, char **port) {
- if(!n->canonical_address) {
- return;
- }
-
- *hostname = xstrdup(n->canonical_address);
- char *space = strchr(*hostname, ' ');
-
- if(space) {
- *space++ = 0;
- *port = xstrdup(space);
- }
-}
-
static bool is_valid_hostname(const char *hostname) {
if(!*hostname) {
return false;
}
-// Find out what local address a socket would use if we connect to the given address.
-// We do this using connect() on a UDP socket, so the kernel has to resolve the address
-// of both endpoints, but this will actually not send any UDP packet.
-static bool getlocaladdr(const char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
- struct addrinfo *rai = NULL;
- const struct addrinfo hint = {
- .ai_family = AF_UNSPEC,
- .ai_socktype = SOCK_DGRAM,
- .ai_protocol = IPPROTO_UDP,
- .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
- };
-
- if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
- return false;
+static bool write_main_config_files(meshlink_handle_t *mesh) {
+ if(!mesh->confbase) {
+ return true;
}
- int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
-
- if(sock == -1) {
- freeaddrinfo(rai);
- return false;
- }
+ uint8_t buf[4096];
- if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
- closesocket(sock);
- freeaddrinfo(rai);
- return false;
- }
+ /* Write the main config file */
+ packmsg_output_t out = {buf, sizeof buf};
- freeaddrinfo(rai);
+ packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
+ packmsg_add_str(&out, mesh->name);
+ packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
+ packmsg_add_nil(&out); // Invitation keys are not supported
+ packmsg_add_uint16(&out, atoi(mesh->myport));
- if(getsockname(sock, &sa->sa, salen)) {
- closesocket(sock);
+ if(!packmsg_output_ok(&out)) {
return false;
}
- closesocket(sock);
- return true;
-}
-
-static bool getlocaladdrname(const char *destaddr, char *host, socklen_t hostlen, int netns) {
- sockaddr_t sa;
- socklen_t salen = sizeof(sa);
+ config_t config = {buf, packmsg_output_size(&out, buf)};
- if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
+ if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
return false;
}
- if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
+ /* Write our own host config file */
+ if(!node_write_config(mesh, mesh->self, true)) {
return false;
}
return true;
}
-char *meshlink_get_external_address(meshlink_handle_t *mesh) {
- return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
-}
-
-char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_get_external_address_for_family(%d)", family);
- const char *url = mesh->external_address_url;
+typedef struct {
+ meshlink_handle_t *mesh;
+ int sock;
+ char cookie[18 + 32];
+ char hash[18];
+ bool success;
+ sptps_t sptps;
+ char *data;
+ size_t thedatalen;
+ size_t blen;
+ char line[4096];
+ char buffer[4096];
+} join_state_t;
- if(!url) {
- url = "http://meshlink.io/host.cgi";
- }
+static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
+ meshlink_handle_t *mesh = state->mesh;
+ packmsg_input_t in = {buf, len};
+ uint32_t version = packmsg_get_uint32(&in);
- /* Find the hostname part between the slashes */
- if(strncmp(url, "http://", 7)) {
- abort();
- meshlink_errno = MESHLINK_EINTERNAL;
- return NULL;
+ if(version != MESHLINK_INVITATION_VERSION) {
+ logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
+ return false;
}
- const char *begin = url + 7;
+ char *name = packmsg_get_str_dup(&in);
+ packmsg_skip_element(&in); // submesh_name
+ dev_class_t devclass = packmsg_get_int32(&in);
+ uint32_t count = packmsg_get_array(&in);
- const char *end = strchr(begin, '/');
+ if(!name || !check_id(name)) {
+ logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
+ free(name);
+ return false;
+ }
- if(!end) {
- end = begin + strlen(begin);
+ if(!count) {
+ logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
+ free(name);
+ return false;
}
- /* Make a copy */
- char host[end - begin + 1];
- strncpy(host, begin, end - begin);
- host[end - begin] = 0;
+ free(mesh->name);
+ free(mesh->self->name);
+ mesh->name = name;
+ mesh->self->name = xstrdup(name);
+ mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
- char *port = strchr(host, ':');
+ // Initialize configuration directory
+ if(!config_init(mesh, "current")) {
+ return false;
+ }
- if(port) {
- *port++ = 0;
+ if(!write_main_config_files(mesh)) {
+ return false;
}
- logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
- struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(host), xstrdup(port ? port : "80"), SOCK_STREAM, 5);
- char line[256];
- char *hostname = NULL;
+ // Write host config files
+ for(uint32_t i = 0; i < count; i++) {
+ const void *data;
+ uint32_t data_len = packmsg_get_bin_raw(&in, &data);
- for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
- if(family != AF_UNSPEC && aip->ai_family != family) {
- continue;
+ if(!data_len) {
+ logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
+ return false;
}
- int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
+ packmsg_input_t in2 = {data, data_len};
+ uint32_t version2 = packmsg_get_uint32(&in2);
+ char *name2 = packmsg_get_str_dup(&in2);
-#ifdef SO_NOSIGPIPE
- int nosigpipe = 1;
- setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
-#endif
+ if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
+ free(name2);
+ packmsg_input_invalidate(&in);
+ break;
+ }
- if(s >= 0) {
- set_timeout(s, 5000);
+ if(!check_id(name2)) {
+ free(name2);
+ break;
+ }
- if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
- closesocket(s);
- s = -1;
- }
+ if(!strcmp(name2, mesh->name)) {
+ logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
+ free(name2);
+ meshlink_errno = MESHLINK_EPEER;
+ return false;
}
- if(s >= 0) {
- send(s, "GET ", 4, 0);
- send(s, url, strlen(url), 0);
- send(s, " HTTP/1.0\r\n\r\n", 13, 0);
- int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
+ node_t *n = new_node();
+ n->name = name2;
- if(len > 0) {
- line[len] = 0;
+ config_t config = {data, data_len};
- if(line[len - 1] == '\n') {
- line[--len] = 0;
- }
+ if(!node_read_from_config(mesh, n, &config)) {
+ free_node(n);
+ logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
+ meshlink_errno = MESHLINK_EPEER;
+ return false;
+ }
- char *p = strrchr(line, '\n');
+ if(i == 0) {
+ /* The first host config file is of the inviter itself;
+ * remember the address we are currently using for the invitation connection.
+ */
+ sockaddr_t sa;
+ socklen_t salen = sizeof(sa);
- if(p && p[1]) {
- hostname = xstrdup(p + 1);
- }
+ if(getpeername(state->sock, &sa.sa, &salen) == 0) {
+ node_add_recent_address(mesh, n, &sa);
}
+ }
- closesocket(s);
-
- if(hostname) {
- break;
- }
+ if(!node_write_config(mesh, n, true)) {
+ free_node(n);
+ return false;
}
- }
- if(ai) {
- freeaddrinfo(ai);
+ node_add(mesh, n);
}
- // Check that the hostname is reasonable
- if(hostname && !is_valid_hostname(hostname)) {
- free(hostname);
- hostname = NULL;
+ /* Ensure the configuration directory metadata is on disk */
+ if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
+ return false;
}
- if(!hostname) {
- meshlink_errno = MESHLINK_ERESOLV;
+ if(!mesh->inviter_commits_first) {
+ devtool_set_inviter_commits_first(false);
}
- return hostname;
-}
-
-static bool is_localaddr(sockaddr_t *sa) {
- switch(sa->sa.sa_family) {
- case AF_INET:
- return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
+ sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
- case AF_INET6: {
- uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
- return first == 0 || (first & 0xffc0) == 0xfe80;
- }
+ logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
- default:
- return false;
- }
+ return true;
}
-#ifdef HAVE_GETIFADDRS
-struct getifaddrs_in_netns_params {
- struct ifaddrs **ifa;
- int netns;
-};
+static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
+ (void)type;
+ join_state_t *state = handle;
+ const char *ptr = data;
-#ifdef HAVE_SETNS
-static void *getifaddrs_in_netns_thread(void *arg) {
- struct getifaddrs_in_netns_params *params = arg;
+ while(len) {
+ int result = send(state->sock, ptr, len, 0);
- if(setns(params->netns, CLONE_NEWNET) == -1) {
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
+ if(result == -1 && errno == EINTR) {
+ continue;
+ } else if(result <= 0) {
+ return false;
+ }
- if(getifaddrs(params->ifa) != 0) {
- *params->ifa = NULL;
+ ptr += result;
+ len -= result;
}
- return NULL;
+ return true;
}
-#endif // HAVE_SETNS
-static int getifaddrs_in_netns(struct ifaddrs **ifa, int netns) {
- if(netns == -1) {
- return getifaddrs(ifa);
- }
+static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
+ join_state_t *state = handle;
+ meshlink_handle_t *mesh = state->mesh;
-#ifdef HAVE_SETNS
- struct getifaddrs_in_netns_params params = {ifa, netns};
- pthread_t thr;
+ if(mesh->inviter_commits_first) {
+ switch(type) {
+ case SPTPS_HANDSHAKE:
+ return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
- if(pthread_create(&thr, NULL, getifaddrs_in_netns_thread, ¶ms) == 0) {
- if(pthread_join(thr, NULL) != 0) {
- abort();
- }
- }
+ case 1:
+ break;
- return *params.ifa ? 0 : -1;
-#else
- return -1;
-#endif // HAVE_SETNS
+ case 0:
+ if(!finalize_join(state, msg, len)) {
+ return false;
+ }
-}
-#endif
+ logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
+ shutdown(state->sock, SHUT_RDWR);
+ state->success = true;
+ break;
-char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_get_local_address_for_family(%d)", family);
+ default:
+ return false;
+ }
+ } else {
+ switch(type) {
+ case SPTPS_HANDSHAKE:
+ return sptps_send_record(&state->sptps, 0, state->cookie, 18);
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
+ case 0:
+ return finalize_join(state, msg, len);
- // Determine address of the local interface used for outgoing connections.
- char localaddr[NI_MAXHOST];
- bool success = false;
+ case 1:
+ logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
+ shutdown(state->sock, SHUT_RDWR);
+ state->success = true;
+ break;
- if(family == AF_INET) {
- success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
- } else if(family == AF_INET6) {
- success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
+ default:
+ return false;
+ }
}
-#ifdef HAVE_GETIFADDRS
-
- if(!success) {
- struct ifaddrs *ifa = NULL;
- getifaddrs_in_netns(&ifa, mesh->netns);
-
- for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
- sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
+ return true;
+}
- if(!sa || sa->sa.sa_family != family) {
- continue;
- }
+static bool recvline(join_state_t *state) {
+ char *newline = NULL;
- if(is_localaddr(sa)) {
- continue;
- }
+ while(!(newline = memchr(state->buffer, '\n', state->blen))) {
+ int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
- if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
- success = true;
- break;
- }
+ if(result == -1 && errno == EINTR) {
+ continue;
+ } else if(result <= 0) {
+ return false;
}
- freeifaddrs(ifa);
+ state->blen += result;
}
-#endif
-
- if(!success) {
- meshlink_errno = MESHLINK_ENETWORK;
- return NULL;
+ if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
+ return false;
}
- return xstrdup(localaddr);
-}
+ size_t len = newline - state->buffer;
-static void remove_duplicate_hostnames(char *host[], char *port[], int n) {
- for(int i = 0; i < n; i++) {
- if(!host[i]) {
- continue;
- }
-
- // Ignore duplicate hostnames
- bool found = false;
-
- for(int j = 0; j < i; j++) {
- if(!host[j]) {
- continue;
- }
-
- if(strcmp(host[i], host[j])) {
- continue;
- }
-
- if(strcmp(port[i], port[j])) {
- continue;
- }
-
- found = true;
- break;
- }
+ memcpy(state->line, state->buffer, len);
+ state->line[len] = 0;
+ memmove(state->buffer, newline + 1, state->blen - len - 1);
+ state->blen -= len + 1;
- if(found || !is_valid_hostname(host[i])) {
- free(host[i]);
- free(port[i]);
- host[i] = NULL;
- port[i] = NULL;
- continue;
- }
- }
+ return true;
}
-// This gets the hostname part for use in invitation URLs
-static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
- int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
- int n = 0;
- char *hostname[count];
- char *port[count];
- char *hostport = NULL;
-
- memset(hostname, 0, sizeof(hostname));
- memset(port, 0, sizeof(port));
-
- if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
- flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
- }
-
- if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
- flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
- }
-
- // Add all explicitly set invitation addresses
- if(mesh->invitation_addresses) {
- for list_each(char, combo, mesh->invitation_addresses) {
- hostname[n] = xstrdup(combo);
- char *slash = strrchr(hostname[n], '/');
-
- if(slash) {
- *slash = 0;
- port[n] = xstrdup(slash + 1);
- }
-
- n++;
- }
- }
-
- // Add local addresses if requested
- if(flags & MESHLINK_INVITE_LOCAL) {
- if(flags & MESHLINK_INVITE_IPV4) {
- hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
- }
-
- if(flags & MESHLINK_INVITE_IPV6) {
- hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
- }
- }
-
- // Add public/canonical addresses if requested
- if(flags & MESHLINK_INVITE_PUBLIC) {
- // Try the CanonicalAddress first
- get_canonical_address(mesh->self, &hostname[n], &port[n]);
-
- if(!hostname[n] && count == 4) {
- if(flags & MESHLINK_INVITE_IPV4) {
- hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
- }
+static bool sendline(int fd, const char *format, ...) {
+ char buffer[4096];
+ char *p = buffer;
+ int blen = 0;
+ va_list ap;
- if(flags & MESHLINK_INVITE_IPV6) {
- hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
- }
- } else {
- n++;
- }
- }
+ va_start(ap, format);
+ blen = vsnprintf(buffer, sizeof(buffer), format, ap);
+ va_end(ap);
- for(int i = 0; i < n; i++) {
- // Ensure we always have a port number
- if(hostname[i] && !port[i]) {
- port[i] = xstrdup(mesh->myport);
- }
+ if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
+ return false;
}
- remove_duplicate_hostnames(hostname, port, n);
-
- // Resolve the hostnames
- for(int i = 0; i < n; i++) {
- if(!hostname[i]) {
- continue;
- }
+ buffer[blen] = '\n';
+ blen++;
- // Convert what we have to a sockaddr
- struct addrinfo *ai_in = adns_blocking_request(mesh, xstrdup(hostname[i]), xstrdup(port[i]), SOCK_STREAM, 5);
+ while(blen) {
+ int result = send(fd, p, blen, MSG_NOSIGNAL);
- if(!ai_in) {
+ if(result == -1 && errno == EINTR) {
continue;
+ } else if(result <= 0) {
+ return false;
}
- // Remember the address(es)
- for(struct addrinfo *aip = ai_in; aip; aip = aip->ai_next) {
- node_add_recent_address(mesh, mesh->self, (sockaddr_t *)aip->ai_addr);
- }
-
- freeaddrinfo(ai_in);
- continue;
+ p += result;
+ blen -= result;
}
- // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
- remove_duplicate_hostnames(hostname, port, n);
-
- // Concatenate all unique address to the hostport string
- for(int i = 0; i < n; i++) {
- if(!hostname[i]) {
- continue;
- }
+ return true;
+}
- // Append the address to the hostport string
- char *newhostport;
- xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
- free(hostport);
- hostport = newhostport;
+static const char *errstr[] = {
+ [MESHLINK_OK] = "No error",
+ [MESHLINK_EINVAL] = "Invalid argument",
+ [MESHLINK_ENOMEM] = "Out of memory",
+ [MESHLINK_ENOENT] = "No such node",
+ [MESHLINK_EEXIST] = "Node already exists",
+ [MESHLINK_EINTERNAL] = "Internal error",
+ [MESHLINK_ERESOLV] = "Could not resolve hostname",
+ [MESHLINK_ESTORAGE] = "Storage error",
+ [MESHLINK_ENETWORK] = "Network error",
+ [MESHLINK_EPEER] = "Error communicating with peer",
+ [MESHLINK_ENOTSUP] = "Operation not supported",
+ [MESHLINK_EBUSY] = "MeshLink instance already in use",
+ [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
+};
- free(hostname[i]);
- free(port[i]);
+const char *meshlink_strerror(meshlink_errno_t err) {
+ if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
+ return "Invalid error code";
}
- return hostport;
+ return errstr[err];
}
-static bool try_bind(meshlink_handle_t *mesh, int port) {
- struct addrinfo *ai = NULL;
- struct addrinfo hint = {
- .ai_flags = AI_PASSIVE,
- .ai_family = AF_UNSPEC,
- .ai_socktype = SOCK_STREAM,
- .ai_protocol = IPPROTO_TCP,
- };
+static bool ecdsa_keygen(meshlink_handle_t *mesh) {
+ logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
- char portstr[16];
- snprintf(portstr, sizeof(portstr), "%d", port);
+ mesh->private_key = ecdsa_generate();
- if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
+ if(!mesh->private_key) {
+ logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
+ meshlink_errno = MESHLINK_EINTERNAL;
return false;
}
- bool success = false;
-
- for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
- /* Try to bind to TCP. */
-
- int tcp_fd = setup_tcp_listen_socket(mesh, aip);
-
- if(tcp_fd == -1) {
- if(errno == EADDRINUSE) {
- /* If this port is in use for any address family, avoid it. */
- success = false;
- break;
- } else {
- continue;
- }
- }
-
- /* If TCP worked, then we require that UDP works as well. */
-
- int udp_fd = setup_udp_listen_socket(mesh, aip);
-
- if(udp_fd == -1) {
- closesocket(tcp_fd);
- success = false;
- break;
- }
-
- closesocket(tcp_fd);
- closesocket(udp_fd);
- success = true;
- }
+ logger(mesh, MESHLINK_DEBUG, "Done.\n");
- freeaddrinfo(ai);
- return success;
+ return true;
}
-int check_port(meshlink_handle_t *mesh) {
- for(int i = 0; i < 1000; i++) {
- int port = 0x1000 + prng(mesh, 0x8000);
+static struct timespec idle(event_loop_t *loop, void *data) {
+ (void)loop;
+ meshlink_handle_t *mesh = data;
- if(try_bind(mesh, port)) {
- free(mesh->myport);
- xasprintf(&mesh->myport, "%d", port);
- return port;
- }
+ if(mesh->peer && mesh->peer->utcp) {
+ return utcp_timeout(mesh->peer->utcp);
+ } else {
+ return (struct timespec) {
+ 3600, 0
+ };
}
-
- meshlink_errno = MESHLINK_ENETWORK;
- logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
- return 0;
}
-static bool write_main_config_files(meshlink_handle_t *mesh) {
- if(!mesh->confbase) {
- return true;
+static bool meshlink_setup(meshlink_handle_t *mesh) {
+ if(!config_destroy(mesh->confbase, "new")) {
+ logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return false;
}
- uint8_t buf[4096];
-
- /* Write the main config file */
- packmsg_output_t out = {buf, sizeof buf};
+ if(!config_destroy(mesh->confbase, "old")) {
+ logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return false;
+ }
- packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
- packmsg_add_str(&out, mesh->name);
- packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
- packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
- packmsg_add_uint16(&out, atoi(mesh->myport));
+ if(!config_init(mesh, "current")) {
+ logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return false;
+ }
- if(!packmsg_output_ok(&out)) {
+ if(!ecdsa_keygen(mesh)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
return false;
}
- config_t config = {buf, packmsg_output_size(&out, buf)};
+ mesh->myport = xstrdup("0");
- if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
+ /* Create a node for ourself */
+
+ mesh->self = new_node();
+ mesh->self->name = xstrdup(mesh->name);
+ mesh->self->devclass = mesh->devclass;
+ mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
+ mesh->self->session_id = mesh->session_id;
+
+ if(!write_main_config_files(mesh)) {
+ logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
return false;
}
- /* Write our own host config file */
- if(!node_write_config(mesh, mesh->self, true)) {
+ /* Ensure the configuration directory metadata is on disk */
+ if(!config_sync(mesh, "current")) {
return false;
}
return true;
}
-typedef struct {
- meshlink_handle_t *mesh;
- int sock;
- char cookie[18 + 32];
- char hash[18];
- bool success;
- sptps_t sptps;
- char *data;
- size_t thedatalen;
- size_t blen;
- char line[4096];
- char buffer[4096];
-} join_state_t;
-
-static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
- meshlink_handle_t *mesh = state->mesh;
- packmsg_input_t in = {buf, len};
- uint32_t version = packmsg_get_uint32(&in);
+static bool meshlink_read_config(meshlink_handle_t *mesh) {
+ config_t config;
- if(version != MESHLINK_INVITATION_VERSION) {
- logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
+ if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
+ logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
return false;
}
- char *name = packmsg_get_str_dup(&in);
- char *submesh_name = packmsg_get_str_dup(&in);
- dev_class_t devclass = packmsg_get_int32(&in);
- uint32_t count = packmsg_get_array(&in);
+ packmsg_input_t in = {config.buf, config.len};
+ const void *private_key;
- if(!name || !check_id(name)) {
- logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
- free(name);
- free(submesh_name);
- return false;
- }
+ uint32_t version = packmsg_get_uint32(&in);
+ char *name = packmsg_get_str_dup(&in);
+ uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
+ packmsg_skip_element(&in); // Invitation key is not supported
+ uint16_t myport = packmsg_get_uint16(&in);
- if(!submesh_name || (strcmp(submesh_name, CORE_MESH) && !check_id(submesh_name))) {
- logger(mesh, MESHLINK_DEBUG, "No valid Submesh found in invitation!\n");
+ if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
+ logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
free(name);
- free(submesh_name);
+ config_free(&config);
return false;
}
- if(!count) {
- logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
+ if(mesh->name && strcmp(mesh->name, name)) {
+ logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
+ meshlink_errno = MESHLINK_ESTORAGE;
free(name);
- free(submesh_name);
+ config_free(&config);
return false;
}
free(mesh->name);
- free(mesh->self->name);
mesh->name = name;
+ xasprintf(&mesh->myport, "%u", myport);
+ mesh->private_key = ecdsa_set_private_key(private_key);
+ config_free(&config);
+
+ /* Create a node for ourself and read our host configuration file */
+
+ mesh->self = new_node();
mesh->self->name = xstrdup(name);
- mesh->self->submesh = strcmp(submesh_name, CORE_MESH) ? lookup_or_create_submesh(mesh, submesh_name) : NULL;
- free(submesh_name);
- mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
+ mesh->self->devclass = mesh->devclass;
+ mesh->self->session_id = mesh->session_id;
- // Initialize configuration directory
- if(!config_init(mesh, "current")) {
+ 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;
return false;
}
- if(!write_main_config_files(mesh)) {
- return false;
- }
+ return true;
+}
- // Write host config files
- for(uint32_t i = 0; i < count; i++) {
- const void *data;
- uint32_t data_len = packmsg_get_bin_raw(&in, &data);
+#ifdef HAVE_SETNS
+static void *setup_network_in_netns_thread(void *arg) {
+ meshlink_handle_t *mesh = arg;
- if(!data_len) {
- logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
- return false;
- }
+ if(setns(mesh->netns, CLONE_NEWNET) != 0) {
+ return NULL;
+ }
- packmsg_input_t in2 = {data, data_len};
- uint32_t version2 = packmsg_get_uint32(&in2);
- char *name2 = packmsg_get_str_dup(&in2);
-
- if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
- free(name2);
- packmsg_input_invalidate(&in);
- break;
- }
-
- if(!check_id(name2)) {
- free(name2);
- break;
- }
-
- if(!strcmp(name2, mesh->name)) {
- logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
- free(name2);
- meshlink_errno = MESHLINK_EPEER;
- return false;
- }
-
- node_t *n = new_node();
- n->name = name2;
-
- config_t config = {data, data_len};
-
- if(!node_read_from_config(mesh, n, &config)) {
- free_node(n);
- logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
- meshlink_errno = MESHLINK_EPEER;
- return false;
- }
-
- if(i == 0) {
- /* The first host config file is of the inviter itself;
- * remember the address we are currently using for the invitation connection.
- */
- sockaddr_t sa;
- socklen_t salen = sizeof(sa);
-
- if(getpeername(state->sock, &sa.sa, &salen) == 0) {
- node_add_recent_address(mesh, n, &sa);
- }
- }
-
- /* 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, true)) {
- free_node(n);
- return false;
- }
-
- node_add(mesh, n);
- }
-
- /* Ensure the configuration directory metadata is on disk */
- if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
- return false;
- }
-
- if(!mesh->inviter_commits_first) {
- devtool_set_inviter_commits_first(false);
- }
-
- sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
-
- logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
-
- return true;
-}
-
-static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
- (void)type;
- join_state_t *state = handle;
- const char *ptr = data;
-
- while(len) {
- int result = send(state->sock, ptr, len, 0);
-
- if(result == -1 && errno == EINTR) {
- continue;
- } else if(result <= 0) {
- return false;
- }
-
- ptr += result;
- len -= result;
- }
-
- return true;
-}
-
-static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
- join_state_t *state = handle;
- meshlink_handle_t *mesh = state->mesh;
-
- if(mesh->inviter_commits_first) {
- switch(type) {
- case SPTPS_HANDSHAKE:
- return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
-
- case 1:
- break;
-
- case 0:
- if(!finalize_join(state, msg, len)) {
- return false;
- }
-
- logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
- shutdown(state->sock, SHUT_RDWR);
- state->success = true;
- break;
-
- default:
- return false;
- }
- } else {
- switch(type) {
- case SPTPS_HANDSHAKE:
- return sptps_send_record(&state->sptps, 0, state->cookie, 18);
-
- case 0:
- return finalize_join(state, msg, len);
-
- case 1:
- logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
- shutdown(state->sock, SHUT_RDWR);
- state->success = true;
- break;
-
- default:
- return false;
- }
- }
-
- return true;
-}
-
-static bool recvline(join_state_t *state) {
- char *newline = NULL;
-
- while(!(newline = memchr(state->buffer, '\n', state->blen))) {
- int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
-
- if(result == -1 && errno == EINTR) {
- continue;
- } else if(result <= 0) {
- return false;
- }
-
- state->blen += result;
- }
-
- if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
- return false;
- }
-
- size_t len = newline - state->buffer;
-
- memcpy(state->line, state->buffer, len);
- state->line[len] = 0;
- memmove(state->buffer, newline + 1, state->blen - len - 1);
- state->blen -= len + 1;
-
- return true;
-}
-
-static bool sendline(int fd, const char *format, ...) {
- char buffer[4096];
- char *p = buffer;
- int blen = 0;
- va_list ap;
-
- va_start(ap, format);
- blen = vsnprintf(buffer, sizeof(buffer), format, ap);
- va_end(ap);
-
- if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
- return false;
- }
-
- buffer[blen] = '\n';
- blen++;
-
- while(blen) {
- int result = send(fd, p, blen, MSG_NOSIGNAL);
-
- if(result == -1 && errno == EINTR) {
- continue;
- } else if(result <= 0) {
- return false;
- }
-
- p += result;
- blen -= result;
- }
-
- return true;
-}
-
-static const char *errstr[] = {
- [MESHLINK_OK] = "No error",
- [MESHLINK_EINVAL] = "Invalid argument",
- [MESHLINK_ENOMEM] = "Out of memory",
- [MESHLINK_ENOENT] = "No such node",
- [MESHLINK_EEXIST] = "Node already exists",
- [MESHLINK_EINTERNAL] = "Internal error",
- [MESHLINK_ERESOLV] = "Could not resolve hostname",
- [MESHLINK_ESTORAGE] = "Storage error",
- [MESHLINK_ENETWORK] = "Network error",
- [MESHLINK_EPEER] = "Error communicating with peer",
- [MESHLINK_ENOTSUP] = "Operation not supported",
- [MESHLINK_EBUSY] = "MeshLink instance already in use",
- [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
-};
-
-const char *meshlink_strerror(meshlink_errno_t err) {
- if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
- return "Invalid error code";
- }
-
- return errstr[err];
-}
-
-static bool ecdsa_keygen(meshlink_handle_t *mesh) {
- logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
-
- mesh->private_key = ecdsa_generate();
- mesh->invitation_key = ecdsa_generate();
-
- if(!mesh->private_key || !mesh->invitation_key) {
- logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
- meshlink_errno = MESHLINK_EINTERNAL;
- return false;
- }
-
- logger(mesh, MESHLINK_DEBUG, "Done.\n");
-
- return true;
-}
-
-static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
- if(a->tv_sec == b->tv_sec) {
- return a->tv_nsec < b->tv_nsec;
- } else {
- return a->tv_sec < b->tv_sec;
- }
-}
-
-static struct timespec idle(event_loop_t *loop, void *data) {
- (void)loop;
- meshlink_handle_t *mesh = data;
- struct timespec t, tmin = {3600, 0};
-
- for splay_each(node_t, n, mesh->nodes) {
- if(!n->utcp) {
- continue;
- }
-
- t = utcp_timeout(n->utcp);
-
- if(timespec_lt(&t, &tmin)) {
- tmin = t;
- }
- }
-
- return tmin;
-}
-
-// Get our local address(es) by simulating connecting to an Internet host.
-static void add_local_addresses(meshlink_handle_t *mesh) {
- sockaddr_t sa;
- sa.storage.ss_family = AF_UNKNOWN;
- socklen_t salen = sizeof(sa);
-
- // IPv4 example.org
-
- if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
- sa.in.sin_port = ntohs(atoi(mesh->myport));
- node_add_recent_address(mesh, mesh->self, &sa);
- }
-
- // IPv6 example.org
-
- salen = sizeof(sa);
-
- if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
- sa.in6.sin6_port = ntohs(atoi(mesh->myport));
- node_add_recent_address(mesh, mesh->self, &sa);
- }
-}
-
-static bool meshlink_setup(meshlink_handle_t *mesh) {
- if(!config_destroy(mesh->confbase, "new")) {
- logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
-
- if(!config_destroy(mesh->confbase, "old")) {
- logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
-
- if(!config_init(mesh, "current")) {
- logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
-
- if(!ecdsa_keygen(mesh)) {
- meshlink_errno = MESHLINK_EINTERNAL;
- return false;
- }
-
- if(check_port(mesh) == 0) {
- meshlink_errno = MESHLINK_ENETWORK;
- return false;
- }
-
- /* Create a node for ourself */
-
- mesh->self = new_node();
- mesh->self->name = xstrdup(mesh->name);
- mesh->self->devclass = mesh->devclass;
- mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
- mesh->self->session_id = mesh->session_id;
-
- if(!write_main_config_files(mesh)) {
- logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
-
- /* Ensure the configuration directory metadata is on disk */
- if(!config_sync(mesh, "current")) {
- return false;
- }
-
- return true;
-}
-
-static bool meshlink_read_config(meshlink_handle_t *mesh) {
- config_t config;
-
- if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
- logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
- return false;
- }
-
- packmsg_input_t in = {config.buf, config.len};
- const void *private_key;
- const void *invitation_key;
-
- uint32_t version = packmsg_get_uint32(&in);
- char *name = packmsg_get_str_dup(&in);
- uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
- uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
- uint16_t myport = packmsg_get_uint16(&in);
-
- if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
- logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
- free(name);
- config_free(&config);
- return false;
- }
-
- if(mesh->name && strcmp(mesh->name, name)) {
- logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
- meshlink_errno = MESHLINK_ESTORAGE;
- free(name);
- config_free(&config);
- return false;
- }
-
- free(mesh->name);
- mesh->name = name;
- xasprintf(&mesh->myport, "%u", myport);
- mesh->private_key = ecdsa_set_private_key(private_key);
- mesh->invitation_key = ecdsa_set_private_key(invitation_key);
- config_free(&config);
-
- /* Create a node for ourself and read our host configuration file */
-
- mesh->self = new_node();
- mesh->self->name = xstrdup(name);
- mesh->self->devclass = mesh->devclass;
- mesh->self->session_id = mesh->session_id;
-
- 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;
- return false;
- }
-
- return true;
-}
-
-#ifdef HAVE_SETNS
-static void *setup_network_in_netns_thread(void *arg) {
- meshlink_handle_t *mesh = arg;
-
- if(setns(mesh->netns, CLONE_NEWNET) != 0) {
- return NULL;
- }
-
- bool success = setup_network(mesh);
- return success ? arg : NULL;
-}
-#endif // HAVE_SETNS
-
-meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
-
- if(!confbase || !*confbase) {
- logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(!appname || !*appname) {
- logger(NULL, MESHLINK_ERROR, "No appname given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(strchr(appname, ' ')) {
- logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(name && !check_id(name)) {
- logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
- logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- meshlink_open_params_t *params = xzalloc(sizeof * params);
-
- params->confbase = xstrdup(confbase);
- params->name = name ? xstrdup(name) : NULL;
- params->appname = xstrdup(appname);
- params->devclass = devclass;
- params->netns = -1;
-
- xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
-
- return params;
-}
-
-bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
-
- if(!params) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- params->netns = netns;
-
- return true;
-}
-
-bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
-
- if(!params) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if((!key && keylen) || (key && !keylen)) {
- logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- params->key = key;
- params->keylen = keylen;
-
- return true;
-}
-
-bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
-
- if(!params) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- params->storage_policy = policy;
-
- return true;
-}
-
-bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
-
- if(!params || !filename) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- free(params->lock_filename);
- params->lock_filename = xstrdup(filename);
-
- return true;
-}
-
-bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
-
- if(!mesh || !new_key || !new_keylen) {
- logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- // Create hash for the new key
- void *new_config_key;
- new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
-
- if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
- logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
- meshlink_errno = MESHLINK_EINTERNAL;
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
-
- if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
- logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- devtool_keyrotate_probe(1);
-
- // Rename confbase/current/ to confbase/old
-
- if(!config_rename(mesh, "current", "old")) {
- logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
- meshlink_errno = MESHLINK_ESTORAGE;
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- devtool_keyrotate_probe(2);
-
- // Rename confbase/new/ to confbase/current
-
- if(!config_rename(mesh, "new", "current")) {
- logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
- meshlink_errno = MESHLINK_ESTORAGE;
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- devtool_keyrotate_probe(3);
-
- // Cleanup the "old" confbase sub-directory
-
- if(!config_destroy(mesh->confbase, "old")) {
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- // Change the mesh handle key with new key
-
- free(mesh->config_key);
- mesh->config_key = new_config_key;
-
- pthread_mutex_unlock(&mesh->mutex);
-
- return true;
-}
-
-void meshlink_open_params_free(meshlink_open_params_t *params) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
-
- if(!params) {
- meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- free(params->confbase);
- free(params->name);
- free(params->appname);
- free(params->lock_filename);
-
- free(params);
-}
-
-/// Device class traits
-static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
- { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
- { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
- { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
- { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
-};
-
-meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
-
- if(!confbase || !*confbase) {
- logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- char lock_filename[PATH_MAX];
- snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
-
- /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
- meshlink_open_params_t params = {
- .confbase = (char *)confbase,
- .lock_filename = lock_filename,
- .name = (char *)name,
- .appname = (char *)appname,
- .devclass = devclass,
- .netns = -1,
- };
-
- return meshlink_open_ex(¶ms);
-}
-
-meshlink_handle_t *meshlink_open_encrypted(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
-
- if(!confbase || !*confbase) {
- logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- char lock_filename[PATH_MAX];
- snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
-
- /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
- meshlink_open_params_t params = {
- .confbase = (char *)confbase,
- .lock_filename = lock_filename,
- .name = (char *)name,
- .appname = (char *)appname,
- .devclass = devclass,
- .netns = -1,
- };
-
- if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
- return false;
- }
-
- return meshlink_open_ex(¶ms);
-}
-
-meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
-
- if(!name) {
- logger(NULL, MESHLINK_ERROR, "No name given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(!check_id(name)) {
- logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(!appname || !*appname) {
- logger(NULL, MESHLINK_ERROR, "No appname given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(strchr(appname, ' ')) {
- logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
- logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
- meshlink_open_params_t params = {
- .name = (char *)name,
- .appname = (char *)appname,
- .devclass = devclass,
- .netns = -1,
- };
-
- return meshlink_open_ex(¶ms);
-}
-
-meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
-
- // Validate arguments provided by the application
- if(!params->appname || !*params->appname) {
- logger(NULL, MESHLINK_ERROR, "No appname given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(strchr(params->appname, ' ')) {
- logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(params->name && !check_id(params->name)) {
- logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
- logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if((params->key && !params->keylen) || (!params->key && params->keylen)) {
- logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
-
- if(params->confbase) {
- mesh->confbase = xstrdup(params->confbase);
- }
-
- mesh->appname = xstrdup(params->appname);
- mesh->devclass = params->devclass;
- mesh->discovery.enabled = true;
- mesh->invitation_timeout = 604800; // 1 week
- mesh->netns = params->netns;
- mesh->submeshes = NULL;
- mesh->log_cb = global_log_cb;
- mesh->log_level = global_log_level;
- mesh->packet = xmalloc(sizeof(vpn_packet_t));
-
- randomize(&mesh->prng_state, sizeof(mesh->prng_state));
-
- do {
- randomize(&mesh->session_id, sizeof(mesh->session_id));
- } while(mesh->session_id == 0);
-
- memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
-
- mesh->name = params->name ? xstrdup(params->name) : NULL;
-
- // Hash the key
- if(params->key) {
- mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
-
- if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
- logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
- meshlink_close(mesh);
- meshlink_errno = MESHLINK_EINTERNAL;
- return NULL;
- }
- }
-
- // initialize mutexes and conds
- pthread_mutexattr_t attr;
- pthread_mutexattr_init(&attr);
-
- if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
- abort();
- }
-
- pthread_mutex_init(&mesh->mutex, &attr);
- pthread_cond_init(&mesh->cond, NULL);
-
- pthread_cond_init(&mesh->adns_cond, NULL);
-
- mesh->threadstarted = false;
- event_loop_init(&mesh->loop);
- mesh->loop.data = mesh;
-
- meshlink_queue_init(&mesh->outpacketqueue);
-
- // Atomically lock the configuration directory.
- if(!main_config_lock(mesh, params->lock_filename)) {
- meshlink_close(mesh);
- return NULL;
- }
-
- // If no configuration exists yet, create it.
-
- bool new_configuration = false;
-
- if(!meshlink_confbase_exists(mesh)) {
- if(!mesh->name) {
- logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
- meshlink_close(mesh);
- meshlink_errno = MESHLINK_ESTORAGE;
- return NULL;
- }
-
- if(!meshlink_setup(mesh)) {
- logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
- meshlink_close(mesh);
- return NULL;
- }
-
- new_configuration = true;
- } else {
- if(!meshlink_read_config(mesh)) {
- logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
- meshlink_close(mesh);
- return NULL;
- }
- }
-
- mesh->storage_policy = params->storage_policy;
-
-#ifdef HAVE_MINGW
- struct WSAData wsa_state;
- WSAStartup(MAKEWORD(2, 2), &wsa_state);
-#endif
-
- // Setup up everything
- // TODO: we should not open listening sockets yet
-
- bool success = false;
-
- if(mesh->netns != -1) {
-#ifdef HAVE_SETNS
- pthread_t thr;
-
- if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
- void *retval = NULL;
- success = pthread_join(thr, &retval) == 0 && retval;
- }
-
-#else
- meshlink_errno = MESHLINK_EINTERNAL;
- return NULL;
-
-#endif // HAVE_SETNS
- } else {
- success = setup_network(mesh);
- }
-
- if(!success) {
- meshlink_close(mesh);
- meshlink_errno = MESHLINK_ENETWORK;
- return NULL;
- }
-
- add_local_addresses(mesh);
-
- if(!node_write_config(mesh, mesh->self, new_configuration)) {
- logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
- return NULL;
- }
-
- idle_set(&mesh->loop, idle, mesh);
-
- logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
- return mesh;
-}
-
-meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_submesh_open(%s)", submesh);
-
- meshlink_submesh_t *s = NULL;
-
- if(!mesh) {
- logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- if(!submesh || !*submesh) {
- logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
-
- //lock mesh->nodes
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
-
- pthread_mutex_unlock(&mesh->mutex);
-
- return s;
-}
-
-static void *meshlink_main_loop(void *arg) {
- meshlink_handle_t *mesh = arg;
-
- if(mesh->netns != -1) {
-#ifdef HAVE_SETNS
-
- if(setns(mesh->netns, CLONE_NEWNET) != 0) {
- pthread_cond_signal(&mesh->cond);
- return NULL;
- }
-
-#else
- pthread_cond_signal(&mesh->cond);
- return NULL;
-#endif // HAVE_SETNS
- }
-
- if(mesh->discovery.enabled) {
- discovery_start(mesh);
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
- pthread_cond_broadcast(&mesh->cond);
- main_loop(mesh);
- logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
-
- pthread_mutex_unlock(&mesh->mutex);
-
- // Stop discovery
- if(mesh->discovery.enabled) {
- discovery_stop(mesh);
- }
-
- return NULL;
-}
-
-bool meshlink_start(meshlink_handle_t *mesh) {
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- assert(mesh->self);
- assert(mesh->private_key);
- assert(mesh->self->ecdsa);
- assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
-
- if(mesh->threadstarted) {
- logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
- pthread_mutex_unlock(&mesh->mutex);
- return true;
- }
-
- if(mesh->listen_socket[0].tcp.fd < 0) {
- logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
- meshlink_errno = MESHLINK_ENETWORK;
- return false;
- }
-
- // Reset node connection timers
- for splay_each(node_t, n, mesh->nodes) {
- n->last_connect_try = 0;
- }
-
- // TODO: open listening sockets first
-
- //Check that a valid name is set
- if(!mesh->name) {
- logger(mesh, MESHLINK_ERROR, "No name given!\n");
- meshlink_errno = MESHLINK_EINVAL;
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- init_outgoings(mesh);
- init_adns(mesh);
-
- // Start the main thread
-
- event_loop_start(&mesh->loop);
-
- // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setstacksize(&attr, 1024 * 1024);
-
- if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
- logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
- memset(&mesh->thread, 0, sizeof(mesh)->thread);
- meshlink_errno = MESHLINK_EINTERNAL;
- event_loop_stop(&mesh->loop);
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- pthread_cond_wait(&mesh->cond, &mesh->mutex);
- mesh->threadstarted = true;
-
- // Ensure we are considered reachable
- graph(mesh);
-
- pthread_mutex_unlock(&mesh->mutex);
- return true;
-}
-
-void meshlink_stop(meshlink_handle_t *mesh) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
-
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- // Shut down the main thread
- event_loop_stop(&mesh->loop);
-
- // Send ourselves a UDP packet to kick the event loop
- for(int i = 0; i < mesh->listen_sockets; i++) {
- sockaddr_t sa;
- socklen_t salen = sizeof(sa);
-
- if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
- logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
- continue;
- }
-
- if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
- logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
- }
- }
-
- if(mesh->threadstarted) {
- // Wait for the main thread to finish
- pthread_mutex_unlock(&mesh->mutex);
-
- if(pthread_join(mesh->thread, NULL) != 0) {
- abort();
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- mesh->threadstarted = false;
- }
-
- // Close all metaconnections
- if(mesh->connections) {
- for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
- next = node->next;
- connection_t *c = node->data;
- c->outgoing = NULL;
- terminate_connection(mesh, c, false);
- }
- }
-
- exit_adns(mesh);
- exit_outgoings(mesh);
-
- // Ensure we are considered unreachable
- if(mesh->nodes) {
- graph(mesh);
- }
-
- // Try to write out any changed node config files, ignore errors at this point.
- if(mesh->nodes) {
- for splay_each(node_t, n, mesh->nodes) {
- if(n->status.dirty) {
- if(!node_write_config(mesh, n, false)) {
- // ignore
- }
- }
- }
- }
-
- pthread_mutex_unlock(&mesh->mutex);
+ bool success = setup_network(mesh);
+ return success ? arg : NULL;
}
+#endif // HAVE_SETNS
-void meshlink_close(meshlink_handle_t *mesh) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
+meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
- if(!mesh) {
+ if(!confbase || !*confbase) {
+ logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- // stop can be called even if mesh has not been started
- meshlink_stop(mesh);
-
- // lock is not released after this
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ return NULL;
}
- // Close and free all resources used.
-
- close_network_connections(mesh);
-
- logger(mesh, MESHLINK_INFO, "Terminating");
-
- event_loop_exit(&mesh->loop);
-
-#ifdef HAVE_MINGW
-
- if(mesh->confbase) {
- WSACleanup();
+ if(!appname || !*appname) {
+ logger(NULL, MESHLINK_ERROR, "No appname given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
-#endif
-
- ecdsa_free(mesh->invitation_key);
-
- if(mesh->netns != -1) {
- close(mesh->netns);
+ if(strchr(appname, ' ')) {
+ logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
- free(packet);
+ if(name && !check_id(name)) {
+ logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- meshlink_queue_exit(&mesh->outpacketqueue);
-
- free(mesh->name);
- free(mesh->appname);
- free(mesh->confbase);
- free(mesh->config_key);
- free(mesh->external_address_url);
- free(mesh->packet);
- ecdsa_free(mesh->private_key);
-
- if(mesh->invitation_addresses) {
- list_delete_list(mesh->invitation_addresses);
+ if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
+ logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- main_config_unlock(mesh);
+ meshlink_open_params_t *params = xzalloc(sizeof * params);
- pthread_mutex_unlock(&mesh->mutex);
- pthread_mutex_destroy(&mesh->mutex);
+ params->confbase = xstrdup(confbase);
+ params->name = name ? xstrdup(name) : NULL;
+ params->appname = xstrdup(appname);
+ params->devclass = devclass;
+ params->netns = -1;
- memset(mesh, 0, sizeof(*mesh));
+ xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
- free(mesh);
+ return params;
}
-bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
+bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
if(!params) {
meshlink_errno = MESHLINK_EINVAL;
return false;
}
- if(!params->confbase) {
- /* Ephemeral instances */
- return true;
- }
-
- /* Exit early if the confbase directory itself doesn't exist */
- if(access(params->confbase, F_OK) && errno == ENOENT) {
- return true;
- }
-
- /* Take the lock the same way meshlink_open() would. */
- FILE *lockfile = fopen(params->lock_filename, "w+");
-
- if(!lockfile) {
- logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
-
-#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", params->lock_filename);
- fclose(lockfile);
- meshlink_errno = MESHLINK_EBUSY;
- return false;
- }
-
-#endif
-
- if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
- logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
- return false;
- }
-
- if(unlink(params->lock_filename)) {
- logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
- fclose(lockfile);
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
-
- fclose(lockfile);
-
- if(!sync_path(params->confbase)) {
- logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
- meshlink_errno = MESHLINK_ESTORAGE;
- return false;
- }
+ params->netns = netns;
return true;
}
-bool meshlink_destroy(const char *confbase) {
- logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
-
- char lock_filename[PATH_MAX];
- snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
-
- meshlink_open_params_t params = {
- .confbase = (char *)confbase,
- .lock_filename = lock_filename,
- };
-
- return meshlink_destroy_ex(¶ms);
-}
-
-void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
-
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
-
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
+bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
- if(!mesh) {
+ if(!params) {
meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ return false;
}
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
-
- if(!mesh) {
+ if((!key && keylen) || (key && !keylen)) {
+ logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
meshlink_errno = MESHLINK_EINVAL;
- return;
+ return false;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
+ params->key = key;
+ params->keylen = keylen;
- mesh->node_pmtu_cb = cb;
- pthread_mutex_unlock(&mesh->mutex);
+ return true;
}
-void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
+bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
- if(!mesh) {
+ if(!params) {
meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ return false;
}
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
-
- if(mesh) {
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
+ params->storage_policy = policy;
- 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;
- }
+ return true;
}
-void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
+bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
- if(!mesh) {
+ if(!params || !filename) {
meshlink_errno = MESHLINK_EINVAL;
- return;
+ return false;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
+ free(params->lock_filename);
+ params->lock_filename = xstrdup(filename);
- mesh->error_cb = cb;
- pthread_mutex_unlock(&mesh->mutex);
+ return true;
}
-void meshlink_set_blacklisted_cb(struct meshlink_handle *mesh, meshlink_blacklisted_cb_t cb) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_blacklisted_cb(%p)", (void *)(intptr_t)cb);
+bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
- if(!mesh) {
+ if(!mesh || !new_key || !new_keylen) {
+ logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
meshlink_errno = MESHLINK_EINVAL;
- return;
+ return false;
}
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- mesh->blacklisted_cb = cb;
- pthread_mutex_unlock(&mesh->mutex);
-}
+ // Create hash for the new key
+ void *new_config_key;
+ new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
-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(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
+ logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
- if(len > MAXSIZE - sizeof(*hdr)) {
- meshlink_errno = MESHLINK_EINVAL;
+ // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
+
+ if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
+ logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&mesh->mutex);
return false;
}
- node_t *n = (node_t *)destination;
+ devtool_keyrotate_probe(1);
- if(n->status.blacklisted) {
- logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
- meshlink_errno = MESHLINK_EBLACKLISTED;
+ // Rename confbase/current/ to confbase/old
+
+ if(!config_rename(mesh, "current", "old")) {
+ logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&mesh->mutex);
return false;
}
- // Prepare the packet
- packet->probe = false;
- packet->tcp = false;
- packet->len = len + sizeof(*hdr);
+ devtool_keyrotate_probe(2);
- 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);
+ // Rename confbase/new/ to confbase/current
- memcpy(packet->data + sizeof(*hdr), data, len);
+ if(!config_rename(mesh, "new", "current")) {
+ logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
- return true;
-}
+ devtool_keyrotate_probe(3);
-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);
+ // Cleanup the "old" confbase sub-directory
- // Prepare the packet
- if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
+ if(!config_destroy(mesh->confbase, "old")) {
+ pthread_mutex_unlock(&mesh->mutex);
return false;
}
- // Send it immediately
- route(mesh, mesh->self, mesh->packet);
+ // Change the mesh handle key with new key
+
+ free(mesh->config_key);
+ mesh->config_key = new_config_key;
+
+ pthread_mutex_unlock(&mesh->mutex);
return true;
}
-bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
+void meshlink_open_params_free(meshlink_open_params_t *params) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
- // Validate arguments
- if(!mesh || !destination) {
+ if(!params) {
meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if(!len) {
- return true;
+ return;
}
- if(!data) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
+ free(params->confbase);
+ free(params->name);
+ free(params->appname);
+ free(params->lock_filename);
- // Prepare the packet
- vpn_packet_t *packet = malloc(sizeof(*packet));
+ free(params);
+}
- if(!packet) {
- meshlink_errno = MESHLINK_ENOMEM;
- return false;
- }
+/// Device class traits
+static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
+ { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
+ { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
+ { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
+ { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
+};
- if(!prepare_packet(mesh, destination, data, len, packet)) {
- free(packet);
- return false;
- }
+meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
- // Queue it
- if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
- free(packet);
- meshlink_errno = MESHLINK_ENOMEM;
- return false;
+ if(!confbase || !*confbase) {
+ logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
+ char lock_filename[PATH_MAX];
+ snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
- // Notify event loop
- signal_trigger(&mesh->loop, &mesh->datafromapp);
+ /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
+ meshlink_open_params_t params = {
+ .confbase = (char *)confbase,
+ .lock_filename = lock_filename,
+ .name = (char *)name,
+ .appname = (char *)appname,
+ .devclass = devclass,
+ .netns = -1,
+ };
- return true;
+ return meshlink_open_ex(¶ms);
}
-void meshlink_send_from_queue(event_loop_t *loop, void *data) {
- (void)loop;
- meshlink_handle_t *mesh = data;
+meshlink_handle_t *meshlink_open_encrypted(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
- logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
+ if(!confbase || !*confbase) {
+ logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
- 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);
+ char lock_filename[PATH_MAX];
+ snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
+
+ /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
+ meshlink_open_params_t params = {
+ .confbase = (char *)confbase,
+ .lock_filename = lock_filename,
+ .name = (char *)name,
+ .appname = (char *)appname,
+ .devclass = devclass,
+ .netns = -1,
+ };
+
+ if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
+ return false;
}
+
+ return meshlink_open_ex(¶ms);
}
-ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
- if(!mesh || !destination) {
+meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
+
+ if(!name) {
+ logger(NULL, MESHLINK_ERROR, "No name given!\n");
meshlink_errno = MESHLINK_EINVAL;
- return -1;
+ return NULL;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ if(!check_id(name)) {
+ logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- 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;
+ if(!appname || !*appname) {
+ logger(NULL, MESHLINK_ERROR, "No appname given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
-}
-char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
- if(!mesh || !node) {
+ if(strchr(appname, ' ')) {
+ logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
meshlink_errno = MESHLINK_EINVAL;
return NULL;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
+ logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- node_t *n = (node_t *)node;
+ /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
+ meshlink_open_params_t params = {
+ .name = (char *)name,
+ .appname = (char *)appname,
+ .devclass = devclass,
+ .netns = -1,
+ };
- if(!node_read_public_key(mesh, n) || !n->ecdsa) {
- meshlink_errno = MESHLINK_EINTERNAL;
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
+ return meshlink_open_ex(¶ms);
+}
- char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
+meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
- if(!fingerprint) {
- meshlink_errno = MESHLINK_EINTERNAL;
+ // Validate arguments provided by the application
+ if(!params->appname || !*params->appname) {
+ logger(NULL, MESHLINK_ERROR, "No appname given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
}
- pthread_mutex_unlock(&mesh->mutex);
- return fingerprint;
-}
+ if(strchr(params->appname, ' ')) {
+ logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
-meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
- if(!mesh) {
+ if(params->name && !check_id(params->name)) {
+ logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
meshlink_errno = MESHLINK_EINVAL;
return NULL;
}
- return (meshlink_node_t *)mesh->self;
-}
+ if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
+ logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ return NULL;
+ }
-meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
- if(!mesh || !name) {
+ if((params->key && !params->keylen) || (!params->key && params->keylen)) {
+ logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
meshlink_errno = MESHLINK_EINVAL;
return NULL;
}
- node_t *n = NULL;
+ meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ if(params->confbase) {
+ mesh->confbase = xstrdup(params->confbase);
}
- n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
- pthread_mutex_unlock(&mesh->mutex);
+ mesh->appname = xstrdup(params->appname);
+ mesh->devclass = params->devclass;
+ mesh->netns = params->netns;
+ mesh->log_cb = global_log_cb;
+ mesh->log_level = global_log_level;
+ mesh->packet = xmalloc(sizeof(vpn_packet_t));
- if(!n) {
- meshlink_errno = MESHLINK_ENOENT;
- }
+ randomize(&mesh->prng_state, sizeof(mesh->prng_state));
- return (meshlink_node_t *)n;
-}
+ do {
+ randomize(&mesh->session_id, sizeof(mesh->session_id));
+ } while(mesh->session_id == 0);
-meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
- if(!mesh || !name) {
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
+ memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
+
+ mesh->name = params->name ? xstrdup(params->name) : NULL;
+
+ // Hash the key
+ if(params->key) {
+ mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
+
+ if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
+ logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
+ meshlink_close(mesh);
+ meshlink_errno = MESHLINK_EINTERNAL;
+ return NULL;
+ }
}
- meshlink_submesh_t *submesh = NULL;
+ // initialize mutexes and conds
+ pthread_mutexattr_t attr;
+ pthread_mutexattr_init(&attr);
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
abort();
}
- submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
- pthread_mutex_unlock(&mesh->mutex);
+ pthread_mutex_init(&mesh->mutex, &attr);
+ pthread_cond_init(&mesh->cond, NULL);
- if(!submesh) {
- meshlink_errno = MESHLINK_ENOENT;
- }
+ mesh->threadstarted = false;
+ event_loop_init(&mesh->loop);
+ mesh->loop.data = mesh;
- return submesh;
-}
+ meshlink_queue_init(&mesh->outpacketqueue);
-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;
+ // Atomically lock the configuration directory.
+ if(!main_config_lock(mesh, params->lock_filename)) {
+ meshlink_close(mesh);
return NULL;
}
- meshlink_node_t **result;
-
- //lock mesh->nodes
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
+ // If no configuration exists yet, create it.
- *nmemb = mesh->nodes->count;
- result = realloc(nodes, *nmemb * sizeof(*nodes));
+ bool new_configuration = false;
- if(result) {
- meshlink_node_t **p = result;
+ if(!meshlink_confbase_exists(mesh)) {
+ if(!mesh->name) {
+ logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
+ meshlink_close(mesh);
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return NULL;
+ }
- for splay_each(node_t, n, mesh->nodes) {
- *p++ = (meshlink_node_t *)n;
+ if(!meshlink_setup(mesh)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
+ meshlink_close(mesh);
+ return NULL;
}
+
+ new_configuration = true;
} else {
- *nmemb = 0;
- free(nodes);
- meshlink_errno = MESHLINK_ENOMEM;
+ if(!meshlink_read_config(mesh)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
+ meshlink_close(mesh);
+ return NULL;
+ }
}
- pthread_mutex_unlock(&mesh->mutex);
+ mesh->storage_policy = params->storage_policy;
- return result;
-}
+#ifdef HAVE_MINGW
+ struct WSAData wsa_state;
+ WSAStartup(MAKEWORD(2, 2), &wsa_state);
+#endif
-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;
+ // Setup up everything
+ // TODO: we should not open listening sockets yet
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
+ bool success = false;
- *nmemb = 0;
+ if(mesh->netns != -1) {
+#ifdef HAVE_SETNS
+ pthread_t thr;
- for splay_each(node_t, n, mesh->nodes) {
- if(search_node(n, condition)) {
- ++*nmemb;
+ if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
+ void *retval = NULL;
+ success = pthread_join(thr, &retval) == 0 && retval;
}
+
+#else
+ meshlink_errno = MESHLINK_EINTERNAL;
+ return NULL;
+
+#endif // HAVE_SETNS
+ } else {
+ success = setup_network(mesh);
}
- if(*nmemb == 0) {
- free(nodes);
- pthread_mutex_unlock(&mesh->mutex);
+ if(!success) {
+ meshlink_close(mesh);
+ meshlink_errno = MESHLINK_ENETWORK;
+ return NULL;
+ }
+
+ if(!node_write_config(mesh, mesh->self, new_configuration)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
return NULL;
}
- result = realloc(nodes, *nmemb * sizeof(*nodes));
+ idle_set(&mesh->loop, idle, mesh);
- if(result) {
- meshlink_node_t **p = result;
+ logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
+ return mesh;
+}
- for splay_each(node_t, n, mesh->nodes) {
- if(search_node(n, condition)) {
- *p++ = (meshlink_node_t *)n;
- }
+static void *meshlink_main_loop(void *arg) {
+ meshlink_handle_t *mesh = arg;
+
+ if(mesh->netns != -1) {
+#ifdef HAVE_SETNS
+
+ if(setns(mesh->netns, CLONE_NEWNET) != 0) {
+ pthread_cond_signal(&mesh->cond);
+ return NULL;
}
- } else {
- *nmemb = 0;
- free(nodes);
- meshlink_errno = MESHLINK_ENOMEM;
+
+#else
+ pthread_cond_signal(&mesh->cond);
+ return NULL;
+#endif // HAVE_SETNS
+ }
+
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
}
+ logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
+ pthread_cond_broadcast(&mesh->cond);
+ main_loop(mesh);
+ logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
+
pthread_mutex_unlock(&mesh->mutex);
- return result;
+ return NULL;
}
-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;
+bool meshlink_start(meshlink_handle_t *mesh) {
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
}
- return false;
-}
+ logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
-static bool search_node_by_blacklisted(const node_t *node, const void *condition) {
- return *(bool *)condition == node->status.blacklisted;
-}
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
+ }
+
+ assert(mesh->self);
+ assert(mesh->private_key);
+ assert(mesh->self->ecdsa);
+ assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
-static bool search_node_by_submesh(const node_t *node, const void *condition) {
- if(condition == node->submesh) {
+ if(mesh->threadstarted) {
+ logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
+ pthread_mutex_unlock(&mesh->mutex);
return true;
}
- return false;
-}
+ // Reset node connection timers
+ if(mesh->peer) {
+ mesh->peer->last_connect_try = 0;
+ }
-struct time_range {
- time_t start;
- time_t end;
-};
+ //Check that a valid name is set
+ if(!mesh->name) {
+ logger(mesh, MESHLINK_ERROR, "No name given!\n");
+ meshlink_errno = MESHLINK_EINVAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
-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;
+ init_outgoings(mesh);
- if(end < start) {
- end = time(NULL);
+ // Start the main thread
- if(end < start) {
- start = end;
- }
- }
+ event_loop_start(&mesh->loop);
- if(range->end >= range->start) {
- return start <= range->end && end >= range->start;
- } else {
- return start > range->start || end < range->end;
- }
-}
+ // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+ pthread_attr_setstacksize(&attr, 1024 * 1024);
-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;
+ if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
+ logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
+ memset(&mesh->thread, 0, sizeof(mesh)->thread);
+ meshlink_errno = MESHLINK_EINTERNAL;
+ event_loop_stop(&mesh->loop);
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
}
- return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
+ pthread_cond_wait(&mesh->cond, &mesh->mutex);
+ mesh->threadstarted = true;
+
+ pthread_mutex_unlock(&mesh->mutex);
+ return true;
}
-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) {
+void meshlink_stop(meshlink_handle_t *mesh) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
+
+ if(!mesh) {
meshlink_errno = MESHLINK_EINVAL;
- return NULL;
+ return;
+ }
+
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
}
- return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
-}
+ // Shut down the main thread
+ event_loop_stop(&mesh->loop);
+
+ // TODO: send something to a local socket to kick the event loop
+
+ if(mesh->threadstarted) {
+ // Wait for the main thread to finish
+ pthread_mutex_unlock(&mesh->mutex);
+
+ if(pthread_join(mesh->thread, NULL) != 0) {
+ abort();
+ }
+
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
+ }
-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;
+ mesh->threadstarted = false;
}
- struct time_range range = {start, end};
+ // Close all metaconnections
+ if(mesh->connection) {
+ mesh->connection->outgoing = NULL;
+ terminate_connection(mesh, mesh->connection, false);
+ }
- return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
-}
+ exit_outgoings(mesh);
-meshlink_node_t **meshlink_get_all_nodes_by_blacklisted(meshlink_handle_t *mesh, bool blacklisted, meshlink_node_t **nodes, size_t *nmemb) {
- if(!mesh || !nmemb) {
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
+ // Try to write out any changed node config files, ignore errors at this point.
+ if(mesh->peer && mesh->peer->status.dirty) {
+ if(!node_write_config(mesh, mesh->peer, false)) {
+ // ignore
+ }
}
- return meshlink_get_all_nodes_by_condition(mesh, &blacklisted, nodes, nmemb, search_node_by_blacklisted);
+ pthread_mutex_unlock(&mesh->mutex);
}
-dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
- if(!mesh || !node) {
+void meshlink_close(meshlink_handle_t *mesh) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
+
+ if(!mesh) {
meshlink_errno = MESHLINK_EINVAL;
- return -1;
+ return;
}
- dev_class_t devclass;
+ // stop can be called even if mesh has not been started
+ meshlink_stop(mesh);
+ // lock is not released after this
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- devclass = ((node_t *)node)->devclass;
+ // Close and free all resources used.
- pthread_mutex_unlock(&mesh->mutex);
+ close_network_connections(mesh);
- return devclass;
-}
+ logger(mesh, MESHLINK_INFO, "Terminating");
-bool meshlink_get_node_blacklisted(meshlink_handle_t *mesh, meshlink_node_t *node) {
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- }
+ event_loop_exit(&mesh->loop);
- if(!node) {
- return mesh->default_blacklist;
+#ifdef HAVE_MINGW
+
+ if(mesh->confbase) {
+ WSACleanup();
}
- bool blacklisted;
+#endif
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ if(mesh->netns != -1) {
+ close(mesh->netns);
}
- blacklisted = ((node_t *)node)->status.blacklisted;
-
- pthread_mutex_unlock(&mesh->mutex);
+ for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
+ free(packet);
+ }
- return blacklisted;
-}
+ meshlink_queue_exit(&mesh->outpacketqueue);
-meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
- if(!mesh || !node) {
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
+ free(mesh->name);
+ free(mesh->appname);
+ free(mesh->confbase);
+ free(mesh->config_key);
+ free(mesh->external_address_url);
+ free(mesh->packet);
+ ecdsa_free(mesh->private_key);
- node_t *n = (node_t *)node;
+ main_config_unlock(mesh);
- meshlink_submesh_t *s;
+ pthread_mutex_unlock(&mesh->mutex);
+ pthread_mutex_destroy(&mesh->mutex);
- s = (meshlink_submesh_t *)n->submesh;
+ memset(mesh, 0, sizeof(*mesh));
- return s;
+ free(mesh);
}
-bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
- if(!mesh || !node) {
+bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
+
+ if(!params) {
meshlink_errno = MESHLINK_EINVAL;
- return NULL;
+ return false;
}
- node_t *n = (node_t *)node;
- bool reachable;
+ if(!params->confbase) {
+ /* Ephemeral instances */
+ return true;
+ }
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ /* Exit early if the confbase directory itself doesn't exist */
+ if(access(params->confbase, F_OK) && errno == ENOENT) {
+ return true;
}
- reachable = n->status.reachable && !n->status.blacklisted;
+ /* Take the lock the same way meshlink_open() would. */
+ FILE *lockfile = fopen(params->lock_filename, "w+");
- if(last_reachable) {
- *last_reachable = n->last_reachable;
+ if(!lockfile) {
+ logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
+ return false;
}
- if(last_unreachable) {
- *last_unreachable = n->last_unreachable;
- }
+#ifdef FD_CLOEXEC
+ fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
+#endif
- pthread_mutex_unlock(&mesh->mutex);
+#ifdef HAVE_MINGW
+ // TODO: use _locking()?
+#else
- return reachable;
-}
+ if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
+ logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
+ fclose(lockfile);
+ meshlink_errno = MESHLINK_EBUSY;
+ return false;
+ }
-bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
+#endif
- if(!mesh || !data || !len || !signature || !siglen) {
- meshlink_errno = MESHLINK_EINVAL;
+ if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
+ logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
return false;
}
- if(*siglen < MESHLINK_SIGLEN) {
- meshlink_errno = MESHLINK_EINVAL;
+ if(unlink(params->lock_filename)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
+ fclose(lockfile);
+ meshlink_errno = MESHLINK_ESTORAGE;
return false;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
+ fclose(lockfile);
- if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
- meshlink_errno = MESHLINK_EINTERNAL;
- pthread_mutex_unlock(&mesh->mutex);
+ if(!sync_path(params->confbase)) {
+ logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
+ meshlink_errno = MESHLINK_ESTORAGE;
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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
+bool meshlink_destroy(const char *confbase) {
+ logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
- if(!mesh || !source || !data || !len || !signature) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
+ char lock_filename[PATH_MAX];
+ snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
- if(siglen != MESHLINK_SIGLEN) {
+ meshlink_open_params_t params = {
+ .confbase = (char *)confbase,
+ .lock_filename = lock_filename,
+ };
+
+ return meshlink_destroy_ex(¶ms);
+}
+
+void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
+
+ if(!mesh) {
meshlink_errno = MESHLINK_EINVAL;
- return false;
+ return;
}
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- bool rval = false;
+ mesh->receive_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
- struct node_t *n = (struct node_t *)source;
+void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
- 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);
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
}
- pthread_mutex_unlock(&mesh->mutex);
- return rval;
-}
-
-static bool refresh_invitation_key(meshlink_handle_t *mesh) {
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
+ mesh->connection_try_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
- if(!count) {
- // TODO: Update invitation key if necessary?
+void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
+
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
}
- pthread_mutex_unlock(&mesh->mutex);
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
+ }
- return mesh->invitation_key;
+ mesh->node_status_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
}
-bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
+void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
- if(!mesh || !node || !address) {
+ if(!mesh) {
meshlink_errno = MESHLINK_EINVAL;
- return false;
+ return;
}
- if(!is_valid_hostname(address)) {
- logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
- meshlink_errno = MESHLINK_EINVAL;
- return false;
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
}
- if((node_t *)node != mesh->self && !port) {
- logger(mesh, MESHLINK_ERROR, "Missing port number!");
- meshlink_errno = MESHLINK_EINVAL;
- return false;
+ 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) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
- if(port && !is_valid_port(port)) {
- logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
+ if(!mesh) {
meshlink_errno = MESHLINK_EINVAL;
- return false;
+ return;
}
- char *canonical_address;
-
- xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
-
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- node_t *n = (node_t *)node;
- free(n->canonical_address);
- n->canonical_address = canonical_address;
+ mesh->node_duplicate_cb = cb;
+ pthread_mutex_unlock(&mesh->mutex);
+}
- if(!node_write_config(mesh, n, false)) {
+void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
+
+ if(mesh) {
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
+ }
+
+ mesh->log_cb = cb;
+ mesh->log_level = cb ? level : 0;
pthread_mutex_unlock(&mesh->mutex);
- return false;
+ } 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) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
+
+ if(!mesh) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return;
+ }
+
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
}
+ mesh->error_cb = cb;
pthread_mutex_unlock(&mesh->mutex);
-
- return config_sync(mesh, "current");
}
-bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
+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(!mesh || !node) {
+ if(len > MAXSIZE - sizeof(*hdr)) {
meshlink_errno = MESHLINK_EINVAL;
return false;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ 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;
}
- node_t *n = (node_t *)node;
- free(n->canonical_address);
- n->canonical_address = NULL;
+ // Prepare the packet
+ packet->probe = false;
+ packet->tcp = false;
+ packet->len = len + sizeof(*hdr);
- if(!node_write_config(mesh, n, false)) {
- pthread_mutex_unlock(&mesh->mutex);
+ 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;
}
- pthread_mutex_unlock(&mesh->mutex);
+ // Send it immediately
+ route(mesh, mesh->self, mesh->packet);
- return config_sync(mesh, "current");
+ return true;
}
-bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_add_invitation_address(%s, %s)", address ? address : "(null)", port ? port : "(null)");
+bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
- if(!mesh || !address) {
+ // Validate arguments
+ if(!mesh || !destination) {
meshlink_errno = MESHLINK_EINVAL;
return false;
}
- if(!is_valid_hostname(address)) {
- logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s\n", address);
- meshlink_errno = MESHLINK_EINVAL;
- return false;
+ if(!len) {
+ return true;
}
- if(port && !is_valid_port(port)) {
- logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s\n", address);
+ if(!data) {
meshlink_errno = MESHLINK_EINVAL;
return false;
}
- char *combo;
+ // Prepare the packet
+ vpn_packet_t *packet = malloc(sizeof(*packet));
- if(port) {
- xasprintf(&combo, "%s/%s", address, port);
- } else {
- combo = xstrdup(address);
+ if(!packet) {
+ meshlink_errno = MESHLINK_ENOMEM;
+ return false;
}
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
+ if(!prepare_packet(mesh, destination, data, len, packet)) {
+ free(packet);
+ return false;
}
- if(!mesh->invitation_addresses) {
- mesh->invitation_addresses = list_alloc((list_action_t)free);
+ // Queue it
+ if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
+ free(packet);
+ meshlink_errno = MESHLINK_ENOMEM;
+ return false;
}
- list_insert_tail(mesh->invitation_addresses, combo);
- pthread_mutex_unlock(&mesh->mutex);
+ 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_clear_invitation_addresses(struct meshlink_handle *mesh) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_clear_invitation_addresses()");
+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");
- if(!mesh) {
+ 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;
+ return -1;
}
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- if(mesh->invitation_addresses) {
- list_delete_list(mesh->invitation_addresses);
- mesh->invitation_addresses = NULL;
- }
-
- pthread_mutex_unlock(&mesh->mutex);
-}
+ node_t *n = (node_t *)destination;
-bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_add_address(%s)", address ? address : "(null)");
+ if(!n->status.reachable) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return 0;
- return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
+ } else if(n->mtuprobes > 30 && n->minmtu) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return n->minmtu;
+ } else {
+ pthread_mutex_unlock(&mesh->mutex);
+ return MTU;
+ }
}
-bool meshlink_add_external_address(meshlink_handle_t *mesh) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_add_external_address()");
-
- if(!mesh) {
+char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ if(!mesh || !node) {
meshlink_errno = MESHLINK_EINVAL;
- return false;
+ return NULL;
+ }
+
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
}
- char *address = meshlink_get_external_address(mesh);
+ node_t *n = (node_t *)node;
- if(!address) {
+ if(!node_read_public_key(mesh, n) || !n->ecdsa) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
return false;
}
- bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
- free(address);
+ char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
- return rval;
+ if(!fingerprint) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ }
+
+ pthread_mutex_unlock(&mesh->mutex);
+ return fingerprint;
}
-int meshlink_get_port(meshlink_handle_t *mesh) {
+meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
if(!mesh) {
meshlink_errno = MESHLINK_EINVAL;
- return -1;
+ return NULL;
}
- if(!mesh->myport) {
- meshlink_errno = MESHLINK_EINTERNAL;
- return -1;
+ 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;
}
- int port;
+ node_t *n = NULL;
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- port = atoi(mesh->myport);
+ n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
pthread_mutex_unlock(&mesh->mutex);
- return port;
+ if(!n) {
+ meshlink_errno = MESHLINK_ENOENT;
+ }
+
+ return (meshlink_node_t *)n;
}
-bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_port(%d)", port);
+bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
- if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
+ if(!mesh || !data || !len || !signature || !siglen) {
meshlink_errno = MESHLINK_EINVAL;
return false;
}
- if(mesh->myport && port == atoi(mesh->myport)) {
- return true;
- }
-
- if(!try_bind(mesh, port)) {
- meshlink_errno = MESHLINK_ENETWORK;
+ if(*siglen < MESHLINK_SIGLEN) {
+ meshlink_errno = MESHLINK_EINVAL;
return false;
}
- devtool_trybind_probe();
-
- bool rval = false;
-
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- 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;
+ if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
+ meshlink_errno = MESHLINK_EINTERNAL;
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
}
- /* 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:
+ *siglen = MESHLINK_SIGLEN;
pthread_mutex_unlock(&mesh->mutex);
-
- return rval && meshlink_get_port(mesh) == port;
-}
-
-void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_invitation_timeout(%d)", timeout);
-
- mesh->invitation_timeout = timeout;
+ return true;
}
-char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_invite_ex(%s, %s, %u)", submesh ? submesh->name : "(null)", name ? name : "(null)", flags);
-
- meshlink_submesh_t *s = NULL;
+bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
- if(!mesh) {
+ if(!mesh || !source || !data || !len || !signature) {
meshlink_errno = MESHLINK_EINVAL;
- return NULL;
+ return false;
}
- if(submesh) {
- s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
-
- if(s != submesh) {
- logger(mesh, MESHLINK_ERROR, "Invalid submesh handle.\n");
- meshlink_errno = MESHLINK_EINVAL;
- return NULL;
- }
- } else {
- s = (meshlink_submesh_t *)mesh->self->submesh;
+ if(siglen != MESHLINK_SIGLEN) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
}
if(pthread_mutex_lock(&mesh->mutex) != 0) {
abort();
}
- // 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;
- }
+ bool rval = false;
- // 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;
- }
+ struct node_t *n = (struct node_t *)source;
- // 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;
+ 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);
}
- // Get the local address
- char *address = get_my_hostname(mesh, flags);
+ pthread_mutex_unlock(&mesh->mutex);
+ return rval;
+}
- if(!address) {
- logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
- meshlink_errno = MESHLINK_ERESOLV;
- pthread_mutex_unlock(&mesh->mutex);
- return NULL;
+bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
+
+ if(!mesh || !node || !address) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
}
- if(!refresh_invitation_key(mesh)) {
- meshlink_errno = MESHLINK_EINTERNAL;
- pthread_mutex_unlock(&mesh->mutex);
- return NULL;
+ if(!is_valid_hostname(address)) {
+ logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
}
- // If we changed our own host config file, write it out now
- if(mesh->self->status.dirty) {
- if(!node_write_config(mesh, mesh->self, false)) {
- logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
- pthread_mutex_unlock(&mesh->mutex);
- return NULL;
- }
+ if((node_t *)node != mesh->self && !port) {
+ logger(mesh, MESHLINK_ERROR, "Missing port number!");
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+
}
- char hash[64];
+ if(port && !is_valid_port(port)) {
+ logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
+ }
- // 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);
+ char *canonical_address;
- // Create a random cookie for this invitation.
- char cookie[25];
- randomize(cookie, 18);
+ xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
- // 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);
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
+ }
- b64encode_urlsafe(cookie, cookie, 18);
+ node_t *n = (node_t *)node;
+ free(n->canonical_address);
+ n->canonical_address = canonical_address;
- free(fingerprint);
+ if(!node_write_config(mesh, n, false)) {
+ pthread_mutex_unlock(&mesh->mutex);
+ return false;
+ }
- /* Construct the invitation file */
- uint8_t outbuf[4096];
- packmsg_output_t inv = {outbuf, sizeof(outbuf)};
+ pthread_mutex_unlock(&mesh->mutex);
- 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? */
+ return config_sync(mesh, "current");
+}
- /* 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;
+bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
+ logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
- if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
- count++;
+ if(!mesh || !node) {
+ meshlink_errno = MESHLINK_EINVAL;
+ return false;
}
- /* 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]);
+ if(pthread_mutex_lock(&mesh->mutex) != 0) {
+ abort();
}
- config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
+ node_t *n = (node_t *)node;
+ free(n->canonical_address);
+ n->canonical_address = NULL;
- 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;
+ if(!node_write_config(mesh, n, false)) {
pthread_mutex_unlock(&mesh->mutex);
- return NULL;
+ return false;
}
- // 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_invite_ex(%s, %s)", submesh ? submesh->name : "(null)", name ? name : "(null)");
-
- return meshlink_invite_ex(mesh, submesh, name, 0);
+ return config_sync(mesh, "current");
}
bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
}
// 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) {
+ if(mesh->peer) {
logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
meshlink_errno = MESHLINK_EINVAL;
goto exit;
}
// Connect to the meshlink daemon mentioned in the URL.
- struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), SOCK_STREAM, 30);
+ struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
if(ai) {
for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
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, true)) {
free_node(n);
free(buf);
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) {
- if(c->status.active) {
- send_error(mesh, c, BLACKLISTED, "blacklisted");
- }
-
- shutdown(c->socket, SHUT_RDWR);
- }
- }
-
- utcp_reset_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);
- }
-
- /* Remove any outstanding invitations */
- invitation_purge_node(mesh, n->name);
-
- return node_write_config(mesh, n, true) && config_sync(mesh, "current");
-}
-
-bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist(%s)", node ? node->name : "(null)");
-
- if(!mesh || !node) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist_by_name(%s)", name ? name : "(null)");
-
- if(!mesh || !name) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- 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, true) && config_sync(mesh, "current");
-}
-
-bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist(%s)", node ? node->name : "(null)");
-
- if(!mesh || !node) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist_by_name(%s)", name ? name : "(null)");
-
- if(!mesh || !name) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- 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) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
-
- if(!mesh || !node) {
- meshlink_errno = MESHLINK_EINVAL;
- return false;
- }
-
- node_t *n = (node_t *)node;
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- /* 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, list_node);
- }
- }
- }
-
- /* Delete the config file for this node */
- if(!config_delete(mesh, "current", n->name)) {
- pthread_mutex_unlock(&mesh->mutex);
- return false;
- }
-
- /* Delete any pending invitations */
- invitation_purge_node(mesh, n->name);
-
- /* 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.
*/
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));
- utcp_set_retransmit_cb(n->utcp, channel_retransmit);
- }
+ if(mesh->peer) {
+ mesh->peer->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, mesh->peer);
+ utcp_set_mtu(mesh->peer->utcp, mesh->peer->mtu - sizeof(meshlink_packethdr_t));
+ utcp_set_retransmit_cb(mesh->peer->utcp, channel_retransmit);
}
pthread_mutex_unlock(&mesh->mutex);
mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
}
-void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_enable_discovery(%d)", enable);
-
- if(!mesh) {
- meshlink_errno = MESHLINK_EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- if(mesh->discovery.enabled == enable) {
- goto end;
- }
-
- if(mesh->threadstarted) {
- if(enable) {
- discovery_start(mesh);
- } else {
- discovery_stop(mesh);
- }
- }
-
- mesh->discovery.enabled = enable;
-
-end:
- pthread_mutex_unlock(&mesh->mutex);
-}
-
void meshlink_hint_network_change(struct meshlink_handle *mesh) {
logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
abort();
}
- if(mesh->discovery.enabled) {
- scan_ifaddrs(mesh);
- }
-
- if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
- mesh->discovery.last_update = mesh->loop.now.tv_sec;
- handle_network_change(mesh, 1);
- }
-
pthread_mutex_unlock(&mesh->mutex);
}
handle_network_change(mesh, true);
- if(mesh->discovery.enabled) {
- discovery_refresh(mesh);
- }
-
pthread_mutex_unlock(&mesh->mutex);
}
pthread_mutex_unlock(&mesh->mutex);
}
-void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
- logger(mesh, MESHLINK_DEBUG, "meshlink_set_external_address_discovery_url(%s)", url ? url : "(null)");
-
- if(!mesh) {
- meshlink_errno = EINVAL;
- return;
- }
-
- if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
- meshlink_errno = EINVAL;
- return;
- }
-
- if(pthread_mutex_lock(&mesh->mutex) != 0) {
- abort();
- }
-
- free(mesh->external_address_url);
- mesh->external_address_url = url ? xstrdup(url) : NULL;
- pthread_mutex_unlock(&mesh->mutex);
-}
-
void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
void handle_network_change(meshlink_handle_t *mesh, bool online) {
(void)online;
- if(!mesh->connections || !mesh->loop.running) {
+ if(!mesh->loop.running) {
return;
}