2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2021 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 #include "meshlink_internal.h"
39 #include "ed25519/sha512.h"
40 #include "discovery.h"
45 #define MSG_NOSIGNAL 0
47 __thread meshlink_errno_t meshlink_errno;
48 meshlink_log_cb_t global_log_cb;
49 meshlink_log_level_t global_log_level;
51 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
53 static int rstrip(char *value) {
54 int len = strlen(value);
56 while(len && strchr("\t\r\n ", value[len - 1])) {
63 static void get_canonical_address(node_t *n, char **hostname, char **port) {
64 if(!n->canonical_address) {
68 *hostname = xstrdup(n->canonical_address);
69 char *space = strchr(*hostname, ' ');
73 *port = xstrdup(space);
77 static bool is_valid_hostname(const char *hostname) {
82 for(const char *p = hostname; *p; p++) {
83 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
91 static bool is_valid_port(const char *port) {
98 unsigned long int result = strtoul(port, &end, 10);
99 return result && result < 65536 && !*end;
102 for(const char *p = port; *p; p++) {
103 if(!(isalnum(*p) || *p == '-')) {
111 static void set_timeout(int sock, int timeout) {
116 tv.tv_sec = timeout / 1000;
117 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
119 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
120 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
123 struct socket_in_netns_params {
132 static void *socket_in_netns_thread(void *arg) {
133 struct socket_in_netns_params *params = arg;
135 if(setns(params->netns, CLONE_NEWNET) == -1) {
136 meshlink_errno = MESHLINK_EINVAL;
140 params->fd = socket(params->domain, params->type, params->protocol);
146 static int socket_in_netns(int domain, int type, int protocol, int netns) {
148 return socket(domain, type, protocol);
152 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
156 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
157 if(pthread_join(thr, NULL) != 0) {
169 // Find out what local address a socket would use if we connect to the given address.
170 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
171 // of both endpoints, but this will actually not send any UDP packet.
172 static bool getlocaladdr(const char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
173 struct addrinfo *rai = NULL;
174 const struct addrinfo hint = {
175 .ai_family = AF_UNSPEC,
176 .ai_socktype = SOCK_DGRAM,
177 .ai_protocol = IPPROTO_UDP,
178 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
181 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
185 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
192 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
200 if(getsockname(sock, &sa->sa, salen)) {
209 static bool getlocaladdrname(const char *destaddr, char *host, socklen_t hostlen, int netns) {
211 socklen_t salen = sizeof(sa);
213 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
217 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
224 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
225 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
228 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
229 logger(mesh, MESHLINK_DEBUG, "meshlink_get_external_address_for_family(%d)", family);
230 const char *url = mesh->external_address_url;
233 url = "http://meshlink.io/host.cgi";
236 /* Find the hostname part between the slashes */
237 if(strncmp(url, "http://", 7)) {
239 meshlink_errno = MESHLINK_EINTERNAL;
243 const char *begin = url + 7;
245 const char *end = strchr(begin, '/');
248 end = begin + strlen(begin);
252 char host[end - begin + 1];
253 strncpy(host, begin, end - begin);
254 host[end - begin] = 0;
256 char *port = strchr(host, ':');
262 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
263 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(host), xstrdup(port ? port : "80"), SOCK_STREAM, 5);
265 char *hostname = NULL;
267 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
268 if(family != AF_UNSPEC && aip->ai_family != family) {
272 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
276 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
280 set_timeout(s, 5000);
282 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
289 send(s, "GET ", 4, 0);
290 send(s, url, strlen(url), 0);
291 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
292 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
297 if(line[len - 1] == '\n') {
301 char *p = strrchr(line, '\n');
304 hostname = xstrdup(p + 1);
320 // Check that the hostname is reasonable
321 if(hostname && !is_valid_hostname(hostname)) {
327 meshlink_errno = MESHLINK_ERESOLV;
333 static bool is_localaddr(sockaddr_t *sa) {
334 switch(sa->sa.sa_family) {
336 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
339 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
340 return first == 0 || (first & 0xffc0) == 0xfe80;
348 #ifdef HAVE_GETIFADDRS
349 struct getifaddrs_in_netns_params {
350 struct ifaddrs **ifa;
355 static void *getifaddrs_in_netns_thread(void *arg) {
356 struct getifaddrs_in_netns_params *params = arg;
358 if(setns(params->netns, CLONE_NEWNET) == -1) {
359 meshlink_errno = MESHLINK_EINVAL;
363 if(getifaddrs(params->ifa) != 0) {
371 static int getifaddrs_in_netns(struct ifaddrs **ifa, int netns) {
373 return getifaddrs(ifa);
377 struct getifaddrs_in_netns_params params = {ifa, netns};
380 if(pthread_create(&thr, NULL, getifaddrs_in_netns_thread, ¶ms) == 0) {
381 if(pthread_join(thr, NULL) != 0) {
386 return *params.ifa ? 0 : -1;
394 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
395 logger(mesh, MESHLINK_DEBUG, "meshlink_get_local_address_for_family(%d)", family);
398 meshlink_errno = MESHLINK_EINVAL;
402 // Determine address of the local interface used for outgoing connections.
403 char localaddr[NI_MAXHOST];
404 bool success = false;
406 if(family == AF_INET) {
407 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
408 } else if(family == AF_INET6) {
409 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
412 #ifdef HAVE_GETIFADDRS
415 struct ifaddrs *ifa = NULL;
416 getifaddrs_in_netns(&ifa, mesh->netns);
418 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
419 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
421 if(!sa || sa->sa.sa_family != family) {
425 if(is_localaddr(sa)) {
429 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
441 meshlink_errno = MESHLINK_ENETWORK;
445 return xstrdup(localaddr);
448 static void remove_duplicate_hostnames(char *host[], char *port[], int n) {
449 for(int i = 0; i < n; i++) {
454 // Ignore duplicate hostnames
457 for(int j = 0; j < i; j++) {
462 if(strcmp(host[i], host[j])) {
466 if(strcmp(port[i], port[j])) {
474 if(found || !is_valid_hostname(host[i])) {
484 // This gets the hostname part for use in invitation URLs
485 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
486 int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
488 char *hostname[count];
490 char *hostport = NULL;
492 memset(hostname, 0, sizeof(hostname));
493 memset(port, 0, sizeof(port));
495 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
496 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
499 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
500 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
503 // Add all explicitly set invitation addresses
504 if(mesh->invitation_addresses) {
505 for list_each(char, combo, mesh->invitation_addresses) {
506 hostname[n] = xstrdup(combo);
507 char *slash = strrchr(hostname[n], '/');
511 port[n] = xstrdup(slash + 1);
518 // Add local addresses if requested
519 if(flags & MESHLINK_INVITE_LOCAL) {
520 if(flags & MESHLINK_INVITE_IPV4) {
521 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
524 if(flags & MESHLINK_INVITE_IPV6) {
525 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
529 // Add public/canonical addresses if requested
530 if(flags & MESHLINK_INVITE_PUBLIC) {
531 // Try the CanonicalAddress first
532 get_canonical_address(mesh->self, &hostname[n], &port[n]);
534 if(!hostname[n] && count == 4) {
535 if(flags & MESHLINK_INVITE_IPV4) {
536 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
539 if(flags & MESHLINK_INVITE_IPV6) {
540 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
547 for(int i = 0; i < n; i++) {
548 // Ensure we always have a port number
549 if(hostname[i] && !port[i]) {
550 port[i] = xstrdup(mesh->myport);
554 remove_duplicate_hostnames(hostname, port, n);
556 // Resolve the hostnames
557 for(int i = 0; i < n; i++) {
562 // Convert what we have to a sockaddr
563 struct addrinfo *ai_in = adns_blocking_request(mesh, xstrdup(hostname[i]), xstrdup(port[i]), SOCK_STREAM, 5);
569 // Remember the address(es)
570 for(struct addrinfo *aip = ai_in; aip; aip = aip->ai_next) {
571 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)aip->ai_addr);
578 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
579 remove_duplicate_hostnames(hostname, port, n);
581 // Concatenate all unique address to the hostport string
582 for(int i = 0; i < n; i++) {
587 // Append the address to the hostport string
589 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
591 hostport = newhostport;
600 static bool try_bind(meshlink_handle_t *mesh, int port) {
601 struct addrinfo *ai = NULL;
602 struct addrinfo hint = {
603 .ai_flags = AI_PASSIVE,
604 .ai_family = AF_UNSPEC,
605 .ai_socktype = SOCK_STREAM,
606 .ai_protocol = IPPROTO_TCP,
610 snprintf(portstr, sizeof(portstr), "%d", port);
612 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
616 bool success = false;
618 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
619 /* Try to bind to TCP. */
621 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
624 if(errno == EADDRINUSE) {
625 /* If this port is in use for any address family, avoid it. */
633 /* If TCP worked, then we require that UDP works as well. */
635 int udp_fd = setup_udp_listen_socket(mesh, aip);
652 int check_port(meshlink_handle_t *mesh) {
653 for(int i = 0; i < 1000; i++) {
654 int port = 0x1000 + prng(mesh, 0x8000);
656 if(try_bind(mesh, port)) {
658 xasprintf(&mesh->myport, "%d", port);
663 meshlink_errno = MESHLINK_ENETWORK;
664 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
668 static bool write_main_config_files(meshlink_handle_t *mesh) {
669 if(!mesh->confbase) {
675 /* Write the main config file */
676 packmsg_output_t out = {buf, sizeof buf};
678 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
679 packmsg_add_str(&out, mesh->name);
680 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
681 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
682 packmsg_add_uint16(&out, atoi(mesh->myport));
684 if(!packmsg_output_ok(&out)) {
688 config_t config = {buf, packmsg_output_size(&out, buf)};
690 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
694 /* Write our own host config file */
695 if(!node_write_config(mesh, mesh->self, true)) {
703 meshlink_handle_t *mesh;
705 char cookie[18 + 32];
716 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
717 meshlink_handle_t *mesh = state->mesh;
718 packmsg_input_t in = {buf, len};
719 uint32_t version = packmsg_get_uint32(&in);
721 if(version != MESHLINK_INVITATION_VERSION) {
722 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
726 char *name = packmsg_get_str_dup(&in);
727 char *submesh_name = packmsg_get_str_dup(&in);
728 dev_class_t devclass = packmsg_get_int32(&in);
729 uint32_t count = packmsg_get_array(&in);
731 if(!name || !check_id(name)) {
732 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
738 if(!submesh_name || (strcmp(submesh_name, CORE_MESH) && !check_id(submesh_name))) {
739 logger(mesh, MESHLINK_DEBUG, "No valid Submesh found in invitation!\n");
746 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
753 free(mesh->self->name);
755 mesh->self->name = xstrdup(name);
756 mesh->self->submesh = strcmp(submesh_name, CORE_MESH) ? lookup_or_create_submesh(mesh, submesh_name) : NULL;
758 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
760 // Initialize configuration directory
761 if(!config_init(mesh, "current")) {
765 if(!write_main_config_files(mesh)) {
769 // Write host config files
770 for(uint32_t i = 0; i < count; i++) {
772 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
775 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
779 packmsg_input_t in2 = {data, data_len};
780 uint32_t version2 = packmsg_get_uint32(&in2);
781 char *name2 = packmsg_get_str_dup(&in2);
783 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
785 packmsg_input_invalidate(&in);
789 if(!check_id(name2)) {
794 if(!strcmp(name2, mesh->name)) {
795 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
797 meshlink_errno = MESHLINK_EPEER;
801 node_t *n = new_node();
804 config_t config = {data, data_len};
806 if(!node_read_from_config(mesh, n, &config)) {
808 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
809 meshlink_errno = MESHLINK_EPEER;
814 /* The first host config file is of the inviter itself;
815 * remember the address we are currently using for the invitation connection.
818 socklen_t salen = sizeof(sa);
820 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
821 node_add_recent_address(mesh, n, &sa);
825 /* Clear the reachability times, since we ourself have never seen these nodes yet */
826 n->last_reachable = 0;
827 n->last_unreachable = 0;
829 if(!node_write_config(mesh, n, true)) {
837 /* Ensure the configuration directory metadata is on disk */
838 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
842 if(!mesh->inviter_commits_first) {
843 devtool_set_inviter_commits_first(false);
846 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
848 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
853 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
855 join_state_t *state = handle;
856 const char *ptr = data;
859 int result = send(state->sock, ptr, len, 0);
861 if(result == -1 && errno == EINTR) {
863 } else if(result <= 0) {
874 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
875 join_state_t *state = handle;
876 meshlink_handle_t *mesh = state->mesh;
878 if(mesh->inviter_commits_first) {
880 case SPTPS_HANDSHAKE:
881 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
887 if(!finalize_join(state, msg, len)) {
891 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
892 shutdown(state->sock, SHUT_RDWR);
893 state->success = true;
901 case SPTPS_HANDSHAKE:
902 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
905 return finalize_join(state, msg, len);
908 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
909 shutdown(state->sock, SHUT_RDWR);
910 state->success = true;
921 static bool recvline(join_state_t *state) {
922 char *newline = NULL;
924 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
925 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
927 if(result == -1 && errno == EINTR) {
929 } else if(result <= 0) {
933 state->blen += result;
936 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
940 size_t len = newline - state->buffer;
942 memcpy(state->line, state->buffer, len);
943 state->line[len] = 0;
944 memmove(state->buffer, newline + 1, state->blen - len - 1);
945 state->blen -= len + 1;
950 static bool sendline(int fd, const char *format, ...) {
956 va_start(ap, format);
957 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
960 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
968 int result = send(fd, p, blen, MSG_NOSIGNAL);
970 if(result == -1 && errno == EINTR) {
972 } else if(result <= 0) {
983 static const char *errstr[] = {
984 [MESHLINK_OK] = "No error",
985 [MESHLINK_EINVAL] = "Invalid argument",
986 [MESHLINK_ENOMEM] = "Out of memory",
987 [MESHLINK_ENOENT] = "No such node",
988 [MESHLINK_EEXIST] = "Node already exists",
989 [MESHLINK_EINTERNAL] = "Internal error",
990 [MESHLINK_ERESOLV] = "Could not resolve hostname",
991 [MESHLINK_ESTORAGE] = "Storage error",
992 [MESHLINK_ENETWORK] = "Network error",
993 [MESHLINK_EPEER] = "Error communicating with peer",
994 [MESHLINK_ENOTSUP] = "Operation not supported",
995 [MESHLINK_EBUSY] = "MeshLink instance already in use",
996 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
999 const char *meshlink_strerror(meshlink_errno_t err) {
1000 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1001 return "Invalid error code";
1007 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1008 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
1010 mesh->private_key = ecdsa_generate();
1011 mesh->invitation_key = ecdsa_generate();
1013 if(!mesh->private_key || !mesh->invitation_key) {
1014 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
1015 meshlink_errno = MESHLINK_EINTERNAL;
1019 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1024 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
1025 if(a->tv_sec == b->tv_sec) {
1026 return a->tv_nsec < b->tv_nsec;
1028 return a->tv_sec < b->tv_sec;
1032 static struct timespec idle(event_loop_t *loop, void *data) {
1034 meshlink_handle_t *mesh = data;
1035 struct timespec t, tmin = {3600, 0};
1037 for splay_each(node_t, n, mesh->nodes) {
1042 t = utcp_timeout(n->utcp);
1044 if(timespec_lt(&t, &tmin)) {
1052 // Get our local address(es) by simulating connecting to an Internet host.
1053 static void add_local_addresses(meshlink_handle_t *mesh) {
1055 sa.storage.ss_family = AF_UNKNOWN;
1056 socklen_t salen = sizeof(sa);
1060 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
1061 sa.in.sin_port = ntohs(atoi(mesh->myport));
1062 node_add_recent_address(mesh, mesh->self, &sa);
1069 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
1070 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
1071 node_add_recent_address(mesh, mesh->self, &sa);
1075 static bool meshlink_setup(meshlink_handle_t *mesh) {
1076 if(!config_destroy(mesh->confbase, "new")) {
1077 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1078 meshlink_errno = MESHLINK_ESTORAGE;
1082 if(!config_destroy(mesh->confbase, "old")) {
1083 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1084 meshlink_errno = MESHLINK_ESTORAGE;
1088 if(!config_init(mesh, "current")) {
1089 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1090 meshlink_errno = MESHLINK_ESTORAGE;
1094 if(!ecdsa_keygen(mesh)) {
1095 meshlink_errno = MESHLINK_EINTERNAL;
1099 if(check_port(mesh) == 0) {
1100 meshlink_errno = MESHLINK_ENETWORK;
1104 /* Create a node for ourself */
1106 mesh->self = new_node();
1107 mesh->self->name = xstrdup(mesh->name);
1108 mesh->self->devclass = mesh->devclass;
1109 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1110 mesh->self->session_id = mesh->session_id;
1112 if(!write_main_config_files(mesh)) {
1113 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1114 meshlink_errno = MESHLINK_ESTORAGE;
1118 /* Ensure the configuration directory metadata is on disk */
1119 if(!config_sync(mesh, "current")) {
1126 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1129 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1130 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1134 packmsg_input_t in = {config.buf, config.len};
1135 const void *private_key;
1136 const void *invitation_key;
1138 uint32_t version = packmsg_get_uint32(&in);
1139 char *name = packmsg_get_str_dup(&in);
1140 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1141 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1142 uint16_t myport = packmsg_get_uint16(&in);
1144 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1145 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1147 config_free(&config);
1151 if(mesh->name && strcmp(mesh->name, name)) {
1152 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1153 meshlink_errno = MESHLINK_ESTORAGE;
1155 config_free(&config);
1161 xasprintf(&mesh->myport, "%u", myport);
1162 mesh->private_key = ecdsa_set_private_key(private_key);
1163 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1164 config_free(&config);
1166 /* Create a node for ourself and read our host configuration file */
1168 mesh->self = new_node();
1169 mesh->self->name = xstrdup(name);
1170 mesh->self->devclass = mesh->devclass;
1171 mesh->self->session_id = mesh->session_id;
1173 if(!node_read_public_key(mesh, mesh->self)) {
1174 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1175 meshlink_errno = MESHLINK_ESTORAGE;
1176 free_node(mesh->self);
1185 static void *setup_network_in_netns_thread(void *arg) {
1186 meshlink_handle_t *mesh = arg;
1188 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1192 bool success = setup_network(mesh);
1193 return success ? arg : NULL;
1195 #endif // HAVE_SETNS
1197 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1198 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
1200 if(!confbase || !*confbase) {
1201 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1202 meshlink_errno = MESHLINK_EINVAL;
1206 if(!appname || !*appname) {
1207 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1208 meshlink_errno = MESHLINK_EINVAL;
1212 if(strchr(appname, ' ')) {
1213 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1214 meshlink_errno = MESHLINK_EINVAL;
1218 if(name && !check_id(name)) {
1219 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1220 meshlink_errno = MESHLINK_EINVAL;
1224 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1225 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1226 meshlink_errno = MESHLINK_EINVAL;
1230 meshlink_open_params_t *params = xzalloc(sizeof * params);
1232 params->confbase = xstrdup(confbase);
1233 params->name = name ? xstrdup(name) : NULL;
1234 params->appname = xstrdup(appname);
1235 params->devclass = devclass;
1238 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
1243 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1244 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
1247 meshlink_errno = MESHLINK_EINVAL;
1251 params->netns = netns;
1256 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1257 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
1260 meshlink_errno = MESHLINK_EINVAL;
1264 if((!key && keylen) || (key && !keylen)) {
1265 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1266 meshlink_errno = MESHLINK_EINVAL;
1271 params->keylen = keylen;
1276 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
1277 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
1280 meshlink_errno = MESHLINK_EINVAL;
1284 params->storage_policy = policy;
1289 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
1290 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
1292 if(!params || !filename) {
1293 meshlink_errno = MESHLINK_EINVAL;
1297 free(params->lock_filename);
1298 params->lock_filename = xstrdup(filename);
1303 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1304 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
1306 if(!mesh || !new_key || !new_keylen) {
1307 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1308 meshlink_errno = MESHLINK_EINVAL;
1312 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1316 // Create hash for the new key
1317 void *new_config_key;
1318 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1320 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1321 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1322 meshlink_errno = MESHLINK_EINTERNAL;
1323 pthread_mutex_unlock(&mesh->mutex);
1327 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1329 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1330 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1331 meshlink_errno = MESHLINK_ESTORAGE;
1332 pthread_mutex_unlock(&mesh->mutex);
1336 devtool_keyrotate_probe(1);
1338 // Rename confbase/current/ to confbase/old
1340 if(!config_rename(mesh, "current", "old")) {
1341 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1342 meshlink_errno = MESHLINK_ESTORAGE;
1343 pthread_mutex_unlock(&mesh->mutex);
1347 devtool_keyrotate_probe(2);
1349 // Rename confbase/new/ to confbase/current
1351 if(!config_rename(mesh, "new", "current")) {
1352 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1353 meshlink_errno = MESHLINK_ESTORAGE;
1354 pthread_mutex_unlock(&mesh->mutex);
1358 devtool_keyrotate_probe(3);
1360 // Cleanup the "old" confbase sub-directory
1362 if(!config_destroy(mesh->confbase, "old")) {
1363 pthread_mutex_unlock(&mesh->mutex);
1367 // Change the mesh handle key with new key
1369 free(mesh->config_key);
1370 mesh->config_key = new_config_key;
1372 pthread_mutex_unlock(&mesh->mutex);
1377 void meshlink_open_params_free(meshlink_open_params_t *params) {
1378 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
1381 meshlink_errno = MESHLINK_EINVAL;
1385 free(params->confbase);
1387 free(params->appname);
1388 free(params->lock_filename);
1393 /// Device class traits
1394 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1395 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1396 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1397 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1398 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1401 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1402 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
1404 if(!confbase || !*confbase) {
1405 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1406 meshlink_errno = MESHLINK_EINVAL;
1410 char lock_filename[PATH_MAX];
1411 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1413 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1414 meshlink_open_params_t params = {
1415 .confbase = (char *)confbase,
1416 .lock_filename = lock_filename,
1417 .name = (char *)name,
1418 .appname = (char *)appname,
1419 .devclass = devclass,
1423 return meshlink_open_ex(¶ms);
1426 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) {
1427 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
1429 if(!confbase || !*confbase) {
1430 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1431 meshlink_errno = MESHLINK_EINVAL;
1435 char lock_filename[PATH_MAX];
1436 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1438 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1439 meshlink_open_params_t params = {
1440 .confbase = (char *)confbase,
1441 .lock_filename = lock_filename,
1442 .name = (char *)name,
1443 .appname = (char *)appname,
1444 .devclass = devclass,
1448 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1452 return meshlink_open_ex(¶ms);
1455 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1456 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
1459 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1460 meshlink_errno = MESHLINK_EINVAL;
1464 if(!check_id(name)) {
1465 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1466 meshlink_errno = MESHLINK_EINVAL;
1470 if(!appname || !*appname) {
1471 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1472 meshlink_errno = MESHLINK_EINVAL;
1476 if(strchr(appname, ' ')) {
1477 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1478 meshlink_errno = MESHLINK_EINVAL;
1482 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1483 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1484 meshlink_errno = MESHLINK_EINVAL;
1488 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1489 meshlink_open_params_t params = {
1490 .name = (char *)name,
1491 .appname = (char *)appname,
1492 .devclass = devclass,
1496 return meshlink_open_ex(¶ms);
1499 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1500 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
1502 // Validate arguments provided by the application
1503 if(!params->appname || !*params->appname) {
1504 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1505 meshlink_errno = MESHLINK_EINVAL;
1509 if(strchr(params->appname, ' ')) {
1510 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1511 meshlink_errno = MESHLINK_EINVAL;
1515 if(params->name && !check_id(params->name)) {
1516 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1517 meshlink_errno = MESHLINK_EINVAL;
1521 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1522 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1523 meshlink_errno = MESHLINK_EINVAL;
1527 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1528 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1529 meshlink_errno = MESHLINK_EINVAL;
1533 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1535 if(params->confbase) {
1536 mesh->confbase = xstrdup(params->confbase);
1539 mesh->appname = xstrdup(params->appname);
1540 mesh->devclass = params->devclass;
1541 mesh->discovery.enabled = true;
1542 mesh->invitation_timeout = 604800; // 1 week
1543 mesh->netns = params->netns;
1544 mesh->submeshes = NULL;
1545 mesh->log_cb = global_log_cb;
1546 mesh->log_level = global_log_level;
1547 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1549 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1552 randomize(&mesh->session_id, sizeof(mesh->session_id));
1553 } while(mesh->session_id == 0);
1555 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1557 mesh->name = params->name ? xstrdup(params->name) : NULL;
1561 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1563 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1564 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1565 meshlink_close(mesh);
1566 meshlink_errno = MESHLINK_EINTERNAL;
1571 // initialize mutexes and conds
1572 pthread_mutexattr_t attr;
1573 pthread_mutexattr_init(&attr);
1575 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
1579 pthread_mutex_init(&mesh->mutex, &attr);
1580 pthread_cond_init(&mesh->cond, NULL);
1582 pthread_cond_init(&mesh->adns_cond, NULL);
1584 mesh->threadstarted = false;
1585 event_loop_init(&mesh->loop);
1586 mesh->loop.data = mesh;
1588 meshlink_queue_init(&mesh->outpacketqueue);
1590 // Atomically lock the configuration directory.
1591 if(!main_config_lock(mesh, params->lock_filename)) {
1592 meshlink_close(mesh);
1596 // If no configuration exists yet, create it.
1598 bool new_configuration = false;
1600 if(!meshlink_confbase_exists(mesh)) {
1602 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1603 meshlink_close(mesh);
1604 meshlink_errno = MESHLINK_ESTORAGE;
1608 if(!meshlink_setup(mesh)) {
1609 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1610 meshlink_close(mesh);
1614 new_configuration = true;
1616 if(!meshlink_read_config(mesh)) {
1617 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1618 meshlink_close(mesh);
1623 mesh->storage_policy = params->storage_policy;
1626 struct WSAData wsa_state;
1627 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1630 // Setup up everything
1631 // TODO: we should not open listening sockets yet
1633 bool success = false;
1635 if(mesh->netns != -1) {
1639 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1640 void *retval = NULL;
1641 success = pthread_join(thr, &retval) == 0 && retval;
1645 meshlink_errno = MESHLINK_EINTERNAL;
1648 #endif // HAVE_SETNS
1650 success = setup_network(mesh);
1654 meshlink_close(mesh);
1655 meshlink_errno = MESHLINK_ENETWORK;
1659 add_local_addresses(mesh);
1661 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1662 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1666 idle_set(&mesh->loop, idle, mesh);
1668 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1672 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1673 logger(NULL, MESHLINK_DEBUG, "meshlink_submesh_open(%s)", submesh);
1675 meshlink_submesh_t *s = NULL;
1678 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1679 meshlink_errno = MESHLINK_EINVAL;
1683 if(!submesh || !*submesh) {
1684 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1685 meshlink_errno = MESHLINK_EINVAL;
1690 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1694 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1696 pthread_mutex_unlock(&mesh->mutex);
1701 static void *meshlink_main_loop(void *arg) {
1702 meshlink_handle_t *mesh = arg;
1704 if(mesh->netns != -1) {
1707 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1708 pthread_cond_signal(&mesh->cond);
1713 pthread_cond_signal(&mesh->cond);
1715 #endif // HAVE_SETNS
1718 if(mesh->discovery.enabled) {
1719 discovery_start(mesh);
1722 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1726 if(mesh->thread_status_cb) {
1727 mesh->thread_status_cb(mesh, true);
1730 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1731 pthread_cond_broadcast(&mesh->cond);
1733 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1735 if(mesh->thread_status_cb) {
1736 mesh->thread_status_cb(mesh, false);
1739 pthread_mutex_unlock(&mesh->mutex);
1742 if(mesh->discovery.enabled) {
1743 discovery_stop(mesh);
1749 bool meshlink_start(meshlink_handle_t *mesh) {
1751 meshlink_errno = MESHLINK_EINVAL;
1755 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1757 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1762 assert(mesh->private_key);
1763 assert(mesh->self->ecdsa);
1764 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1766 if(mesh->threadstarted) {
1767 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1768 pthread_mutex_unlock(&mesh->mutex);
1772 if(mesh->listen_socket[0].tcp.fd < 0) {
1773 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1774 meshlink_errno = MESHLINK_ENETWORK;
1778 // Reset node connection timers
1779 for splay_each(node_t, n, mesh->nodes) {
1780 n->last_connect_try = 0;
1783 // TODO: open listening sockets first
1785 //Check that a valid name is set
1787 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1788 meshlink_errno = MESHLINK_EINVAL;
1789 pthread_mutex_unlock(&mesh->mutex);
1793 init_outgoings(mesh);
1796 // Start the main thread
1798 event_loop_start(&mesh->loop);
1800 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1801 pthread_attr_t attr;
1802 pthread_attr_init(&attr);
1803 pthread_attr_setstacksize(&attr, 1024 * 1024);
1805 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1806 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1807 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1808 meshlink_errno = MESHLINK_EINTERNAL;
1809 event_loop_stop(&mesh->loop);
1810 pthread_mutex_unlock(&mesh->mutex);
1814 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1815 mesh->threadstarted = true;
1817 // Ensure we are considered reachable
1820 pthread_mutex_unlock(&mesh->mutex);
1824 void meshlink_stop(meshlink_handle_t *mesh) {
1825 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1828 meshlink_errno = MESHLINK_EINVAL;
1832 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1836 // Shut down the main thread
1837 event_loop_stop(&mesh->loop);
1839 // Send ourselves a UDP packet to kick the event loop
1840 for(int i = 0; i < mesh->listen_sockets; i++) {
1842 socklen_t salen = sizeof(sa);
1844 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1845 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1849 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1850 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1854 if(mesh->threadstarted) {
1855 // Wait for the main thread to finish
1856 pthread_mutex_unlock(&mesh->mutex);
1858 if(pthread_join(mesh->thread, NULL) != 0) {
1862 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1866 mesh->threadstarted = false;
1869 // Close all metaconnections
1870 if(mesh->connections) {
1871 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1873 connection_t *c = node->data;
1875 terminate_connection(mesh, c, false);
1880 exit_outgoings(mesh);
1882 // Ensure we are considered unreachable
1887 // Try to write out any changed node config files, ignore errors at this point.
1889 for splay_each(node_t, n, mesh->nodes) {
1890 if(n->status.dirty) {
1891 if(!node_write_config(mesh, n, false)) {
1898 pthread_mutex_unlock(&mesh->mutex);
1901 void meshlink_close(meshlink_handle_t *mesh) {
1902 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1905 meshlink_errno = MESHLINK_EINVAL;
1909 // stop can be called even if mesh has not been started
1910 meshlink_stop(mesh);
1912 // lock is not released after this
1913 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1917 // Close and free all resources used.
1919 close_network_connections(mesh);
1921 logger(mesh, MESHLINK_INFO, "Terminating");
1923 event_loop_exit(&mesh->loop);
1927 if(mesh->confbase) {
1933 ecdsa_free(mesh->invitation_key);
1935 if(mesh->netns != -1) {
1939 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1943 meshlink_queue_exit(&mesh->outpacketqueue);
1946 free(mesh->appname);
1947 free(mesh->confbase);
1948 free(mesh->config_key);
1949 free(mesh->external_address_url);
1951 ecdsa_free(mesh->private_key);
1953 if(mesh->invitation_addresses) {
1954 list_delete_list(mesh->invitation_addresses);
1957 main_config_unlock(mesh);
1959 pthread_mutex_unlock(&mesh->mutex);
1960 pthread_mutex_destroy(&mesh->mutex);
1962 memset(mesh, 0, sizeof(*mesh));
1967 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1968 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1971 meshlink_errno = MESHLINK_EINVAL;
1975 if(!params->confbase) {
1976 /* Ephemeral instances */
1980 /* Exit early if the confbase directory itself doesn't exist */
1981 if(access(params->confbase, F_OK) && errno == ENOENT) {
1985 /* Take the lock the same way meshlink_open() would. */
1986 FILE *lockfile = fopen(params->lock_filename, "w+");
1989 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1990 meshlink_errno = MESHLINK_ESTORAGE;
1995 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1999 // TODO: use _locking()?
2002 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
2003 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
2005 meshlink_errno = MESHLINK_EBUSY;
2011 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
2012 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
2016 if(unlink(params->lock_filename)) {
2017 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
2019 meshlink_errno = MESHLINK_ESTORAGE;
2025 if(!sync_path(params->confbase)) {
2026 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
2027 meshlink_errno = MESHLINK_ESTORAGE;
2034 bool meshlink_destroy(const char *confbase) {
2035 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
2037 char lock_filename[PATH_MAX];
2038 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
2040 meshlink_open_params_t params = {
2041 .confbase = (char *)confbase,
2042 .lock_filename = lock_filename,
2045 return meshlink_destroy_ex(¶ms);
2048 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
2049 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
2052 meshlink_errno = MESHLINK_EINVAL;
2056 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2060 mesh->receive_cb = cb;
2061 pthread_mutex_unlock(&mesh->mutex);
2064 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
2065 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
2068 meshlink_errno = MESHLINK_EINVAL;
2072 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2076 mesh->connection_try_cb = cb;
2077 pthread_mutex_unlock(&mesh->mutex);
2080 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
2081 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
2084 meshlink_errno = MESHLINK_EINVAL;
2088 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2092 mesh->node_status_cb = cb;
2093 pthread_mutex_unlock(&mesh->mutex);
2096 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
2097 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
2100 meshlink_errno = MESHLINK_EINVAL;
2104 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2108 mesh->node_pmtu_cb = cb;
2109 pthread_mutex_unlock(&mesh->mutex);
2112 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
2113 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
2116 meshlink_errno = MESHLINK_EINVAL;
2120 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2124 mesh->node_duplicate_cb = cb;
2125 pthread_mutex_unlock(&mesh->mutex);
2128 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
2129 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
2132 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2137 mesh->log_level = cb ? level : 0;
2138 pthread_mutex_unlock(&mesh->mutex);
2141 global_log_level = cb ? level : 0;
2145 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
2146 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
2149 meshlink_errno = MESHLINK_EINVAL;
2153 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2157 mesh->error_cb = cb;
2158 pthread_mutex_unlock(&mesh->mutex);
2161 void meshlink_set_blacklisted_cb(struct meshlink_handle *mesh, meshlink_blacklisted_cb_t cb) {
2162 logger(mesh, MESHLINK_DEBUG, "meshlink_set_blacklisted_cb(%p)", (void *)(intptr_t)cb);
2165 meshlink_errno = MESHLINK_EINVAL;
2169 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2173 mesh->blacklisted_cb = cb;
2174 pthread_mutex_unlock(&mesh->mutex);
2177 void meshlink_set_thread_status_cb(struct meshlink_handle *mesh, meshlink_thread_status_cb_t cb) {
2178 logger(mesh, MESHLINK_DEBUG, "meshlink_set_thread_status_cb(%p)", (void *)(intptr_t)cb);
2181 meshlink_errno = MESHLINK_EINVAL;
2185 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2189 mesh->thread_status_cb = cb;
2190 pthread_mutex_unlock(&mesh->mutex);
2193 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
2194 meshlink_packethdr_t *hdr;
2196 if(len > MAXSIZE - sizeof(*hdr)) {
2197 meshlink_errno = MESHLINK_EINVAL;
2201 node_t *n = (node_t *)destination;
2203 if(n->status.blacklisted) {
2204 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
2205 meshlink_errno = MESHLINK_EBLACKLISTED;
2209 // Prepare the packet
2210 packet->probe = false;
2211 packet->tcp = false;
2212 packet->len = len + sizeof(*hdr);
2214 hdr = (meshlink_packethdr_t *)packet->data;
2215 memset(hdr, 0, sizeof(*hdr));
2216 // leave the last byte as 0 to make sure strings are always
2217 // null-terminated if they are longer than the buffer
2218 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
2219 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
2221 memcpy(packet->data + sizeof(*hdr), data, len);
2226 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2228 assert(destination);
2232 // Prepare the packet
2233 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2237 // Send it immediately
2238 route(mesh, mesh->self, mesh->packet);
2243 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2244 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
2246 // Validate arguments
2247 if(!mesh || !destination) {
2248 meshlink_errno = MESHLINK_EINVAL;
2257 meshlink_errno = MESHLINK_EINVAL;
2261 // Prepare the packet
2262 vpn_packet_t *packet = malloc(sizeof(*packet));
2265 meshlink_errno = MESHLINK_ENOMEM;
2269 if(!prepare_packet(mesh, destination, data, len, packet)) {
2275 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2277 meshlink_errno = MESHLINK_ENOMEM;
2281 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2283 // Notify event loop
2284 signal_trigger(&mesh->loop, &mesh->datafromapp);
2289 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2291 meshlink_handle_t *mesh = data;
2293 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2295 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2296 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2297 mesh->self->in_packets++;
2298 mesh->self->in_bytes += packet->len;
2299 route(mesh, mesh->self, packet);
2304 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2305 if(!mesh || !destination) {
2306 meshlink_errno = MESHLINK_EINVAL;
2310 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2314 node_t *n = (node_t *)destination;
2316 if(!n->status.reachable) {
2317 pthread_mutex_unlock(&mesh->mutex);
2320 } else if(n->mtuprobes > 30 && n->minmtu) {
2321 pthread_mutex_unlock(&mesh->mutex);
2324 pthread_mutex_unlock(&mesh->mutex);
2329 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2330 if(!mesh || !node) {
2331 meshlink_errno = MESHLINK_EINVAL;
2335 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2339 node_t *n = (node_t *)node;
2341 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2342 meshlink_errno = MESHLINK_EINTERNAL;
2343 pthread_mutex_unlock(&mesh->mutex);
2347 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2350 meshlink_errno = MESHLINK_EINTERNAL;
2353 pthread_mutex_unlock(&mesh->mutex);
2357 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2359 meshlink_errno = MESHLINK_EINVAL;
2363 return (meshlink_node_t *)mesh->self;
2366 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2367 if(!mesh || !name) {
2368 meshlink_errno = MESHLINK_EINVAL;
2374 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2378 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2379 pthread_mutex_unlock(&mesh->mutex);
2382 meshlink_errno = MESHLINK_ENOENT;
2385 return (meshlink_node_t *)n;
2388 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2389 if(!mesh || !name) {
2390 meshlink_errno = MESHLINK_EINVAL;
2394 meshlink_submesh_t *submesh = NULL;
2396 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2400 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2401 pthread_mutex_unlock(&mesh->mutex);
2404 meshlink_errno = MESHLINK_ENOENT;
2410 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2411 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2412 meshlink_errno = MESHLINK_EINVAL;
2416 meshlink_node_t **result;
2419 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2423 *nmemb = mesh->nodes->count;
2424 result = realloc(nodes, *nmemb * sizeof(*nodes));
2427 meshlink_node_t **p = result;
2429 for splay_each(node_t, n, mesh->nodes) {
2430 *p++ = (meshlink_node_t *)n;
2435 meshlink_errno = MESHLINK_ENOMEM;
2438 pthread_mutex_unlock(&mesh->mutex);
2443 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) {
2444 meshlink_node_t **result;
2446 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2452 for splay_each(node_t, n, mesh->nodes) {
2453 if(search_node(n, condition)) {
2460 pthread_mutex_unlock(&mesh->mutex);
2464 result = realloc(nodes, *nmemb * sizeof(*nodes));
2467 meshlink_node_t **p = result;
2469 for splay_each(node_t, n, mesh->nodes) {
2470 if(search_node(n, condition)) {
2471 *p++ = (meshlink_node_t *)n;
2477 meshlink_errno = MESHLINK_ENOMEM;
2480 pthread_mutex_unlock(&mesh->mutex);
2485 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2486 dev_class_t *devclass = (dev_class_t *)condition;
2488 if(*devclass == (dev_class_t)node->devclass) {
2495 static bool search_node_by_blacklisted(const node_t *node, const void *condition) {
2496 return *(bool *)condition == node->status.blacklisted;
2499 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2500 if(condition == node->submesh) {
2512 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2513 const struct time_range *range = condition;
2514 time_t start = node->last_reachable;
2515 time_t end = node->last_unreachable;
2525 if(range->end >= range->start) {
2526 return start <= range->end && end >= range->start;
2528 return start > range->start || end < range->end;
2532 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) {
2533 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2534 meshlink_errno = MESHLINK_EINVAL;
2538 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2541 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2542 if(!mesh || !submesh || !nmemb) {
2543 meshlink_errno = MESHLINK_EINVAL;
2547 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2550 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) {
2551 if(!mesh || !nmemb) {
2552 meshlink_errno = MESHLINK_EINVAL;
2556 struct time_range range = {start, end};
2558 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2561 meshlink_node_t **meshlink_get_all_nodes_by_blacklisted(meshlink_handle_t *mesh, bool blacklisted, meshlink_node_t **nodes, size_t *nmemb) {
2562 if(!mesh || !nmemb) {
2563 meshlink_errno = MESHLINK_EINVAL;
2567 return meshlink_get_all_nodes_by_condition(mesh, &blacklisted, nodes, nmemb, search_node_by_blacklisted);
2570 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2571 if(!mesh || !node) {
2572 meshlink_errno = MESHLINK_EINVAL;
2576 dev_class_t devclass;
2578 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2582 devclass = ((node_t *)node)->devclass;
2584 pthread_mutex_unlock(&mesh->mutex);
2589 bool meshlink_get_node_tiny(meshlink_handle_t *mesh, meshlink_node_t *node) {
2590 if(!mesh || !node) {
2591 meshlink_errno = MESHLINK_EINVAL;
2597 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2601 tiny = ((node_t *)node)->status.tiny;
2603 pthread_mutex_unlock(&mesh->mutex);
2608 bool meshlink_get_node_blacklisted(meshlink_handle_t *mesh, meshlink_node_t *node) {
2610 meshlink_errno = MESHLINK_EINVAL;
2614 return mesh->default_blacklist;
2619 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2623 blacklisted = ((node_t *)node)->status.blacklisted;
2625 pthread_mutex_unlock(&mesh->mutex);
2630 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2631 if(!mesh || !node) {
2632 meshlink_errno = MESHLINK_EINVAL;
2636 node_t *n = (node_t *)node;
2638 meshlink_submesh_t *s;
2640 s = (meshlink_submesh_t *)n->submesh;
2645 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2646 if(!mesh || !node) {
2647 meshlink_errno = MESHLINK_EINVAL;
2651 node_t *n = (node_t *)node;
2654 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2658 reachable = n->status.reachable && !n->status.blacklisted;
2660 if(last_reachable) {
2661 *last_reachable = n->last_reachable;
2664 if(last_unreachable) {
2665 *last_unreachable = n->last_unreachable;
2668 pthread_mutex_unlock(&mesh->mutex);
2673 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2674 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
2676 if(!mesh || !data || !len || !signature || !siglen) {
2677 meshlink_errno = MESHLINK_EINVAL;
2681 if(*siglen < MESHLINK_SIGLEN) {
2682 meshlink_errno = MESHLINK_EINVAL;
2686 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2690 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2691 meshlink_errno = MESHLINK_EINTERNAL;
2692 pthread_mutex_unlock(&mesh->mutex);
2696 *siglen = MESHLINK_SIGLEN;
2697 pthread_mutex_unlock(&mesh->mutex);
2701 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2702 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
2704 if(!mesh || !source || !data || !len || !signature) {
2705 meshlink_errno = MESHLINK_EINVAL;
2709 if(siglen != MESHLINK_SIGLEN) {
2710 meshlink_errno = MESHLINK_EINVAL;
2714 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2720 struct node_t *n = (struct node_t *)source;
2722 if(!node_read_public_key(mesh, n)) {
2723 meshlink_errno = MESHLINK_EINTERNAL;
2726 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2729 pthread_mutex_unlock(&mesh->mutex);
2733 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2734 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2738 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2741 // TODO: Update invitation key if necessary?
2744 pthread_mutex_unlock(&mesh->mutex);
2746 return mesh->invitation_key;
2749 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2750 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
2752 if(!mesh || !node || !address) {
2753 meshlink_errno = MESHLINK_EINVAL;
2757 if(!is_valid_hostname(address)) {
2758 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
2759 meshlink_errno = MESHLINK_EINVAL;
2763 if((node_t *)node != mesh->self && !port) {
2764 logger(mesh, MESHLINK_ERROR, "Missing port number!");
2765 meshlink_errno = MESHLINK_EINVAL;
2770 if(port && !is_valid_port(port)) {
2771 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
2772 meshlink_errno = MESHLINK_EINVAL;
2776 char *canonical_address;
2778 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
2780 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2784 node_t *n = (node_t *)node;
2785 free(n->canonical_address);
2786 n->canonical_address = canonical_address;
2788 if(!node_write_config(mesh, n, false)) {
2789 pthread_mutex_unlock(&mesh->mutex);
2793 pthread_mutex_unlock(&mesh->mutex);
2795 return config_sync(mesh, "current");
2798 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
2799 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
2801 if(!mesh || !node) {
2802 meshlink_errno = MESHLINK_EINVAL;
2806 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2810 node_t *n = (node_t *)node;
2811 free(n->canonical_address);
2812 n->canonical_address = NULL;
2814 if(!node_write_config(mesh, n, false)) {
2815 pthread_mutex_unlock(&mesh->mutex);
2819 pthread_mutex_unlock(&mesh->mutex);
2821 return config_sync(mesh, "current");
2824 bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
2825 logger(mesh, MESHLINK_DEBUG, "meshlink_add_invitation_address(%s, %s)", address ? address : "(null)", port ? port : "(null)");
2827 if(!mesh || !address) {
2828 meshlink_errno = MESHLINK_EINVAL;
2832 if(!is_valid_hostname(address)) {
2833 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s\n", address);
2834 meshlink_errno = MESHLINK_EINVAL;
2838 if(port && !is_valid_port(port)) {
2839 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s\n", address);
2840 meshlink_errno = MESHLINK_EINVAL;
2847 xasprintf(&combo, "%s/%s", address, port);
2849 combo = xstrdup(address);
2852 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2856 if(!mesh->invitation_addresses) {
2857 mesh->invitation_addresses = list_alloc((list_action_t)free);
2860 list_insert_tail(mesh->invitation_addresses, combo);
2861 pthread_mutex_unlock(&mesh->mutex);
2866 void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
2867 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_invitation_addresses()");
2870 meshlink_errno = MESHLINK_EINVAL;
2874 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2878 if(mesh->invitation_addresses) {
2879 list_delete_list(mesh->invitation_addresses);
2880 mesh->invitation_addresses = NULL;
2883 pthread_mutex_unlock(&mesh->mutex);
2886 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2887 logger(mesh, MESHLINK_DEBUG, "meshlink_add_address(%s)", address ? address : "(null)");
2889 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2892 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2893 logger(mesh, MESHLINK_DEBUG, "meshlink_add_external_address()");
2896 meshlink_errno = MESHLINK_EINVAL;
2900 char *address = meshlink_get_external_address(mesh);
2906 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2912 int meshlink_get_port(meshlink_handle_t *mesh) {
2914 meshlink_errno = MESHLINK_EINVAL;
2919 meshlink_errno = MESHLINK_EINTERNAL;
2925 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2929 port = atoi(mesh->myport);
2930 pthread_mutex_unlock(&mesh->mutex);
2935 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2936 logger(mesh, MESHLINK_DEBUG, "meshlink_set_port(%d)", port);
2938 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2939 meshlink_errno = MESHLINK_EINVAL;
2943 if(mesh->myport && port == atoi(mesh->myport)) {
2947 if(!try_bind(mesh, port)) {
2948 meshlink_errno = MESHLINK_ENETWORK;
2952 devtool_trybind_probe();
2956 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2960 if(mesh->threadstarted) {
2961 meshlink_errno = MESHLINK_EINVAL;
2966 xasprintf(&mesh->myport, "%d", port);
2968 /* Close down the network. This also deletes mesh->self. */
2969 close_network_connections(mesh);
2971 /* Recreate mesh->self. */
2972 mesh->self = new_node();
2973 mesh->self->name = xstrdup(mesh->name);
2974 mesh->self->devclass = mesh->devclass;
2975 mesh->self->session_id = mesh->session_id;
2976 xasprintf(&mesh->myport, "%d", port);
2978 if(!node_read_public_key(mesh, mesh->self)) {
2979 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2980 meshlink_errno = MESHLINK_ESTORAGE;
2981 free_node(mesh->self);
2984 } else if(!setup_network(mesh)) {
2985 meshlink_errno = MESHLINK_ENETWORK;
2989 /* Rebuild our own list of recent addresses */
2990 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2991 add_local_addresses(mesh);
2993 /* Write meshlink.conf with the updated port number */
2994 write_main_config_files(mesh);
2996 rval = config_sync(mesh, "current");
2999 pthread_mutex_unlock(&mesh->mutex);
3001 return rval && meshlink_get_port(mesh) == port;
3004 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
3005 logger(mesh, MESHLINK_DEBUG, "meshlink_invitation_timeout(%d)", timeout);
3007 mesh->invitation_timeout = timeout;
3010 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
3011 logger(mesh, MESHLINK_DEBUG, "meshlink_invite_ex(%s, %s, %u)", submesh ? submesh->name : "(null)", name ? name : "(null)", flags);
3013 meshlink_submesh_t *s = NULL;
3016 meshlink_errno = MESHLINK_EINVAL;
3021 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
3024 logger(mesh, MESHLINK_ERROR, "Invalid submesh handle.\n");
3025 meshlink_errno = MESHLINK_EINVAL;
3029 s = (meshlink_submesh_t *)mesh->self->submesh;
3032 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3036 // Check validity of the new node's name
3037 if(!check_id(name)) {
3038 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
3039 meshlink_errno = MESHLINK_EINVAL;
3040 pthread_mutex_unlock(&mesh->mutex);
3044 // Ensure no host configuration file with that name exists
3045 if(config_exists(mesh, "current", name)) {
3046 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
3047 meshlink_errno = MESHLINK_EEXIST;
3048 pthread_mutex_unlock(&mesh->mutex);
3052 // Ensure no other nodes know about this name
3053 if(lookup_node(mesh, name)) {
3054 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
3055 meshlink_errno = MESHLINK_EEXIST;
3056 pthread_mutex_unlock(&mesh->mutex);
3060 // Get the local address
3061 char *address = get_my_hostname(mesh, flags);
3064 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
3065 meshlink_errno = MESHLINK_ERESOLV;
3066 pthread_mutex_unlock(&mesh->mutex);
3070 if(!refresh_invitation_key(mesh)) {
3071 meshlink_errno = MESHLINK_EINTERNAL;
3072 pthread_mutex_unlock(&mesh->mutex);
3076 // If we changed our own host config file, write it out now
3077 if(mesh->self->status.dirty) {
3078 if(!node_write_config(mesh, mesh->self, false)) {
3079 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
3080 pthread_mutex_unlock(&mesh->mutex);
3087 // Create a hash of the key.
3088 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
3089 sha512(fingerprint, strlen(fingerprint), hash);
3090 b64encode_urlsafe(hash, hash, 18);
3092 // Create a random cookie for this invitation.
3094 randomize(cookie, 18);
3096 // Create a filename that doesn't reveal the cookie itself
3097 char buf[18 + strlen(fingerprint)];
3098 char cookiehash[64];
3099 memcpy(buf, cookie, 18);
3100 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
3101 sha512(buf, sizeof(buf), cookiehash);
3102 b64encode_urlsafe(cookiehash, cookiehash, 18);
3104 b64encode_urlsafe(cookie, cookie, 18);
3108 /* Construct the invitation file */
3109 uint8_t outbuf[4096];
3110 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
3112 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
3113 packmsg_add_str(&inv, name);
3114 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
3115 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
3117 /* TODO: Add several host config files to bootstrap connections.
3118 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
3119 * and are not blacklisted.
3121 config_t configs[5];
3122 memset(configs, 0, sizeof(configs));
3125 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
3129 /* Append host config files to the invitation file */
3130 packmsg_add_array(&inv, count);
3132 for(int i = 0; i < count; i++) {
3133 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
3134 config_free(&configs[i]);
3137 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
3139 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
3140 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
3141 meshlink_errno = MESHLINK_ESTORAGE;
3142 pthread_mutex_unlock(&mesh->mutex);
3146 // Create an URL from the local address, key hash and cookie
3148 xasprintf(&url, "%s/%s%s", address, hash, cookie);
3151 pthread_mutex_unlock(&mesh->mutex);
3155 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
3156 logger(mesh, MESHLINK_DEBUG, "meshlink_invite_ex(%s, %s)", submesh ? submesh->name : "(null)", name ? name : "(null)");
3158 return meshlink_invite_ex(mesh, submesh, name, 0);
3161 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
3162 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
3164 if(!mesh || !invitation) {
3165 meshlink_errno = MESHLINK_EINVAL;
3169 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
3170 meshlink_errno = MESHLINK_EINVAL;
3174 join_state_t state = {
3179 ecdsa_t *key = NULL;
3180 ecdsa_t *hiskey = NULL;
3182 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
3183 char copy[strlen(invitation) + 1];
3185 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3189 //Before doing meshlink_join make sure we are not connected to another mesh
3190 if(mesh->threadstarted) {
3191 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
3192 meshlink_errno = MESHLINK_EINVAL;
3196 // 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.
3197 if(mesh->nodes->count > 1) {
3198 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
3199 meshlink_errno = MESHLINK_EINVAL;
3203 strcpy(copy, invitation);
3205 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
3207 char *slash = strchr(copy, '/');
3215 if(strlen(slash) != 48) {
3219 char *address = copy;
3222 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
3226 if(mesh->inviter_commits_first) {
3227 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
3230 // Generate a throw-away key for the invitation.
3231 key = ecdsa_generate();
3234 meshlink_errno = MESHLINK_EINTERNAL;
3238 char *b64key = ecdsa_get_base64_public_key(key);
3241 while(address && *address) {
3242 // We allow commas in the address part to support multiple addresses in one invitation URL.
3243 comma = strchr(address, ',');
3249 // Split of the port
3250 port = strrchr(address, ':');
3258 // IPv6 address are enclosed in brackets, per RFC 3986
3259 if(*address == '[') {
3261 char *bracket = strchr(address, ']');
3274 // Connect to the meshlink daemon mentioned in the URL.
3275 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), SOCK_STREAM, 30);
3278 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
3279 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
3281 if(state.sock == -1) {
3282 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
3283 meshlink_errno = MESHLINK_ENETWORK;
3289 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
3292 set_timeout(state.sock, 5000);
3294 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
3295 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
3296 meshlink_errno = MESHLINK_ENETWORK;
3297 closesocket(state.sock);
3307 meshlink_errno = MESHLINK_ERESOLV;
3310 if(state.sock != -1 || !comma) {
3317 if(state.sock == -1) {
3321 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
3323 // Tell him we have an invitation, and give him our throw-away key.
3327 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
3328 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
3329 meshlink_errno = MESHLINK_ENETWORK;
3335 char hisname[4096] = "";
3336 int code, hismajor, hisminor = 0;
3338 if(!recvline(&state) || sscanf(state.line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(&state) || !rstrip(state.line) || sscanf(state.line, "%d ", &code) != 1 || code != ACK || strlen(state.line) < 3) {
3339 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
3340 meshlink_errno = MESHLINK_ENETWORK;
3344 // Check if the hash of the key he gave us matches the hash in the URL.
3345 char *fingerprint = state.line + 2;
3348 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
3349 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
3350 meshlink_errno = MESHLINK_EINTERNAL;
3354 if(memcmp(hishash, state.hash, 18)) {
3355 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
3356 meshlink_errno = MESHLINK_EPEER;
3360 hiskey = ecdsa_set_base64_public_key(fingerprint);
3363 meshlink_errno = MESHLINK_EINTERNAL;
3367 // Start an SPTPS session
3368 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
3369 meshlink_errno = MESHLINK_EINTERNAL;
3373 // Feed rest of input buffer to SPTPS
3374 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
3375 meshlink_errno = MESHLINK_EPEER;
3380 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
3382 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
3384 if(errno == EINTR) {
3388 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
3389 meshlink_errno = MESHLINK_ENETWORK;
3393 if(!sptps_receive_data(&state.sptps, state.line, len)) {
3394 meshlink_errno = MESHLINK_EPEER;
3399 if(!state.success) {
3400 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
3401 meshlink_errno = MESHLINK_EPEER;
3405 sptps_stop(&state.sptps);
3408 closesocket(state.sock);
3410 pthread_mutex_unlock(&mesh->mutex);
3414 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
3415 meshlink_errno = MESHLINK_EINVAL;
3417 sptps_stop(&state.sptps);
3421 if(state.sock != -1) {
3422 closesocket(state.sock);
3425 pthread_mutex_unlock(&mesh->mutex);
3429 char *meshlink_export(meshlink_handle_t *mesh) {
3431 meshlink_errno = MESHLINK_EINVAL;
3435 // Create a config file on the fly.
3438 packmsg_output_t out = {buf, sizeof(buf)};
3439 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
3440 packmsg_add_str(&out, mesh->name);
3441 packmsg_add_str(&out, CORE_MESH);
3443 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3447 packmsg_add_int32(&out, mesh->self->devclass);
3448 packmsg_add_bool(&out, mesh->self->status.blacklisted);
3449 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
3451 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
3452 char *canonical_address = NULL;
3453 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
3454 packmsg_add_str(&out, canonical_address);
3455 free(canonical_address);
3457 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3462 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3463 if(mesh->self->recent[i].sa.sa_family) {
3470 packmsg_add_array(&out, count);
3472 for(uint32_t i = 0; i < count; i++) {
3473 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3476 packmsg_add_int64(&out, 0);
3477 packmsg_add_int64(&out, 0);
3479 pthread_mutex_unlock(&mesh->mutex);
3481 if(!packmsg_output_ok(&out)) {
3482 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
3483 meshlink_errno = MESHLINK_EINTERNAL;
3487 // Prepare a base64-encoded packmsg array containing our config file
3489 uint32_t len = packmsg_output_size(&out, buf);
3490 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3491 uint8_t *buf2 = xmalloc(len2);
3492 packmsg_output_t out2 = {buf2, len2};
3493 packmsg_add_array(&out2, 1);
3494 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3496 if(!packmsg_output_ok(&out2)) {
3497 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
3498 meshlink_errno = MESHLINK_EINTERNAL;
3503 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3505 return (char *)buf2;
3508 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3509 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
3511 if(!mesh || !data) {
3512 meshlink_errno = MESHLINK_EINVAL;
3516 size_t datalen = strlen(data);
3517 uint8_t *buf = xmalloc(datalen);
3518 int buflen = b64decode(data, buf, datalen);
3521 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3523 meshlink_errno = MESHLINK_EPEER;
3527 packmsg_input_t in = {buf, buflen};
3528 uint32_t count = packmsg_get_array(&in);
3531 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3533 meshlink_errno = MESHLINK_EPEER;
3537 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3543 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
3549 packmsg_input_t in2 = {data2, len2};
3550 uint32_t version = packmsg_get_uint32(&in2);
3551 char *name = packmsg_get_str_dup(&in2);
3553 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3555 packmsg_input_invalidate(&in);
3559 if(!check_id(name)) {
3564 node_t *n = lookup_node(mesh, name);
3567 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3575 config_t config = {data2, len2};
3577 if(!node_read_from_config(mesh, n, &config)) {
3579 packmsg_input_invalidate(&in);
3583 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3584 n->last_reachable = 0;
3585 n->last_unreachable = 0;
3587 if(!node_write_config(mesh, n, true)) {
3596 pthread_mutex_unlock(&mesh->mutex);
3600 if(!packmsg_done(&in)) {
3601 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3602 meshlink_errno = MESHLINK_EPEER;
3606 if(!config_sync(mesh, "current")) {
3613 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3614 if(n == mesh->self) {
3615 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3616 meshlink_errno = MESHLINK_EINVAL;
3620 if(n->status.blacklisted) {
3621 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3625 n->status.blacklisted = true;
3627 /* Immediately shut down any connections we have with the blacklisted node.
3628 * We can't call terminate_connection(), because we might be called from a callback function.
3630 for list_each(connection_t, c, mesh->connections) {
3632 if(c->status.active) {
3633 send_error(mesh, c, BLACKLISTED, "blacklisted");
3636 shutdown(c->socket, SHUT_RDWR);
3640 utcp_reset_all_connections(n->utcp);
3646 n->status.udp_confirmed = false;
3648 if(n->status.reachable) {
3649 n->last_unreachable = time(NULL);
3652 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3653 * manually call the status callback if necessary.
3655 if(n->status.reachable && mesh->node_status_cb) {
3656 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3659 /* Remove any outstanding invitations */
3660 invitation_purge_node(mesh, n->name);
3662 return node_write_config(mesh, n, true) && config_sync(mesh, "current");
3665 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3666 logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist(%s)", node ? node->name : "(null)");
3668 if(!mesh || !node) {
3669 meshlink_errno = MESHLINK_EINVAL;
3673 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3677 if(!blacklist(mesh, (node_t *)node)) {
3678 pthread_mutex_unlock(&mesh->mutex);
3682 pthread_mutex_unlock(&mesh->mutex);
3684 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3688 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3689 logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist_by_name(%s)", name ? name : "(null)");
3691 if(!mesh || !name) {
3692 meshlink_errno = MESHLINK_EINVAL;
3696 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3700 node_t *n = lookup_node(mesh, (char *)name);
3704 n->name = xstrdup(name);
3708 if(!blacklist(mesh, (node_t *)n)) {
3709 pthread_mutex_unlock(&mesh->mutex);
3713 pthread_mutex_unlock(&mesh->mutex);
3715 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3719 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3720 if(n == mesh->self) {
3721 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3722 meshlink_errno = MESHLINK_EINVAL;
3726 if(!n->status.blacklisted) {
3727 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3731 n->status.blacklisted = false;
3733 if(n->status.reachable) {
3734 n->last_reachable = time(NULL);
3735 update_node_status(mesh, n);
3738 return node_write_config(mesh, n, true) && config_sync(mesh, "current");
3741 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3742 logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist(%s)", node ? node->name : "(null)");
3744 if(!mesh || !node) {
3745 meshlink_errno = MESHLINK_EINVAL;
3749 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3753 if(!whitelist(mesh, (node_t *)node)) {
3754 pthread_mutex_unlock(&mesh->mutex);
3758 pthread_mutex_unlock(&mesh->mutex);
3760 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3764 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3765 logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist_by_name(%s)", name ? name : "(null)");
3767 if(!mesh || !name) {
3768 meshlink_errno = MESHLINK_EINVAL;
3772 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3776 node_t *n = lookup_node(mesh, (char *)name);
3780 n->name = xstrdup(name);
3784 if(!whitelist(mesh, (node_t *)n)) {
3785 pthread_mutex_unlock(&mesh->mutex);
3789 pthread_mutex_unlock(&mesh->mutex);
3791 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3795 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3796 mesh->default_blacklist = blacklist;
3799 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3800 logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
3802 if(!mesh || !node) {
3803 meshlink_errno = MESHLINK_EINVAL;
3807 node_t *n = (node_t *)node;
3809 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3813 /* Check that the node is not reachable */
3814 if(n->status.reachable || n->connection) {
3815 pthread_mutex_unlock(&mesh->mutex);
3816 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3820 /* Check that we don't have any active UTCP connections */
3821 if(n->utcp && utcp_is_active(n->utcp)) {
3822 pthread_mutex_unlock(&mesh->mutex);
3823 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3827 /* Check that we have no active connections to this node */
3828 for list_each(connection_t, c, mesh->connections) {
3830 pthread_mutex_unlock(&mesh->mutex);
3831 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3836 /* Remove any pending outgoings to this node */
3837 if(mesh->outgoings) {
3838 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3839 if(outgoing->node == n) {
3840 list_delete_node(mesh->outgoings, list_node);
3845 /* Delete the config file for this node */
3846 if(!config_delete(mesh, "current", n->name)) {
3847 pthread_mutex_unlock(&mesh->mutex);
3851 /* Delete any pending invitations */
3852 invitation_purge_node(mesh, n->name);
3854 /* Delete the node struct and any remaining edges referencing this node */
3857 pthread_mutex_unlock(&mesh->mutex);
3859 return config_sync(mesh, "current");
3862 /* Hint that a hostname may be found at an address
3863 * See header file for detailed comment.
3865 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3866 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
3868 if(!mesh || !node || !addr) {
3869 meshlink_errno = EINVAL;
3873 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3877 node_t *n = (node_t *)node;
3879 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3880 if(!node_write_config(mesh, n, false)) {
3881 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3885 pthread_mutex_unlock(&mesh->mutex);
3886 // @TODO do we want to fire off a connection attempt right away?
3889 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3891 node_t *n = utcp->priv;
3892 meshlink_handle_t *mesh = n->mesh;
3894 if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
3895 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
3897 return mesh->channel_accept_cb;
3901 /* Finish one AIO buffer, return true if the channel is still open. */
3902 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3903 meshlink_aio_buffer_t *aio = *head;
3907 channel->in_callback = true;
3910 if(aio->cb.buffer) {
3911 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
3915 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3919 channel->in_callback = false;
3932 /* Finish all AIO buffers, return true if the channel is still open. */
3933 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3935 if(!aio_finish_one(mesh, channel, head)) {
3943 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3944 meshlink_channel_t *channel = connection->priv;
3950 node_t *n = channel->node;
3951 meshlink_handle_t *mesh = n->mesh;
3953 if(n->status.destroyed) {
3954 meshlink_channel_close(mesh, channel);
3958 const char *p = data;
3961 while(channel->aio_receive) {
3963 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
3964 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
3971 meshlink_aio_buffer_t *aio = channel->aio_receive;
3972 size_t todo = aio->len - aio->done;
3979 memcpy((char *)aio->data + aio->done, p, todo);
3981 ssize_t result = write(aio->fd, p, todo);
3984 if(result < 0 && errno == EINTR) {
3988 /* Writing to fd failed, cancel just this AIO buffer. */
3989 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
3991 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
4005 if(aio->done == aio->len) {
4006 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
4016 if(channel->receive_cb) {
4017 channel->receive_cb(mesh, channel, p, left);
4023 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
4024 node_t *n = utcp_connection->utcp->priv;
4030 meshlink_handle_t *mesh = n->mesh;
4032 if(!mesh->channel_accept_cb) {
4036 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
4038 channel->c = utcp_connection;
4040 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
4041 utcp_accept(utcp_connection, channel_recv, channel);
4047 static void channel_retransmit(struct utcp_connection *utcp_connection) {
4048 node_t *n = utcp_connection->utcp->priv;
4049 meshlink_handle_t *mesh = n->mesh;
4051 if(n->mtuprobes == 31 && n->mtutimeout.cb) {
4052 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
4058 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
4059 node_t *n = utcp->priv;
4061 if(n->status.destroyed) {
4065 meshlink_handle_t *mesh = n->mesh;
4066 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
4069 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
4070 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
4072 if(!mesh || !channel) {
4073 meshlink_errno = MESHLINK_EINVAL;
4077 channel->receive_cb = cb;
4080 void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
4082 node_t *n = (node_t *)source;
4088 utcp_recv(n->utcp, data, len);
4091 static void channel_poll(struct utcp_connection *connection, size_t len) {
4092 meshlink_channel_t *channel = connection->priv;
4098 node_t *n = channel->node;
4099 meshlink_handle_t *mesh = n->mesh;
4101 while(channel->aio_send) {
4103 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
4104 if(!aio_abort(mesh, channel, &channel->aio_send)) {
4111 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
4112 meshlink_aio_buffer_t *aio = channel->aio_send;
4113 size_t todo = aio->len - aio->done;
4121 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
4123 /* Limit the amount we read at once to avoid stack overflows */
4129 ssize_t result = read(aio->fd, buf, todo);
4133 sent = utcp_send(connection, buf, todo);
4135 if(result < 0 && errno == EINTR) {
4139 /* Reading from fd failed, cancel just this AIO buffer. */
4141 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
4144 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
4152 if(sent != (ssize_t)todo) {
4153 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
4154 if(!aio_abort(mesh, channel, &channel->aio_send)) {
4165 /* If we didn't finish this buffer, exit early. */
4166 if(aio->done < aio->len) {
4170 /* Signal completion of this buffer, and go to the next one. */
4171 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
4180 if(channel->poll_cb) {
4181 channel->poll_cb(mesh, channel, len);
4183 utcp_set_poll_cb(connection, NULL);
4187 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
4188 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
4190 if(!mesh || !channel) {
4191 meshlink_errno = MESHLINK_EINVAL;
4195 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4199 channel->poll_cb = cb;
4200 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
4201 pthread_mutex_unlock(&mesh->mutex);
4204 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
4205 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
4208 meshlink_errno = MESHLINK_EINVAL;
4212 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4216 mesh->channel_listen_cb = cb;
4218 pthread_mutex_unlock(&mesh->mutex);
4221 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
4222 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
4225 meshlink_errno = MESHLINK_EINVAL;
4229 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4233 mesh->channel_accept_cb = cb;
4235 for splay_each(node_t, n, mesh->nodes) {
4236 if(!n->utcp && n != mesh->self) {
4237 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4238 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4239 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4243 pthread_mutex_unlock(&mesh->mutex);
4246 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
4247 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
4249 meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
4252 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
4253 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
4255 meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
4258 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
4259 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
4261 if(!mesh || !channel) {
4262 meshlink_errno = MESHLINK_EINVAL;
4266 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4270 utcp_set_sndbuf(channel->c, buf, size);
4271 pthread_mutex_unlock(&mesh->mutex);
4274 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
4275 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
4277 if(!mesh || !channel) {
4278 meshlink_errno = MESHLINK_EINVAL;
4282 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4286 utcp_set_rcvbuf(channel->c, buf, size);
4287 pthread_mutex_unlock(&mesh->mutex);
4290 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
4291 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
4293 if(!mesh || !channel) {
4294 meshlink_errno = MESHLINK_EINVAL;
4298 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4302 utcp_set_flags(channel->c, flags);
4303 pthread_mutex_unlock(&mesh->mutex);
4306 meshlink_channel_t *meshlink_channel_open_ex(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len, uint32_t flags) {
4307 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu, %u)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len, flags);
4310 abort(); // TODO: handle non-NULL data
4313 if(!mesh || !node) {
4314 meshlink_errno = MESHLINK_EINVAL;
4318 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4322 node_t *n = (node_t *)node;
4325 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4326 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4327 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4330 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
4331 pthread_mutex_unlock(&mesh->mutex);
4336 if(n->status.blacklisted) {
4337 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
4338 meshlink_errno = MESHLINK_EBLACKLISTED;
4339 pthread_mutex_unlock(&mesh->mutex);
4343 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
4345 channel->receive_cb = cb;
4348 channel->priv = (void *)data;
4351 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
4353 pthread_mutex_unlock(&mesh->mutex);
4356 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
4364 meshlink_channel_t *meshlink_channel_open(meshlink_handle_t *mesh, meshlink_node_t *node, uint16_t port, meshlink_channel_receive_cb_t cb, const void *data, size_t len) {
4365 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
4367 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
4370 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
4371 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
4373 if(!mesh || !channel) {
4374 meshlink_errno = MESHLINK_EINVAL;
4378 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4382 utcp_shutdown(channel->c, direction);
4383 pthread_mutex_unlock(&mesh->mutex);
4386 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4387 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
4389 if(!mesh || !channel) {
4390 meshlink_errno = MESHLINK_EINVAL;
4394 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4399 utcp_close(channel->c);
4402 /* Clean up any outstanding AIO buffers. */
4403 aio_abort(mesh, channel, &channel->aio_send);
4404 aio_abort(mesh, channel, &channel->aio_receive);
4407 if(!channel->in_callback) {
4411 pthread_mutex_unlock(&mesh->mutex);
4414 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4415 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
4417 if(!mesh || !channel) {
4418 meshlink_errno = MESHLINK_EINVAL;
4422 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4427 utcp_abort(channel->c);
4430 /* Clean up any outstanding AIO buffers. */
4431 aio_abort(mesh, channel, &channel->aio_send);
4432 aio_abort(mesh, channel, &channel->aio_receive);
4435 if(!channel->in_callback) {
4439 pthread_mutex_unlock(&mesh->mutex);
4442 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
4443 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
4445 if(!mesh || !channel) {
4446 meshlink_errno = MESHLINK_EINVAL;
4455 meshlink_errno = MESHLINK_EINVAL;
4459 // TODO: more finegrained locking.
4460 // Ideally we want to put the data into the UTCP connection's send buffer.
4461 // Then, preferably only if there is room in the receiver window,
4462 // kick the meshlink thread to go send packets.
4466 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4470 /* Disallow direct calls to utcp_send() while we still have AIO active. */
4471 if(channel->aio_send) {
4474 retval = utcp_send(channel->c, data, len);
4477 pthread_mutex_unlock(&mesh->mutex);
4480 meshlink_errno = MESHLINK_ENETWORK;
4486 bool meshlink_channel_aio_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
4487 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
4489 if(!mesh || !channel) {
4490 meshlink_errno = MESHLINK_EINVAL;
4495 meshlink_errno = MESHLINK_EINVAL;
4499 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4502 aio->cb.buffer = cb;
4505 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4509 /* Append the AIO buffer descriptor to the end of the chain */
4510 meshlink_aio_buffer_t **p = &channel->aio_send;
4518 /* Ensure the poll callback is set, and call it right now to push data if possible */
4519 utcp_set_poll_cb(channel->c, channel_poll);
4520 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
4523 channel_poll(channel->c, todo);
4526 pthread_mutex_unlock(&mesh->mutex);
4531 bool meshlink_channel_aio_fd_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
4532 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
4534 if(!mesh || !channel) {
4535 meshlink_errno = MESHLINK_EINVAL;
4539 if(!len || fd == -1) {
4540 meshlink_errno = MESHLINK_EINVAL;
4544 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4550 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4554 /* Append the AIO buffer descriptor to the end of the chain */
4555 meshlink_aio_buffer_t **p = &channel->aio_send;
4563 /* Ensure the poll callback is set, and call it right now to push data if possible */
4564 utcp_set_poll_cb(channel->c, channel_poll);
4565 size_t left = utcp_get_rcvbuf_free(channel->c);
4568 channel_poll(channel->c, left);
4571 pthread_mutex_unlock(&mesh->mutex);
4576 bool meshlink_channel_aio_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
4577 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
4579 if(!mesh || !channel) {
4580 meshlink_errno = MESHLINK_EINVAL;
4585 meshlink_errno = MESHLINK_EINVAL;
4589 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4592 aio->cb.buffer = cb;
4595 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4599 /* Append the AIO buffer descriptor to the end of the chain */
4600 meshlink_aio_buffer_t **p = &channel->aio_receive;
4608 pthread_mutex_unlock(&mesh->mutex);
4613 bool meshlink_channel_aio_fd_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, int fd, size_t len, meshlink_aio_fd_cb_t cb, void *priv) {
4614 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
4616 if(!mesh || !channel) {
4617 meshlink_errno = MESHLINK_EINVAL;
4621 if(!len || fd == -1) {
4622 meshlink_errno = MESHLINK_EINVAL;
4626 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4632 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4636 /* Append the AIO buffer descriptor to the end of the chain */
4637 meshlink_aio_buffer_t **p = &channel->aio_receive;
4645 pthread_mutex_unlock(&mesh->mutex);
4650 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4651 if(!mesh || !channel) {
4652 meshlink_errno = MESHLINK_EINVAL;
4656 return channel->c->flags;
4659 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4660 if(!mesh || !channel) {
4661 meshlink_errno = MESHLINK_EINVAL;
4665 return utcp_get_sendq(channel->c);
4668 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4669 if(!mesh || !channel) {
4670 meshlink_errno = MESHLINK_EINVAL;
4674 return utcp_get_recvq(channel->c);
4677 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4678 if(!mesh || !channel) {
4679 meshlink_errno = MESHLINK_EINVAL;
4683 return utcp_get_mss(channel->node->utcp);
4686 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
4687 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
4689 if(!mesh || !node) {
4690 meshlink_errno = MESHLINK_EINVAL;
4694 node_t *n = (node_t *)node;
4696 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4701 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4702 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4703 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4706 utcp_set_user_timeout(n->utcp, timeout);
4708 pthread_mutex_unlock(&mesh->mutex);
4711 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4712 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4713 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4714 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4715 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4718 if(mesh->node_status_cb) {
4719 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4722 if(mesh->node_pmtu_cb) {
4723 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4727 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4728 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4730 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4731 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4735 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4736 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4740 n->status.duplicate = true;
4741 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4744 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4745 logger(mesh, MESHLINK_DEBUG, "meshlink_enable_discovery(%d)", enable);
4748 meshlink_errno = MESHLINK_EINVAL;
4752 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4756 if(mesh->discovery.enabled == enable) {
4760 if(mesh->threadstarted) {
4762 discovery_start(mesh);
4764 discovery_stop(mesh);
4768 mesh->discovery.enabled = enable;
4771 pthread_mutex_unlock(&mesh->mutex);
4774 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
4775 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
4778 meshlink_errno = MESHLINK_EINVAL;
4782 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4786 if(mesh->discovery.enabled) {
4790 if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
4791 mesh->discovery.last_update = mesh->loop.now.tv_sec;
4792 handle_network_change(mesh, 1);
4795 pthread_mutex_unlock(&mesh->mutex);
4798 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4799 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
4801 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4802 meshlink_errno = EINVAL;
4806 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4807 meshlink_errno = EINVAL;
4811 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4815 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4816 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4817 pthread_mutex_unlock(&mesh->mutex);
4820 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4821 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
4823 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4824 meshlink_errno = EINVAL;
4828 if(fast_retry_period < 0) {
4829 meshlink_errno = EINVAL;
4833 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4837 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4838 pthread_mutex_unlock(&mesh->mutex);
4841 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
4842 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
4844 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4845 meshlink_errno = EINVAL;
4849 if(maxtimeout < 0) {
4850 meshlink_errno = EINVAL;
4854 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4858 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
4859 pthread_mutex_unlock(&mesh->mutex);
4862 void meshlink_reset_timers(struct meshlink_handle *mesh) {
4863 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
4869 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4873 handle_network_change(mesh, true);
4875 if(mesh->discovery.enabled) {
4876 discovery_refresh(mesh);
4879 pthread_mutex_unlock(&mesh->mutex);
4882 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4883 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
4886 meshlink_errno = EINVAL;
4890 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4894 mesh->inviter_commits_first = inviter_commits_first;
4895 pthread_mutex_unlock(&mesh->mutex);
4898 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4899 logger(mesh, MESHLINK_DEBUG, "meshlink_set_external_address_discovery_url(%s)", url ? url : "(null)");
4902 meshlink_errno = EINVAL;
4906 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4907 meshlink_errno = EINVAL;
4911 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4915 free(mesh->external_address_url);
4916 mesh->external_address_url = url ? xstrdup(url) : NULL;
4917 pthread_mutex_unlock(&mesh->mutex);
4920 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4921 logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
4923 if(!mesh || granularity < 0) {
4924 meshlink_errno = EINVAL;
4928 utcp_set_clock_granularity(granularity);
4931 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
4932 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
4935 meshlink_errno = EINVAL;
4939 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4943 mesh->storage_policy = policy;
4944 pthread_mutex_unlock(&mesh->mutex);
4947 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4950 if(!mesh->connections || !mesh->loop.running) {
4955 signal_trigger(&mesh->loop, &mesh->datafromapp);
4958 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
4959 // We should only call the callback function if we are in the background thread.
4960 if(!mesh->error_cb) {
4964 if(!mesh->threadstarted) {
4968 if(mesh->thread == pthread_self()) {
4969 mesh->error_cb(mesh, cb_errno);
4973 static void __attribute__((constructor)) meshlink_init(void) {
4975 utcp_set_clock_granularity(10000);
4978 static void __attribute__((destructor)) meshlink_exit(void) {