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"
40 #include "ed25519/sha512.h"
41 #include "discovery.h"
46 #define MSG_NOSIGNAL 0
48 __thread meshlink_errno_t meshlink_errno;
49 meshlink_log_cb_t global_log_cb;
50 meshlink_log_level_t global_log_level;
52 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
54 static int rstrip(char *value) {
55 int len = strlen(value);
57 while(len && strchr("\t\r\n ", value[len - 1])) {
64 static void get_canonical_address(node_t *n, char **hostname, char **port) {
65 if(!n->canonical_address) {
69 *hostname = xstrdup(n->canonical_address);
70 char *space = strchr(*hostname, ' ');
74 *port = xstrdup(space);
78 static bool is_valid_hostname(const char *hostname) {
83 for(const char *p = hostname; *p; p++) {
84 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
92 static bool is_valid_port(const char *port) {
99 unsigned long int result = strtoul(port, &end, 10);
100 return result && result < 65536 && !*end;
103 for(const char *p = port; *p; p++) {
104 if(!(isalnum(*p) || *p == '-')) {
112 static void set_timeout(int sock, int timeout) {
117 tv.tv_sec = timeout / 1000;
118 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
120 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
121 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
124 struct socket_in_netns_params {
133 static void *socket_in_netns_thread(void *arg) {
134 struct socket_in_netns_params *params = arg;
136 if(setns(params->netns, CLONE_NEWNET) == -1) {
137 meshlink_errno = MESHLINK_EINVAL;
141 params->fd = socket(params->domain, params->type, params->protocol);
147 static int socket_in_netns(int domain, int type, int protocol, int netns) {
149 return socket(domain, type, protocol);
153 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
157 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
158 if(pthread_join(thr, NULL) != 0) {
170 // Find out what local address a socket would use if we connect to the given address.
171 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
172 // of both endpoints, but this will actually not send any UDP packet.
173 static bool getlocaladdr(const char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
174 struct addrinfo *rai = NULL;
175 const struct addrinfo hint = {
176 .ai_family = AF_UNSPEC,
177 .ai_socktype = SOCK_DGRAM,
178 .ai_protocol = IPPROTO_UDP,
179 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
182 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
186 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
193 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
201 if(getsockname(sock, &sa->sa, salen)) {
210 static bool getlocaladdrname(const char *destaddr, char *host, socklen_t hostlen, int netns) {
212 socklen_t salen = sizeof(sa);
214 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
218 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
225 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
226 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
229 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
230 logger(mesh, MESHLINK_DEBUG, "meshlink_get_external_address_for_family(%d)", family);
231 const char *url = mesh->external_address_url;
234 url = "http://meshlink.io/host.cgi";
237 /* Find the hostname part between the slashes */
238 if(strncmp(url, "http://", 7)) {
240 meshlink_errno = MESHLINK_EINTERNAL;
244 const char *begin = url + 7;
246 const char *end = strchr(begin, '/');
249 end = begin + strlen(begin);
253 char host[end - begin + 1];
254 strncpy(host, begin, end - begin);
255 host[end - begin] = 0;
257 char *port = strchr(host, ':');
263 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
264 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(host), xstrdup(port ? port : "80"), SOCK_STREAM, 5);
266 char *hostname = NULL;
268 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
269 if(family != AF_UNSPEC && aip->ai_family != family) {
273 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
277 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
281 set_timeout(s, 5000);
283 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
290 send(s, "GET ", 4, 0);
291 send(s, url, strlen(url), 0);
292 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
293 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
298 if(line[len - 1] == '\n') {
302 char *p = strrchr(line, '\n');
305 hostname = xstrdup(p + 1);
321 // Check that the hostname is reasonable
322 if(hostname && !is_valid_hostname(hostname)) {
328 meshlink_errno = MESHLINK_ERESOLV;
334 static bool is_localaddr(sockaddr_t *sa) {
335 switch(sa->sa.sa_family) {
337 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
340 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
341 return first == 0 || (first & 0xffc0) == 0xfe80;
349 #ifdef HAVE_GETIFADDRS
350 struct getifaddrs_in_netns_params {
351 struct ifaddrs **ifa;
356 static void *getifaddrs_in_netns_thread(void *arg) {
357 struct getifaddrs_in_netns_params *params = arg;
359 if(setns(params->netns, CLONE_NEWNET) == -1) {
360 meshlink_errno = MESHLINK_EINVAL;
364 if(getifaddrs(params->ifa) != 0) {
372 static int getifaddrs_in_netns(struct ifaddrs **ifa, int netns) {
374 return getifaddrs(ifa);
378 struct getifaddrs_in_netns_params params = {ifa, netns};
381 if(pthread_create(&thr, NULL, getifaddrs_in_netns_thread, ¶ms) == 0) {
382 if(pthread_join(thr, NULL) != 0) {
387 return *params.ifa ? 0 : -1;
395 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
396 logger(mesh, MESHLINK_DEBUG, "meshlink_get_local_address_for_family(%d)", family);
399 meshlink_errno = MESHLINK_EINVAL;
403 // Determine address of the local interface used for outgoing connections.
404 char localaddr[NI_MAXHOST];
405 bool success = false;
407 if(family == AF_INET) {
408 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
409 } else if(family == AF_INET6) {
410 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
413 #ifdef HAVE_GETIFADDRS
416 struct ifaddrs *ifa = NULL;
417 getifaddrs_in_netns(&ifa, mesh->netns);
419 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
420 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
422 if(!sa || sa->sa.sa_family != family) {
426 if(is_localaddr(sa)) {
430 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
442 meshlink_errno = MESHLINK_ENETWORK;
446 return xstrdup(localaddr);
449 static void remove_duplicate_hostnames(char *host[], char *port[], int n) {
450 for(int i = 0; i < n; i++) {
455 // Ignore duplicate hostnames
458 for(int j = 0; j < i; j++) {
463 if(strcmp(host[i], host[j])) {
467 if(strcmp(port[i], port[j])) {
475 if(found || !is_valid_hostname(host[i])) {
485 // This gets the hostname part for use in invitation URLs
486 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
487 int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
489 char *hostname[count];
491 char *hostport = NULL;
493 memset(hostname, 0, sizeof(hostname));
494 memset(port, 0, sizeof(port));
496 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
497 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
500 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
501 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
504 // Add all explicitly set invitation addresses
505 if(mesh->invitation_addresses) {
506 for list_each(char, combo, mesh->invitation_addresses) {
507 hostname[n] = xstrdup(combo);
508 char *slash = strrchr(hostname[n], '/');
512 port[n] = xstrdup(slash + 1);
519 // Add local addresses if requested
520 if(flags & MESHLINK_INVITE_LOCAL) {
521 if(flags & MESHLINK_INVITE_IPV4) {
522 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
525 if(flags & MESHLINK_INVITE_IPV6) {
526 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
530 // Add public/canonical addresses if requested
531 if(flags & MESHLINK_INVITE_PUBLIC) {
532 // Try the CanonicalAddress first
533 get_canonical_address(mesh->self, &hostname[n], &port[n]);
535 if(!hostname[n] && count == 4) {
536 if(flags & MESHLINK_INVITE_IPV4) {
537 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
540 if(flags & MESHLINK_INVITE_IPV6) {
541 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
548 for(int i = 0; i < n; i++) {
549 // Ensure we always have a port number
550 if(hostname[i] && !port[i]) {
551 port[i] = xstrdup(mesh->myport);
555 remove_duplicate_hostnames(hostname, port, n);
557 // Resolve the hostnames
558 for(int i = 0; i < n; i++) {
563 // Convert what we have to a sockaddr
564 struct addrinfo *ai_in = adns_blocking_request(mesh, xstrdup(hostname[i]), xstrdup(port[i]), SOCK_STREAM, 5);
570 // Remember the address(es)
571 for(struct addrinfo *aip = ai_in; aip; aip = aip->ai_next) {
572 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)aip->ai_addr);
579 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
580 remove_duplicate_hostnames(hostname, port, n);
582 // Concatenate all unique address to the hostport string
583 for(int i = 0; i < n; i++) {
588 // Append the address to the hostport string
590 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
592 hostport = newhostport;
601 static bool try_bind(meshlink_handle_t *mesh, int port) {
602 struct addrinfo *ai = NULL;
603 struct addrinfo hint = {
604 .ai_flags = AI_PASSIVE,
605 .ai_family = AF_UNSPEC,
606 .ai_socktype = SOCK_STREAM,
607 .ai_protocol = IPPROTO_TCP,
611 snprintf(portstr, sizeof(portstr), "%d", port);
613 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
617 bool success = false;
619 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
620 /* Try to bind to TCP. */
622 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
625 if(errno == EADDRINUSE) {
626 /* If this port is in use for any address family, avoid it. */
634 /* If TCP worked, then we require that UDP works as well. */
636 int udp_fd = setup_udp_listen_socket(mesh, aip);
653 int check_port(meshlink_handle_t *mesh) {
654 for(int i = 0; i < 1000; i++) {
655 int port = 0x1000 + prng(mesh, 0x8000);
657 if(try_bind(mesh, port)) {
659 xasprintf(&mesh->myport, "%d", port);
664 meshlink_errno = MESHLINK_ENETWORK;
665 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
669 static bool write_main_config_files(meshlink_handle_t *mesh) {
670 if(!mesh->confbase) {
676 /* Write the main config file */
677 packmsg_output_t out = {buf, sizeof buf};
679 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
680 packmsg_add_str(&out, mesh->name);
681 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
682 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
683 packmsg_add_uint16(&out, atoi(mesh->myport));
685 if(!packmsg_output_ok(&out)) {
689 config_t config = {buf, packmsg_output_size(&out, buf)};
691 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
695 /* Write our own host config file */
696 if(!node_write_config(mesh, mesh->self, true)) {
704 meshlink_handle_t *mesh;
706 char cookie[18 + 32];
717 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
718 meshlink_handle_t *mesh = state->mesh;
719 packmsg_input_t in = {buf, len};
720 uint32_t version = packmsg_get_uint32(&in);
722 if(version != MESHLINK_INVITATION_VERSION) {
723 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
727 char *name = packmsg_get_str_dup(&in);
728 char *submesh_name = packmsg_get_str_dup(&in);
729 dev_class_t devclass = packmsg_get_int32(&in);
730 uint32_t count = packmsg_get_array(&in);
732 if(!name || !check_id(name)) {
733 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
739 if(!submesh_name || (strcmp(submesh_name, CORE_MESH) && !check_id(submesh_name))) {
740 logger(mesh, MESHLINK_DEBUG, "No valid Submesh found in invitation!\n");
747 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
754 free(mesh->self->name);
756 mesh->self->name = xstrdup(name);
757 mesh->self->submesh = strcmp(submesh_name, CORE_MESH) ? lookup_or_create_submesh(mesh, submesh_name) : NULL;
759 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
761 // Initialize configuration directory
762 if(!config_init(mesh, "current")) {
766 if(!write_main_config_files(mesh)) {
770 // Write host config files
771 for(uint32_t i = 0; i < count; i++) {
773 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
776 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
780 packmsg_input_t in2 = {data, data_len};
781 uint32_t version2 = packmsg_get_uint32(&in2);
782 char *name2 = packmsg_get_str_dup(&in2);
784 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
786 packmsg_input_invalidate(&in);
790 if(!check_id(name2)) {
795 if(!strcmp(name2, mesh->name)) {
796 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
798 meshlink_errno = MESHLINK_EPEER;
802 node_t *n = new_node();
805 config_t config = {data, data_len};
807 if(!node_read_from_config(mesh, n, &config)) {
809 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
810 meshlink_errno = MESHLINK_EPEER;
815 /* The first host config file is of the inviter itself;
816 * remember the address we are currently using for the invitation connection.
819 socklen_t salen = sizeof(sa);
821 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
822 node_add_recent_address(mesh, n, &sa);
826 /* Clear the reachability times, since we ourself have never seen these nodes yet */
827 n->last_reachable = 0;
828 n->last_unreachable = 0;
830 if(!node_write_config(mesh, n, true)) {
838 /* Ensure the configuration directory metadata is on disk */
839 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
843 if(!mesh->inviter_commits_first) {
844 devtool_set_inviter_commits_first(false);
847 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
849 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
854 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
856 join_state_t *state = handle;
857 const char *ptr = data;
860 int result = send(state->sock, ptr, len, 0);
862 if(result == -1 && errno == EINTR) {
864 } else if(result <= 0) {
875 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
876 join_state_t *state = handle;
877 meshlink_handle_t *mesh = state->mesh;
879 if(mesh->inviter_commits_first) {
881 case SPTPS_HANDSHAKE:
882 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
888 if(!finalize_join(state, msg, len)) {
892 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
893 shutdown(state->sock, SHUT_RDWR);
894 state->success = true;
902 case SPTPS_HANDSHAKE:
903 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
906 return finalize_join(state, msg, len);
909 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
910 shutdown(state->sock, SHUT_RDWR);
911 state->success = true;
922 static bool recvline(join_state_t *state) {
923 char *newline = NULL;
925 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
926 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
928 if(result == -1 && errno == EINTR) {
930 } else if(result <= 0) {
934 state->blen += result;
937 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
941 size_t len = newline - state->buffer;
943 memcpy(state->line, state->buffer, len);
944 state->line[len] = 0;
945 memmove(state->buffer, newline + 1, state->blen - len - 1);
946 state->blen -= len + 1;
951 static bool sendline(int fd, const char *format, ...) {
957 va_start(ap, format);
958 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
961 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
969 int result = send(fd, p, blen, MSG_NOSIGNAL);
971 if(result == -1 && errno == EINTR) {
973 } else if(result <= 0) {
984 static const char *errstr[] = {
985 [MESHLINK_OK] = "No error",
986 [MESHLINK_EINVAL] = "Invalid argument",
987 [MESHLINK_ENOMEM] = "Out of memory",
988 [MESHLINK_ENOENT] = "No such node",
989 [MESHLINK_EEXIST] = "Node already exists",
990 [MESHLINK_EINTERNAL] = "Internal error",
991 [MESHLINK_ERESOLV] = "Could not resolve hostname",
992 [MESHLINK_ESTORAGE] = "Storage error",
993 [MESHLINK_ENETWORK] = "Network error",
994 [MESHLINK_EPEER] = "Error communicating with peer",
995 [MESHLINK_ENOTSUP] = "Operation not supported",
996 [MESHLINK_EBUSY] = "MeshLink instance already in use",
997 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
1000 const char *meshlink_strerror(meshlink_errno_t err) {
1001 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
1002 return "Invalid error code";
1008 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
1009 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
1011 mesh->private_key = ecdsa_generate();
1012 mesh->invitation_key = ecdsa_generate();
1014 if(!mesh->private_key || !mesh->invitation_key) {
1015 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
1016 meshlink_errno = MESHLINK_EINTERNAL;
1020 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1025 static struct timespec idle(event_loop_t *loop, void *data) {
1027 meshlink_handle_t *mesh = data;
1028 struct timespec t, tmin = {3600, 0};
1030 for splay_each(node_t, n, mesh->nodes) {
1035 t = utcp_timeout(n->utcp);
1037 if(timespec_lt(&t, &tmin)) {
1045 // Get our local address(es) by simulating connecting to an Internet host.
1046 static void add_local_addresses(meshlink_handle_t *mesh) {
1048 sa.storage.ss_family = AF_UNKNOWN;
1049 socklen_t salen = sizeof(sa);
1053 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
1054 sa.in.sin_port = ntohs(atoi(mesh->myport));
1055 node_add_recent_address(mesh, mesh->self, &sa);
1062 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
1063 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
1064 node_add_recent_address(mesh, mesh->self, &sa);
1068 static bool meshlink_setup(meshlink_handle_t *mesh) {
1069 if(!config_destroy(mesh->confbase, "new")) {
1070 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1071 meshlink_errno = MESHLINK_ESTORAGE;
1075 if(!config_destroy(mesh->confbase, "old")) {
1076 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1077 meshlink_errno = MESHLINK_ESTORAGE;
1081 if(!config_init(mesh, "current")) {
1082 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1083 meshlink_errno = MESHLINK_ESTORAGE;
1087 if(!ecdsa_keygen(mesh)) {
1088 meshlink_errno = MESHLINK_EINTERNAL;
1092 if(check_port(mesh) == 0) {
1093 meshlink_errno = MESHLINK_ENETWORK;
1097 /* Create a node for ourself */
1099 mesh->self = new_node();
1100 mesh->self->name = xstrdup(mesh->name);
1101 mesh->self->devclass = mesh->devclass;
1102 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1103 mesh->self->session_id = mesh->session_id;
1105 if(!write_main_config_files(mesh)) {
1106 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1107 meshlink_errno = MESHLINK_ESTORAGE;
1111 /* Ensure the configuration directory metadata is on disk */
1112 if(!config_sync(mesh, "current")) {
1119 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1122 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1123 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1127 packmsg_input_t in = {config.buf, config.len};
1128 const void *private_key;
1129 const void *invitation_key;
1131 uint32_t version = packmsg_get_uint32(&in);
1132 char *name = packmsg_get_str_dup(&in);
1133 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1134 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1135 uint16_t myport = packmsg_get_uint16(&in);
1137 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1138 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1140 config_free(&config);
1144 if(mesh->name && strcmp(mesh->name, name)) {
1145 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1146 meshlink_errno = MESHLINK_ESTORAGE;
1148 config_free(&config);
1154 xasprintf(&mesh->myport, "%u", myport);
1155 mesh->private_key = ecdsa_set_private_key(private_key);
1156 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1157 config_free(&config);
1159 /* Create a node for ourself and read our host configuration file */
1161 mesh->self = new_node();
1162 mesh->self->name = xstrdup(name);
1163 mesh->self->devclass = mesh->devclass;
1164 mesh->self->session_id = mesh->session_id;
1166 if(!node_read_public_key(mesh, mesh->self)) {
1167 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1168 meshlink_errno = MESHLINK_ESTORAGE;
1169 free_node(mesh->self);
1178 static void *setup_network_in_netns_thread(void *arg) {
1179 meshlink_handle_t *mesh = arg;
1181 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1185 bool success = setup_network(mesh);
1186 return success ? arg : NULL;
1188 #endif // HAVE_SETNS
1190 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1191 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
1193 if(!confbase || !*confbase) {
1194 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1195 meshlink_errno = MESHLINK_EINVAL;
1199 if(!appname || !*appname) {
1200 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1201 meshlink_errno = MESHLINK_EINVAL;
1205 if(strchr(appname, ' ')) {
1206 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1207 meshlink_errno = MESHLINK_EINVAL;
1211 if(name && !check_id(name)) {
1212 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1213 meshlink_errno = MESHLINK_EINVAL;
1217 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1218 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1219 meshlink_errno = MESHLINK_EINVAL;
1223 meshlink_open_params_t *params = xzalloc(sizeof * params);
1225 params->confbase = xstrdup(confbase);
1226 params->name = name ? xstrdup(name) : NULL;
1227 params->appname = xstrdup(appname);
1228 params->devclass = devclass;
1231 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
1236 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1237 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
1240 meshlink_errno = MESHLINK_EINVAL;
1244 params->netns = netns;
1249 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1250 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
1253 meshlink_errno = MESHLINK_EINVAL;
1257 if((!key && keylen) || (key && !keylen)) {
1258 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1259 meshlink_errno = MESHLINK_EINVAL;
1264 params->keylen = keylen;
1269 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
1270 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
1273 meshlink_errno = MESHLINK_EINVAL;
1277 params->storage_policy = policy;
1282 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
1283 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
1285 if(!params || !filename) {
1286 meshlink_errno = MESHLINK_EINVAL;
1290 free(params->lock_filename);
1291 params->lock_filename = xstrdup(filename);
1296 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1297 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
1299 if(!mesh || !new_key || !new_keylen) {
1300 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1301 meshlink_errno = MESHLINK_EINVAL;
1305 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1309 // Create hash for the new key
1310 void *new_config_key;
1311 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1313 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1314 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1315 meshlink_errno = MESHLINK_EINTERNAL;
1316 pthread_mutex_unlock(&mesh->mutex);
1320 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1322 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1323 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1324 meshlink_errno = MESHLINK_ESTORAGE;
1325 pthread_mutex_unlock(&mesh->mutex);
1329 devtool_keyrotate_probe(1);
1331 // Rename confbase/current/ to confbase/old
1333 if(!config_rename(mesh, "current", "old")) {
1334 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1335 meshlink_errno = MESHLINK_ESTORAGE;
1336 pthread_mutex_unlock(&mesh->mutex);
1340 devtool_keyrotate_probe(2);
1342 // Rename confbase/new/ to confbase/current
1344 if(!config_rename(mesh, "new", "current")) {
1345 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1346 meshlink_errno = MESHLINK_ESTORAGE;
1347 pthread_mutex_unlock(&mesh->mutex);
1351 devtool_keyrotate_probe(3);
1353 // Cleanup the "old" confbase sub-directory
1355 if(!config_destroy(mesh->confbase, "old")) {
1356 pthread_mutex_unlock(&mesh->mutex);
1360 // Change the mesh handle key with new key
1362 free(mesh->config_key);
1363 mesh->config_key = new_config_key;
1365 pthread_mutex_unlock(&mesh->mutex);
1370 void meshlink_open_params_free(meshlink_open_params_t *params) {
1371 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
1374 meshlink_errno = MESHLINK_EINVAL;
1378 free(params->confbase);
1380 free(params->appname);
1381 free(params->lock_filename);
1386 /// Device class traits
1387 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1388 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1389 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1390 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1391 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1394 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1395 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
1397 if(!confbase || !*confbase) {
1398 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1399 meshlink_errno = MESHLINK_EINVAL;
1403 char lock_filename[PATH_MAX];
1404 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1406 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1407 meshlink_open_params_t params = {
1408 .confbase = (char *)confbase,
1409 .lock_filename = lock_filename,
1410 .name = (char *)name,
1411 .appname = (char *)appname,
1412 .devclass = devclass,
1416 return meshlink_open_ex(¶ms);
1419 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) {
1420 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
1422 if(!confbase || !*confbase) {
1423 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1424 meshlink_errno = MESHLINK_EINVAL;
1428 char lock_filename[PATH_MAX];
1429 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1431 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1432 meshlink_open_params_t params = {
1433 .confbase = (char *)confbase,
1434 .lock_filename = lock_filename,
1435 .name = (char *)name,
1436 .appname = (char *)appname,
1437 .devclass = devclass,
1441 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1445 return meshlink_open_ex(¶ms);
1448 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1449 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
1452 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1453 meshlink_errno = MESHLINK_EINVAL;
1457 if(!check_id(name)) {
1458 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1459 meshlink_errno = MESHLINK_EINVAL;
1463 if(!appname || !*appname) {
1464 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1465 meshlink_errno = MESHLINK_EINVAL;
1469 if(strchr(appname, ' ')) {
1470 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1471 meshlink_errno = MESHLINK_EINVAL;
1475 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1476 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1477 meshlink_errno = MESHLINK_EINVAL;
1481 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1482 meshlink_open_params_t params = {
1483 .name = (char *)name,
1484 .appname = (char *)appname,
1485 .devclass = devclass,
1489 return meshlink_open_ex(¶ms);
1492 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1493 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
1495 // Validate arguments provided by the application
1496 if(!params->appname || !*params->appname) {
1497 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1498 meshlink_errno = MESHLINK_EINVAL;
1502 if(strchr(params->appname, ' ')) {
1503 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1504 meshlink_errno = MESHLINK_EINVAL;
1508 if(params->name && !check_id(params->name)) {
1509 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1510 meshlink_errno = MESHLINK_EINVAL;
1514 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1515 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1516 meshlink_errno = MESHLINK_EINVAL;
1520 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1521 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1522 meshlink_errno = MESHLINK_EINVAL;
1526 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1528 if(params->confbase) {
1529 mesh->confbase = xstrdup(params->confbase);
1532 mesh->appname = xstrdup(params->appname);
1533 mesh->devclass = params->devclass;
1534 mesh->discovery.enabled = true;
1535 mesh->invitation_timeout = 604800; // 1 week
1536 mesh->netns = params->netns;
1537 mesh->submeshes = NULL;
1538 mesh->log_cb = global_log_cb;
1539 mesh->log_level = global_log_level;
1540 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1542 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1545 randomize(&mesh->session_id, sizeof(mesh->session_id));
1546 } while(mesh->session_id == 0);
1548 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1550 mesh->name = params->name ? xstrdup(params->name) : NULL;
1554 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1556 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1557 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1558 meshlink_close(mesh);
1559 meshlink_errno = MESHLINK_EINTERNAL;
1564 // initialize mutexes and conds
1565 pthread_mutexattr_t attr;
1566 pthread_mutexattr_init(&attr);
1568 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
1572 pthread_mutex_init(&mesh->mutex, &attr);
1573 pthread_cond_init(&mesh->cond, NULL);
1575 pthread_cond_init(&mesh->adns_cond, NULL);
1577 mesh->threadstarted = false;
1578 event_loop_init(&mesh->loop);
1579 mesh->loop.data = mesh;
1581 meshlink_queue_init(&mesh->outpacketqueue);
1583 // Atomically lock the configuration directory.
1584 if(!main_config_lock(mesh, params->lock_filename)) {
1585 meshlink_close(mesh);
1589 // If no configuration exists yet, create it.
1591 bool new_configuration = false;
1593 if(!meshlink_confbase_exists(mesh)) {
1595 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1596 meshlink_close(mesh);
1597 meshlink_errno = MESHLINK_ESTORAGE;
1601 if(!meshlink_setup(mesh)) {
1602 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1603 meshlink_close(mesh);
1607 new_configuration = true;
1609 if(!meshlink_read_config(mesh)) {
1610 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1611 meshlink_close(mesh);
1616 mesh->storage_policy = params->storage_policy;
1619 struct WSAData wsa_state;
1620 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1623 // Setup up everything
1624 // TODO: we should not open listening sockets yet
1626 bool success = false;
1628 if(mesh->netns != -1) {
1632 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1633 void *retval = NULL;
1634 success = pthread_join(thr, &retval) == 0 && retval;
1638 meshlink_errno = MESHLINK_EINTERNAL;
1641 #endif // HAVE_SETNS
1643 success = setup_network(mesh);
1647 meshlink_close(mesh);
1648 meshlink_errno = MESHLINK_ENETWORK;
1652 add_local_addresses(mesh);
1654 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1655 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1659 idle_set(&mesh->loop, idle, mesh);
1661 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1665 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1666 logger(NULL, MESHLINK_DEBUG, "meshlink_submesh_open(%s)", submesh);
1668 meshlink_submesh_t *s = NULL;
1671 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1672 meshlink_errno = MESHLINK_EINVAL;
1676 if(!submesh || !*submesh) {
1677 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1678 meshlink_errno = MESHLINK_EINVAL;
1683 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1687 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1689 pthread_mutex_unlock(&mesh->mutex);
1694 static void *meshlink_main_loop(void *arg) {
1695 meshlink_handle_t *mesh = arg;
1697 if(mesh->netns != -1) {
1700 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1701 pthread_cond_signal(&mesh->cond);
1706 pthread_cond_signal(&mesh->cond);
1708 #endif // HAVE_SETNS
1711 if(mesh->discovery.enabled) {
1712 discovery_start(mesh);
1715 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1719 if(mesh->thread_status_cb) {
1720 mesh->thread_status_cb(mesh, true);
1723 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1724 pthread_cond_broadcast(&mesh->cond);
1726 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1728 if(mesh->thread_status_cb) {
1729 mesh->thread_status_cb(mesh, false);
1732 pthread_mutex_unlock(&mesh->mutex);
1735 if(mesh->discovery.enabled) {
1736 discovery_stop(mesh);
1742 bool meshlink_start(meshlink_handle_t *mesh) {
1744 meshlink_errno = MESHLINK_EINVAL;
1748 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1750 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1755 assert(mesh->private_key);
1756 assert(mesh->self->ecdsa);
1757 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1759 if(mesh->threadstarted) {
1760 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1761 pthread_mutex_unlock(&mesh->mutex);
1765 if(mesh->listen_socket[0].tcp.fd < 0) {
1766 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1767 meshlink_errno = MESHLINK_ENETWORK;
1771 // Reset node connection timers
1772 for splay_each(node_t, n, mesh->nodes) {
1773 n->last_connect_try = 0;
1776 // TODO: open listening sockets first
1778 //Check that a valid name is set
1780 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1781 meshlink_errno = MESHLINK_EINVAL;
1782 pthread_mutex_unlock(&mesh->mutex);
1786 init_outgoings(mesh);
1789 // Start the main thread
1791 event_loop_start(&mesh->loop);
1793 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1794 pthread_attr_t attr;
1795 pthread_attr_init(&attr);
1796 pthread_attr_setstacksize(&attr, 1024 * 1024);
1798 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1799 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1800 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1801 meshlink_errno = MESHLINK_EINTERNAL;
1802 event_loop_stop(&mesh->loop);
1803 pthread_mutex_unlock(&mesh->mutex);
1807 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1808 mesh->threadstarted = true;
1810 // Ensure we are considered reachable
1813 pthread_mutex_unlock(&mesh->mutex);
1817 void meshlink_stop(meshlink_handle_t *mesh) {
1818 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1821 meshlink_errno = MESHLINK_EINVAL;
1825 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1829 // Shut down the main thread
1830 event_loop_stop(&mesh->loop);
1832 // Send ourselves a UDP packet to kick the event loop
1833 for(int i = 0; i < mesh->listen_sockets; i++) {
1835 socklen_t salen = sizeof(sa);
1837 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1838 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1842 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1843 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1847 if(mesh->threadstarted) {
1848 // Wait for the main thread to finish
1849 pthread_mutex_unlock(&mesh->mutex);
1851 if(pthread_join(mesh->thread, NULL) != 0) {
1855 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1859 mesh->threadstarted = false;
1862 // Close all metaconnections
1863 if(mesh->connections) {
1864 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1866 connection_t *c = node->data;
1868 terminate_connection(mesh, c, false);
1873 exit_outgoings(mesh);
1875 // Ensure we are considered unreachable
1880 // Try to write out any changed node config files, ignore errors at this point.
1882 for splay_each(node_t, n, mesh->nodes) {
1883 if(n->status.dirty) {
1884 if(!node_write_config(mesh, n, false)) {
1891 pthread_mutex_unlock(&mesh->mutex);
1894 void meshlink_close(meshlink_handle_t *mesh) {
1895 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1898 meshlink_errno = MESHLINK_EINVAL;
1902 // stop can be called even if mesh has not been started
1903 meshlink_stop(mesh);
1905 // lock is not released after this
1906 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1910 // Close and free all resources used.
1912 close_network_connections(mesh);
1914 logger(mesh, MESHLINK_INFO, "Terminating");
1916 event_loop_exit(&mesh->loop);
1920 if(mesh->confbase) {
1926 ecdsa_free(mesh->invitation_key);
1928 if(mesh->netns != -1) {
1932 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1936 meshlink_queue_exit(&mesh->outpacketqueue);
1939 free(mesh->appname);
1940 free(mesh->confbase);
1941 free(mesh->config_key);
1942 free(mesh->external_address_url);
1944 ecdsa_free(mesh->private_key);
1946 if(mesh->invitation_addresses) {
1947 list_delete_list(mesh->invitation_addresses);
1950 main_config_unlock(mesh);
1952 pthread_mutex_unlock(&mesh->mutex);
1953 pthread_mutex_destroy(&mesh->mutex);
1955 memset(mesh, 0, sizeof(*mesh));
1960 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1961 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1964 meshlink_errno = MESHLINK_EINVAL;
1968 if(!params->confbase) {
1969 /* Ephemeral instances */
1973 /* Exit early if the confbase directory itself doesn't exist */
1974 if(access(params->confbase, F_OK) && errno == ENOENT) {
1978 /* Take the lock the same way meshlink_open() would. */
1979 FILE *lockfile = fopen(params->lock_filename, "w+");
1982 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1983 meshlink_errno = MESHLINK_ESTORAGE;
1988 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1992 // TODO: use _locking()?
1995 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1996 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1998 meshlink_errno = MESHLINK_EBUSY;
2004 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
2005 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
2009 if(unlink(params->lock_filename)) {
2010 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
2012 meshlink_errno = MESHLINK_ESTORAGE;
2018 if(!sync_path(params->confbase)) {
2019 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
2020 meshlink_errno = MESHLINK_ESTORAGE;
2027 bool meshlink_destroy(const char *confbase) {
2028 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
2030 char lock_filename[PATH_MAX];
2031 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
2033 meshlink_open_params_t params = {
2034 .confbase = (char *)confbase,
2035 .lock_filename = lock_filename,
2038 return meshlink_destroy_ex(¶ms);
2041 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
2042 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
2045 meshlink_errno = MESHLINK_EINVAL;
2049 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2053 mesh->receive_cb = cb;
2054 pthread_mutex_unlock(&mesh->mutex);
2057 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
2058 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
2061 meshlink_errno = MESHLINK_EINVAL;
2065 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2069 mesh->connection_try_cb = cb;
2070 pthread_mutex_unlock(&mesh->mutex);
2073 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
2074 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
2077 meshlink_errno = MESHLINK_EINVAL;
2081 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2085 mesh->node_status_cb = cb;
2086 pthread_mutex_unlock(&mesh->mutex);
2089 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
2090 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
2093 meshlink_errno = MESHLINK_EINVAL;
2097 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2101 mesh->node_pmtu_cb = cb;
2102 pthread_mutex_unlock(&mesh->mutex);
2105 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
2106 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
2109 meshlink_errno = MESHLINK_EINVAL;
2113 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2117 mesh->node_duplicate_cb = cb;
2118 pthread_mutex_unlock(&mesh->mutex);
2121 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
2122 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
2125 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2130 mesh->log_level = cb ? level : 0;
2131 pthread_mutex_unlock(&mesh->mutex);
2134 global_log_level = cb ? level : 0;
2138 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
2139 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
2142 meshlink_errno = MESHLINK_EINVAL;
2146 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2150 mesh->error_cb = cb;
2151 pthread_mutex_unlock(&mesh->mutex);
2154 void meshlink_set_blacklisted_cb(struct meshlink_handle *mesh, meshlink_blacklisted_cb_t cb) {
2155 logger(mesh, MESHLINK_DEBUG, "meshlink_set_blacklisted_cb(%p)", (void *)(intptr_t)cb);
2158 meshlink_errno = MESHLINK_EINVAL;
2162 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2166 mesh->blacklisted_cb = cb;
2167 pthread_mutex_unlock(&mesh->mutex);
2170 void meshlink_set_thread_status_cb(struct meshlink_handle *mesh, meshlink_thread_status_cb_t cb) {
2171 logger(mesh, MESHLINK_DEBUG, "meshlink_set_thread_status_cb(%p)", (void *)(intptr_t)cb);
2174 meshlink_errno = MESHLINK_EINVAL;
2178 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2182 mesh->thread_status_cb = cb;
2183 pthread_mutex_unlock(&mesh->mutex);
2186 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
2187 meshlink_packethdr_t *hdr;
2189 if(len > MAXSIZE - sizeof(*hdr)) {
2190 meshlink_errno = MESHLINK_EINVAL;
2194 node_t *n = (node_t *)destination;
2196 if(n->status.blacklisted) {
2197 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
2198 meshlink_errno = MESHLINK_EBLACKLISTED;
2202 // Prepare the packet
2203 packet->probe = false;
2204 packet->len = len + sizeof(*hdr);
2206 hdr = (meshlink_packethdr_t *)packet->data;
2207 memset(hdr, 0, sizeof(*hdr));
2208 // leave the last byte as 0 to make sure strings are always
2209 // null-terminated if they are longer than the buffer
2210 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
2211 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
2213 memcpy(packet->data + sizeof(*hdr), data, len);
2218 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2220 assert(destination);
2224 // Prepare the packet
2225 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2229 // Send it immediately
2230 route(mesh, mesh->self, mesh->packet);
2235 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2236 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
2238 // Validate arguments
2239 if(!mesh || !destination) {
2240 meshlink_errno = MESHLINK_EINVAL;
2249 meshlink_errno = MESHLINK_EINVAL;
2253 // Prepare the packet
2254 vpn_packet_t *packet = malloc(sizeof(*packet));
2257 meshlink_errno = MESHLINK_ENOMEM;
2261 if(!prepare_packet(mesh, destination, data, len, packet)) {
2267 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2269 meshlink_errno = MESHLINK_ENOMEM;
2273 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2275 // Notify event loop
2276 signal_trigger(&mesh->loop, &mesh->datafromapp);
2281 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2283 meshlink_handle_t *mesh = data;
2285 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2287 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2288 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2289 route(mesh, mesh->self, packet);
2294 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2295 if(!mesh || !destination) {
2296 meshlink_errno = MESHLINK_EINVAL;
2300 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2304 node_t *n = (node_t *)destination;
2306 if(!n->status.reachable) {
2307 pthread_mutex_unlock(&mesh->mutex);
2310 } else if(n->mtuprobes > 30 && n->minmtu) {
2311 pthread_mutex_unlock(&mesh->mutex);
2314 pthread_mutex_unlock(&mesh->mutex);
2319 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2320 if(!mesh || !node) {
2321 meshlink_errno = MESHLINK_EINVAL;
2325 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2329 node_t *n = (node_t *)node;
2331 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2332 meshlink_errno = MESHLINK_EINTERNAL;
2333 pthread_mutex_unlock(&mesh->mutex);
2337 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2340 meshlink_errno = MESHLINK_EINTERNAL;
2343 pthread_mutex_unlock(&mesh->mutex);
2347 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2349 meshlink_errno = MESHLINK_EINVAL;
2353 return (meshlink_node_t *)mesh->self;
2356 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2357 if(!mesh || !name) {
2358 meshlink_errno = MESHLINK_EINVAL;
2364 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2368 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2369 pthread_mutex_unlock(&mesh->mutex);
2372 meshlink_errno = MESHLINK_ENOENT;
2375 return (meshlink_node_t *)n;
2378 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2379 if(!mesh || !name) {
2380 meshlink_errno = MESHLINK_EINVAL;
2384 meshlink_submesh_t *submesh = NULL;
2386 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2390 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2391 pthread_mutex_unlock(&mesh->mutex);
2394 meshlink_errno = MESHLINK_ENOENT;
2400 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2401 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2402 meshlink_errno = MESHLINK_EINVAL;
2406 meshlink_node_t **result;
2409 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2413 *nmemb = mesh->nodes->count;
2414 result = realloc(nodes, *nmemb * sizeof(*nodes));
2417 meshlink_node_t **p = result;
2419 for splay_each(node_t, n, mesh->nodes) {
2420 *p++ = (meshlink_node_t *)n;
2425 meshlink_errno = MESHLINK_ENOMEM;
2428 pthread_mutex_unlock(&mesh->mutex);
2433 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) {
2434 meshlink_node_t **result;
2436 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2442 for splay_each(node_t, n, mesh->nodes) {
2443 if(search_node(n, condition)) {
2450 pthread_mutex_unlock(&mesh->mutex);
2454 result = realloc(nodes, *nmemb * sizeof(*nodes));
2457 meshlink_node_t **p = result;
2459 for splay_each(node_t, n, mesh->nodes) {
2460 if(search_node(n, condition)) {
2461 *p++ = (meshlink_node_t *)n;
2467 meshlink_errno = MESHLINK_ENOMEM;
2470 pthread_mutex_unlock(&mesh->mutex);
2475 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2476 dev_class_t *devclass = (dev_class_t *)condition;
2478 if(*devclass == (dev_class_t)node->devclass) {
2485 static bool search_node_by_blacklisted(const node_t *node, const void *condition) {
2486 return *(bool *)condition == node->status.blacklisted;
2489 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2490 if(condition == node->submesh) {
2502 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2503 const struct time_range *range = condition;
2504 time_t start = node->last_reachable;
2505 time_t end = node->last_unreachable;
2515 if(range->end >= range->start) {
2516 return start <= range->end && end >= range->start;
2518 return start > range->start || end < range->end;
2522 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) {
2523 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2524 meshlink_errno = MESHLINK_EINVAL;
2528 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2531 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2532 if(!mesh || !submesh || !nmemb) {
2533 meshlink_errno = MESHLINK_EINVAL;
2537 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2540 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) {
2541 if(!mesh || !nmemb) {
2542 meshlink_errno = MESHLINK_EINVAL;
2546 struct time_range range = {start, end};
2548 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2551 meshlink_node_t **meshlink_get_all_nodes_by_blacklisted(meshlink_handle_t *mesh, bool blacklisted, meshlink_node_t **nodes, size_t *nmemb) {
2552 if(!mesh || !nmemb) {
2553 meshlink_errno = MESHLINK_EINVAL;
2557 return meshlink_get_all_nodes_by_condition(mesh, &blacklisted, nodes, nmemb, search_node_by_blacklisted);
2560 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2561 if(!mesh || !node) {
2562 meshlink_errno = MESHLINK_EINVAL;
2566 dev_class_t devclass;
2568 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2572 devclass = ((node_t *)node)->devclass;
2574 pthread_mutex_unlock(&mesh->mutex);
2579 bool meshlink_get_node_tiny(meshlink_handle_t *mesh, meshlink_node_t *node) {
2580 if(!mesh || !node) {
2581 meshlink_errno = MESHLINK_EINVAL;
2587 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2591 tiny = ((node_t *)node)->status.tiny;
2593 pthread_mutex_unlock(&mesh->mutex);
2598 bool meshlink_get_node_blacklisted(meshlink_handle_t *mesh, meshlink_node_t *node) {
2600 meshlink_errno = MESHLINK_EINVAL;
2604 return mesh->default_blacklist;
2609 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2613 blacklisted = ((node_t *)node)->status.blacklisted;
2615 pthread_mutex_unlock(&mesh->mutex);
2620 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2621 if(!mesh || !node) {
2622 meshlink_errno = MESHLINK_EINVAL;
2626 node_t *n = (node_t *)node;
2628 meshlink_submesh_t *s;
2630 s = (meshlink_submesh_t *)n->submesh;
2635 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2636 if(!mesh || !node) {
2637 meshlink_errno = MESHLINK_EINVAL;
2641 node_t *n = (node_t *)node;
2644 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2648 reachable = n->status.reachable && !n->status.blacklisted;
2650 if(last_reachable) {
2651 *last_reachable = n->last_reachable;
2654 if(last_unreachable) {
2655 *last_unreachable = n->last_unreachable;
2658 pthread_mutex_unlock(&mesh->mutex);
2663 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2664 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
2666 if(!mesh || !data || !len || !signature || !siglen) {
2667 meshlink_errno = MESHLINK_EINVAL;
2671 if(*siglen < MESHLINK_SIGLEN) {
2672 meshlink_errno = MESHLINK_EINVAL;
2676 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2680 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2681 meshlink_errno = MESHLINK_EINTERNAL;
2682 pthread_mutex_unlock(&mesh->mutex);
2686 *siglen = MESHLINK_SIGLEN;
2687 pthread_mutex_unlock(&mesh->mutex);
2691 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2692 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
2694 if(!mesh || !source || !data || !len || !signature) {
2695 meshlink_errno = MESHLINK_EINVAL;
2699 if(siglen != MESHLINK_SIGLEN) {
2700 meshlink_errno = MESHLINK_EINVAL;
2704 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2710 struct node_t *n = (struct node_t *)source;
2712 if(!node_read_public_key(mesh, n)) {
2713 meshlink_errno = MESHLINK_EINTERNAL;
2716 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2719 pthread_mutex_unlock(&mesh->mutex);
2723 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2724 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2728 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2731 // TODO: Update invitation key if necessary?
2734 pthread_mutex_unlock(&mesh->mutex);
2736 return mesh->invitation_key;
2739 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2740 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
2742 if(!mesh || !node || !address) {
2743 meshlink_errno = MESHLINK_EINVAL;
2747 if(!is_valid_hostname(address)) {
2748 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
2749 meshlink_errno = MESHLINK_EINVAL;
2753 if((node_t *)node != mesh->self && !port) {
2754 logger(mesh, MESHLINK_ERROR, "Missing port number!");
2755 meshlink_errno = MESHLINK_EINVAL;
2760 if(port && !is_valid_port(port)) {
2761 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
2762 meshlink_errno = MESHLINK_EINVAL;
2766 char *canonical_address;
2768 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
2770 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2774 node_t *n = (node_t *)node;
2775 free(n->canonical_address);
2776 n->canonical_address = canonical_address;
2778 if(!node_write_config(mesh, n, false)) {
2779 pthread_mutex_unlock(&mesh->mutex);
2783 pthread_mutex_unlock(&mesh->mutex);
2785 return config_sync(mesh, "current");
2788 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
2789 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
2791 if(!mesh || !node) {
2792 meshlink_errno = MESHLINK_EINVAL;
2796 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2800 node_t *n = (node_t *)node;
2801 free(n->canonical_address);
2802 n->canonical_address = NULL;
2804 if(!node_write_config(mesh, n, false)) {
2805 pthread_mutex_unlock(&mesh->mutex);
2809 pthread_mutex_unlock(&mesh->mutex);
2811 return config_sync(mesh, "current");
2814 bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
2815 logger(mesh, MESHLINK_DEBUG, "meshlink_add_invitation_address(%s, %s)", address ? address : "(null)", port ? port : "(null)");
2817 if(!mesh || !address) {
2818 meshlink_errno = MESHLINK_EINVAL;
2822 if(!is_valid_hostname(address)) {
2823 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s\n", address);
2824 meshlink_errno = MESHLINK_EINVAL;
2828 if(port && !is_valid_port(port)) {
2829 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s\n", address);
2830 meshlink_errno = MESHLINK_EINVAL;
2837 xasprintf(&combo, "%s/%s", address, port);
2839 combo = xstrdup(address);
2842 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2846 if(!mesh->invitation_addresses) {
2847 mesh->invitation_addresses = list_alloc((list_action_t)free);
2850 list_insert_tail(mesh->invitation_addresses, combo);
2851 pthread_mutex_unlock(&mesh->mutex);
2856 void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
2857 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_invitation_addresses()");
2860 meshlink_errno = MESHLINK_EINVAL;
2864 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2868 if(mesh->invitation_addresses) {
2869 list_delete_list(mesh->invitation_addresses);
2870 mesh->invitation_addresses = NULL;
2873 pthread_mutex_unlock(&mesh->mutex);
2876 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2877 logger(mesh, MESHLINK_DEBUG, "meshlink_add_address(%s)", address ? address : "(null)");
2879 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2882 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2883 logger(mesh, MESHLINK_DEBUG, "meshlink_add_external_address()");
2886 meshlink_errno = MESHLINK_EINVAL;
2890 char *address = meshlink_get_external_address(mesh);
2896 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2902 int meshlink_get_port(meshlink_handle_t *mesh) {
2904 meshlink_errno = MESHLINK_EINVAL;
2909 meshlink_errno = MESHLINK_EINTERNAL;
2915 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2919 port = atoi(mesh->myport);
2920 pthread_mutex_unlock(&mesh->mutex);
2925 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2926 logger(mesh, MESHLINK_DEBUG, "meshlink_set_port(%d)", port);
2928 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2929 meshlink_errno = MESHLINK_EINVAL;
2933 if(mesh->myport && port == atoi(mesh->myport)) {
2937 if(!try_bind(mesh, port)) {
2938 meshlink_errno = MESHLINK_ENETWORK;
2942 devtool_trybind_probe();
2946 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2950 if(mesh->threadstarted) {
2951 meshlink_errno = MESHLINK_EINVAL;
2956 xasprintf(&mesh->myport, "%d", port);
2958 /* Close down the network. This also deletes mesh->self. */
2959 close_network_connections(mesh);
2961 /* Recreate mesh->self. */
2962 mesh->self = new_node();
2963 mesh->self->name = xstrdup(mesh->name);
2964 mesh->self->devclass = mesh->devclass;
2965 mesh->self->session_id = mesh->session_id;
2966 xasprintf(&mesh->myport, "%d", port);
2968 if(!node_read_public_key(mesh, mesh->self)) {
2969 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2970 meshlink_errno = MESHLINK_ESTORAGE;
2971 free_node(mesh->self);
2974 } else if(!setup_network(mesh)) {
2975 meshlink_errno = MESHLINK_ENETWORK;
2979 /* Rebuild our own list of recent addresses */
2980 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2981 add_local_addresses(mesh);
2983 /* Write meshlink.conf with the updated port number */
2984 write_main_config_files(mesh);
2986 rval = config_sync(mesh, "current");
2989 pthread_mutex_unlock(&mesh->mutex);
2991 return rval && meshlink_get_port(mesh) == port;
2994 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2995 logger(mesh, MESHLINK_DEBUG, "meshlink_invitation_timeout(%d)", timeout);
2997 mesh->invitation_timeout = timeout;
3000 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
3001 logger(mesh, MESHLINK_DEBUG, "meshlink_invite_ex(%s, %s, %u)", submesh ? submesh->name : "(null)", name ? name : "(null)", flags);
3003 meshlink_submesh_t *s = NULL;
3006 meshlink_errno = MESHLINK_EINVAL;
3011 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
3014 logger(mesh, MESHLINK_ERROR, "Invalid submesh handle.\n");
3015 meshlink_errno = MESHLINK_EINVAL;
3019 s = (meshlink_submesh_t *)mesh->self->submesh;
3022 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3026 // Check validity of the new node's name
3027 if(!check_id(name)) {
3028 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
3029 meshlink_errno = MESHLINK_EINVAL;
3030 pthread_mutex_unlock(&mesh->mutex);
3034 // Ensure no host configuration file with that name exists
3035 if(config_exists(mesh, "current", name)) {
3036 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
3037 meshlink_errno = MESHLINK_EEXIST;
3038 pthread_mutex_unlock(&mesh->mutex);
3042 // Ensure no other nodes know about this name
3043 if(lookup_node(mesh, name)) {
3044 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
3045 meshlink_errno = MESHLINK_EEXIST;
3046 pthread_mutex_unlock(&mesh->mutex);
3050 // Get the local address
3051 char *address = get_my_hostname(mesh, flags);
3054 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
3055 meshlink_errno = MESHLINK_ERESOLV;
3056 pthread_mutex_unlock(&mesh->mutex);
3060 if(!refresh_invitation_key(mesh)) {
3061 meshlink_errno = MESHLINK_EINTERNAL;
3062 pthread_mutex_unlock(&mesh->mutex);
3066 // If we changed our own host config file, write it out now
3067 if(mesh->self->status.dirty) {
3068 if(!node_write_config(mesh, mesh->self, false)) {
3069 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
3070 pthread_mutex_unlock(&mesh->mutex);
3077 // Create a hash of the key.
3078 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
3079 sha512(fingerprint, strlen(fingerprint), hash);
3080 b64encode_urlsafe(hash, hash, 18);
3082 // Create a random cookie for this invitation.
3084 randomize(cookie, 18);
3086 // Create a filename that doesn't reveal the cookie itself
3087 char buf[18 + strlen(fingerprint)];
3088 char cookiehash[64];
3089 memcpy(buf, cookie, 18);
3090 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
3091 sha512(buf, sizeof(buf), cookiehash);
3092 b64encode_urlsafe(cookiehash, cookiehash, 18);
3094 b64encode_urlsafe(cookie, cookie, 18);
3098 /* Construct the invitation file */
3099 uint8_t outbuf[4096];
3100 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
3102 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
3103 packmsg_add_str(&inv, name);
3104 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
3105 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
3107 /* TODO: Add several host config files to bootstrap connections.
3108 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
3109 * and are not blacklisted.
3111 config_t configs[5];
3112 memset(configs, 0, sizeof(configs));
3115 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
3119 /* Append host config files to the invitation file */
3120 packmsg_add_array(&inv, count);
3122 for(int i = 0; i < count; i++) {
3123 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
3124 config_free(&configs[i]);
3127 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
3129 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
3130 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
3131 meshlink_errno = MESHLINK_ESTORAGE;
3132 pthread_mutex_unlock(&mesh->mutex);
3136 // Create an URL from the local address, key hash and cookie
3138 xasprintf(&url, "%s/%s%s", address, hash, cookie);
3141 pthread_mutex_unlock(&mesh->mutex);
3145 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
3146 logger(mesh, MESHLINK_DEBUG, "meshlink_invite_ex(%s, %s)", submesh ? submesh->name : "(null)", name ? name : "(null)");
3148 return meshlink_invite_ex(mesh, submesh, name, 0);
3151 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
3152 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
3154 if(!mesh || !invitation) {
3155 meshlink_errno = MESHLINK_EINVAL;
3159 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
3160 meshlink_errno = MESHLINK_EINVAL;
3164 join_state_t state = {
3169 ecdsa_t *key = NULL;
3170 ecdsa_t *hiskey = NULL;
3172 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
3173 char copy[strlen(invitation) + 1];
3175 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3179 //Before doing meshlink_join make sure we are not connected to another mesh
3180 if(mesh->threadstarted) {
3181 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
3182 meshlink_errno = MESHLINK_EINVAL;
3186 // 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.
3187 if(mesh->nodes->count > 1) {
3188 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
3189 meshlink_errno = MESHLINK_EINVAL;
3193 strcpy(copy, invitation);
3195 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
3197 char *slash = strchr(copy, '/');
3205 if(strlen(slash) != 48) {
3209 char *address = copy;
3212 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
3216 if(mesh->inviter_commits_first) {
3217 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
3220 // Generate a throw-away key for the invitation.
3221 key = ecdsa_generate();
3224 meshlink_errno = MESHLINK_EINTERNAL;
3228 char *b64key = ecdsa_get_base64_public_key(key);
3231 while(address && *address) {
3232 // We allow commas in the address part to support multiple addresses in one invitation URL.
3233 comma = strchr(address, ',');
3239 // Split of the port
3240 port = strrchr(address, ':');
3248 // IPv6 address are enclosed in brackets, per RFC 3986
3249 if(*address == '[') {
3251 char *bracket = strchr(address, ']');
3264 // Connect to the meshlink daemon mentioned in the URL.
3265 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), SOCK_STREAM, 30);
3268 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
3269 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
3271 if(state.sock == -1) {
3272 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
3273 meshlink_errno = MESHLINK_ENETWORK;
3279 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
3282 set_timeout(state.sock, 5000);
3284 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
3285 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
3286 meshlink_errno = MESHLINK_ENETWORK;
3287 closesocket(state.sock);
3297 meshlink_errno = MESHLINK_ERESOLV;
3300 if(state.sock != -1 || !comma) {
3307 if(state.sock == -1) {
3311 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
3313 // Tell him we have an invitation, and give him our throw-away key.
3317 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
3318 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
3319 meshlink_errno = MESHLINK_ENETWORK;
3325 char hisname[4096] = "";
3326 int code, hismajor, hisminor = 0;
3328 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) {
3329 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
3330 meshlink_errno = MESHLINK_ENETWORK;
3334 // Check if the hash of the key he gave us matches the hash in the URL.
3335 char *fingerprint = state.line + 2;
3338 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
3339 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
3340 meshlink_errno = MESHLINK_EINTERNAL;
3344 if(memcmp(hishash, state.hash, 18)) {
3345 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
3346 meshlink_errno = MESHLINK_EPEER;
3350 hiskey = ecdsa_set_base64_public_key(fingerprint);
3353 meshlink_errno = MESHLINK_EINTERNAL;
3357 // Start an SPTPS session
3358 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
3359 meshlink_errno = MESHLINK_EINTERNAL;
3363 // Feed rest of input buffer to SPTPS
3364 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
3365 meshlink_errno = MESHLINK_EPEER;
3370 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
3372 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
3374 if(errno == EINTR) {
3378 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
3379 meshlink_errno = MESHLINK_ENETWORK;
3383 if(!sptps_receive_data(&state.sptps, state.line, len)) {
3384 meshlink_errno = MESHLINK_EPEER;
3389 if(!state.success) {
3390 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
3391 meshlink_errno = MESHLINK_EPEER;
3395 sptps_stop(&state.sptps);
3398 closesocket(state.sock);
3400 pthread_mutex_unlock(&mesh->mutex);
3404 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
3405 meshlink_errno = MESHLINK_EINVAL;
3407 sptps_stop(&state.sptps);
3411 if(state.sock != -1) {
3412 closesocket(state.sock);
3415 pthread_mutex_unlock(&mesh->mutex);
3419 char *meshlink_export(meshlink_handle_t *mesh) {
3421 meshlink_errno = MESHLINK_EINVAL;
3425 // Create a config file on the fly.
3428 packmsg_output_t out = {buf, sizeof(buf)};
3429 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
3430 packmsg_add_str(&out, mesh->name);
3431 packmsg_add_str(&out, CORE_MESH);
3433 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3437 packmsg_add_int32(&out, mesh->self->devclass);
3438 packmsg_add_bool(&out, mesh->self->status.blacklisted);
3439 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
3441 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
3442 char *canonical_address = NULL;
3443 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
3444 packmsg_add_str(&out, canonical_address);
3445 free(canonical_address);
3447 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3452 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3453 if(mesh->self->recent[i].sa.sa_family) {
3460 packmsg_add_array(&out, count);
3462 for(uint32_t i = 0; i < count; i++) {
3463 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3466 packmsg_add_int64(&out, 0);
3467 packmsg_add_int64(&out, 0);
3469 pthread_mutex_unlock(&mesh->mutex);
3471 if(!packmsg_output_ok(&out)) {
3472 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
3473 meshlink_errno = MESHLINK_EINTERNAL;
3477 // Prepare a base64-encoded packmsg array containing our config file
3479 uint32_t len = packmsg_output_size(&out, buf);
3480 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3481 uint8_t *buf2 = xmalloc(len2);
3482 packmsg_output_t out2 = {buf2, len2};
3483 packmsg_add_array(&out2, 1);
3484 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3486 if(!packmsg_output_ok(&out2)) {
3487 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
3488 meshlink_errno = MESHLINK_EINTERNAL;
3493 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3495 return (char *)buf2;
3498 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3499 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
3501 if(!mesh || !data) {
3502 meshlink_errno = MESHLINK_EINVAL;
3506 size_t datalen = strlen(data);
3507 uint8_t *buf = xmalloc(datalen);
3508 int buflen = b64decode(data, buf, datalen);
3511 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3513 meshlink_errno = MESHLINK_EPEER;
3517 packmsg_input_t in = {buf, buflen};
3518 uint32_t count = packmsg_get_array(&in);
3521 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3523 meshlink_errno = MESHLINK_EPEER;
3527 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3533 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
3539 packmsg_input_t in2 = {data2, len2};
3540 uint32_t version = packmsg_get_uint32(&in2);
3541 char *name = packmsg_get_str_dup(&in2);
3543 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3545 packmsg_input_invalidate(&in);
3549 if(!check_id(name)) {
3554 node_t *n = lookup_node(mesh, name);
3557 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3565 config_t config = {data2, len2};
3567 if(!node_read_from_config(mesh, n, &config)) {
3569 packmsg_input_invalidate(&in);
3573 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3574 n->last_reachable = 0;
3575 n->last_unreachable = 0;
3577 if(!node_write_config(mesh, n, true)) {
3586 pthread_mutex_unlock(&mesh->mutex);
3590 if(!packmsg_done(&in)) {
3591 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3592 meshlink_errno = MESHLINK_EPEER;
3596 if(!config_sync(mesh, "current")) {
3603 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3604 if(n == mesh->self) {
3605 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3606 meshlink_errno = MESHLINK_EINVAL;
3610 if(n->status.blacklisted) {
3611 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3615 n->status.blacklisted = true;
3617 /* Immediately shut down any connections we have with the blacklisted node.
3618 * We can't call terminate_connection(), because we might be called from a callback function.
3620 for list_each(connection_t, c, mesh->connections) {
3622 if(c->status.active) {
3623 send_error(mesh, c, BLACKLISTED, "blacklisted");
3626 shutdown(c->socket, SHUT_RDWR);
3630 utcp_reset_all_connections(n->utcp);
3637 n->status.udp_confirmed = false;
3639 if(n->status.reachable) {
3640 n->last_unreachable = time(NULL);
3643 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3644 * manually call the status callback if necessary.
3646 if(n->status.reachable && mesh->node_status_cb) {
3647 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3650 /* Remove any outstanding invitations */
3651 invitation_purge_node(mesh, n->name);
3653 return node_write_config(mesh, n, true) && config_sync(mesh, "current");
3656 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3657 logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist(%s)", node ? node->name : "(null)");
3659 if(!mesh || !node) {
3660 meshlink_errno = MESHLINK_EINVAL;
3664 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3668 if(!blacklist(mesh, (node_t *)node)) {
3669 pthread_mutex_unlock(&mesh->mutex);
3673 pthread_mutex_unlock(&mesh->mutex);
3675 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3679 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3680 logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist_by_name(%s)", name ? name : "(null)");
3682 if(!mesh || !name) {
3683 meshlink_errno = MESHLINK_EINVAL;
3687 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3691 node_t *n = lookup_node(mesh, (char *)name);
3695 n->name = xstrdup(name);
3699 if(!blacklist(mesh, (node_t *)n)) {
3700 pthread_mutex_unlock(&mesh->mutex);
3704 pthread_mutex_unlock(&mesh->mutex);
3706 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3710 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3711 if(n == mesh->self) {
3712 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3713 meshlink_errno = MESHLINK_EINVAL;
3717 if(!n->status.blacklisted) {
3718 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3722 n->status.blacklisted = false;
3724 if(n->status.reachable) {
3725 n->last_reachable = time(NULL);
3726 update_node_status(mesh, n);
3729 return node_write_config(mesh, n, true) && config_sync(mesh, "current");
3732 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3733 logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist(%s)", node ? node->name : "(null)");
3735 if(!mesh || !node) {
3736 meshlink_errno = MESHLINK_EINVAL;
3740 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3744 if(!whitelist(mesh, (node_t *)node)) {
3745 pthread_mutex_unlock(&mesh->mutex);
3749 pthread_mutex_unlock(&mesh->mutex);
3751 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3755 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3756 logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist_by_name(%s)", name ? name : "(null)");
3758 if(!mesh || !name) {
3759 meshlink_errno = MESHLINK_EINVAL;
3763 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3767 node_t *n = lookup_node(mesh, (char *)name);
3771 n->name = xstrdup(name);
3775 if(!whitelist(mesh, (node_t *)n)) {
3776 pthread_mutex_unlock(&mesh->mutex);
3780 pthread_mutex_unlock(&mesh->mutex);
3782 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3786 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3787 mesh->default_blacklist = blacklist;
3790 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3791 logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
3793 if(!mesh || !node) {
3794 meshlink_errno = MESHLINK_EINVAL;
3798 node_t *n = (node_t *)node;
3800 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3804 /* Check that the node is not reachable */
3805 if(n->status.reachable || n->connection) {
3806 pthread_mutex_unlock(&mesh->mutex);
3807 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3811 /* Check that we don't have any active UTCP connections */
3812 if(n->utcp && utcp_is_active(n->utcp)) {
3813 pthread_mutex_unlock(&mesh->mutex);
3814 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3818 /* Check that we have no active connections to this node */
3819 for list_each(connection_t, c, mesh->connections) {
3821 pthread_mutex_unlock(&mesh->mutex);
3822 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3827 /* Remove any pending outgoings to this node */
3828 if(mesh->outgoings) {
3829 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3830 if(outgoing->node == n) {
3831 list_delete_node(mesh->outgoings, list_node);
3836 /* Delete the config file for this node */
3837 if(!config_delete(mesh, "current", n->name)) {
3838 pthread_mutex_unlock(&mesh->mutex);
3842 /* Delete any pending invitations */
3843 invitation_purge_node(mesh, n->name);
3845 /* Delete the node struct and any remaining edges referencing this node */
3848 pthread_mutex_unlock(&mesh->mutex);
3850 return config_sync(mesh, "current");
3853 /* Hint that a hostname may be found at an address
3854 * See header file for detailed comment.
3856 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3857 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
3859 if(!mesh || !node || !addr) {
3860 meshlink_errno = EINVAL;
3864 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3868 node_t *n = (node_t *)node;
3870 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3871 if(!node_write_config(mesh, n, false)) {
3872 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3876 pthread_mutex_unlock(&mesh->mutex);
3877 // @TODO do we want to fire off a connection attempt right away?
3880 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3882 node_t *n = utcp->priv;
3883 meshlink_handle_t *mesh = n->mesh;
3885 if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
3886 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
3888 return mesh->channel_accept_cb;
3892 /* Finish one AIO buffer, return true if the channel is still open. */
3893 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3894 meshlink_aio_buffer_t *aio = *head;
3898 channel->in_callback = true;
3901 if(aio->cb.buffer) {
3902 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
3906 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3910 channel->in_callback = false;
3923 /* Finish all AIO buffers, return true if the channel is still open. */
3924 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3926 if(!aio_finish_one(mesh, channel, head)) {
3934 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3935 meshlink_channel_t *channel = connection->priv;
3941 node_t *n = channel->node;
3942 meshlink_handle_t *mesh = n->mesh;
3944 if(n->status.destroyed) {
3945 meshlink_channel_close(mesh, channel);
3949 const char *p = data;
3952 while(channel->aio_receive) {
3954 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
3955 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
3962 meshlink_aio_buffer_t *aio = channel->aio_receive;
3963 size_t todo = aio->len - aio->done;
3970 memcpy((char *)aio->data + aio->done, p, todo);
3972 ssize_t result = write(aio->fd, p, todo);
3975 if(result < 0 && errno == EINTR) {
3979 /* Writing to fd failed, cancel just this AIO buffer. */
3980 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
3982 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3996 if(aio->done == aio->len) {
3997 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
4007 if(channel->receive_cb) {
4008 channel->receive_cb(mesh, channel, p, left);
4014 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
4015 node_t *n = utcp_connection->utcp->priv;
4021 meshlink_handle_t *mesh = n->mesh;
4023 if(!mesh->channel_accept_cb) {
4027 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
4029 channel->c = utcp_connection;
4031 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
4032 utcp_accept(utcp_connection, channel_recv, channel);
4038 static void channel_retransmit(struct utcp_connection *utcp_connection) {
4039 node_t *n = utcp_connection->utcp->priv;
4040 meshlink_handle_t *mesh = n->mesh;
4043 timespec_clear(&n->last_udp_probe_sent);
4044 keepalive(mesh, n, false);
4048 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
4049 node_t *n = utcp->priv;
4051 if(n->status.destroyed) {
4055 meshlink_handle_t *mesh = n->mesh;
4056 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
4059 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
4060 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
4062 if(!mesh || !channel) {
4063 meshlink_errno = MESHLINK_EINVAL;
4067 channel->receive_cb = cb;
4070 void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
4072 node_t *n = (node_t *)source;
4078 utcp_recv(n->utcp, data, len);
4081 static void channel_poll(struct utcp_connection *connection, size_t len) {
4082 meshlink_channel_t *channel = connection->priv;
4088 node_t *n = channel->node;
4089 meshlink_handle_t *mesh = n->mesh;
4091 while(channel->aio_send) {
4093 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
4094 if(!aio_abort(mesh, channel, &channel->aio_send)) {
4101 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
4102 meshlink_aio_buffer_t *aio = channel->aio_send;
4103 size_t todo = aio->len - aio->done;
4111 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
4113 /* Limit the amount we read at once to avoid stack overflows */
4119 ssize_t result = read(aio->fd, buf, todo);
4123 sent = utcp_send(connection, buf, todo);
4125 if(result < 0 && errno == EINTR) {
4129 /* Reading from fd failed, cancel just this AIO buffer. */
4131 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
4134 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
4142 if(sent != (ssize_t)todo) {
4143 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
4144 if(!aio_abort(mesh, channel, &channel->aio_send)) {
4155 /* If we didn't finish this buffer, exit early. */
4156 if(aio->done < aio->len) {
4160 /* Signal completion of this buffer, and go to the next one. */
4161 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
4170 if(channel->poll_cb) {
4171 channel->poll_cb(mesh, channel, len);
4173 utcp_set_poll_cb(connection, NULL);
4177 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
4178 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
4180 if(!mesh || !channel) {
4181 meshlink_errno = MESHLINK_EINVAL;
4185 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4189 channel->poll_cb = cb;
4190 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
4191 pthread_mutex_unlock(&mesh->mutex);
4194 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
4195 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
4198 meshlink_errno = MESHLINK_EINVAL;
4202 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4206 mesh->channel_listen_cb = cb;
4208 pthread_mutex_unlock(&mesh->mutex);
4211 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
4212 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
4215 meshlink_errno = MESHLINK_EINVAL;
4219 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4223 mesh->channel_accept_cb = cb;
4225 for splay_each(node_t, n, mesh->nodes) {
4226 if(!n->utcp && n != mesh->self) {
4227 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4228 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4229 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4233 pthread_mutex_unlock(&mesh->mutex);
4236 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
4237 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
4239 meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
4242 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
4243 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
4245 meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
4248 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
4249 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
4251 if(!mesh || !channel) {
4252 meshlink_errno = MESHLINK_EINVAL;
4256 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4260 utcp_set_sndbuf(channel->c, buf, size);
4261 pthread_mutex_unlock(&mesh->mutex);
4264 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
4265 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
4267 if(!mesh || !channel) {
4268 meshlink_errno = MESHLINK_EINVAL;
4272 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4276 utcp_set_rcvbuf(channel->c, buf, size);
4277 pthread_mutex_unlock(&mesh->mutex);
4280 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
4281 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
4283 if(!mesh || !channel) {
4284 meshlink_errno = MESHLINK_EINVAL;
4288 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4292 utcp_set_flags(channel->c, flags);
4293 pthread_mutex_unlock(&mesh->mutex);
4296 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) {
4297 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);
4300 abort(); // TODO: handle non-NULL data
4303 if(!mesh || !node) {
4304 meshlink_errno = MESHLINK_EINVAL;
4308 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4312 node_t *n = (node_t *)node;
4315 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4316 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4317 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4320 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
4321 pthread_mutex_unlock(&mesh->mutex);
4326 if(n->status.blacklisted) {
4327 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
4328 meshlink_errno = MESHLINK_EBLACKLISTED;
4329 pthread_mutex_unlock(&mesh->mutex);
4333 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
4335 channel->receive_cb = cb;
4338 channel->priv = (void *)data;
4341 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
4343 pthread_mutex_unlock(&mesh->mutex);
4346 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
4354 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) {
4355 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
4357 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
4360 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
4361 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
4363 if(!mesh || !channel) {
4364 meshlink_errno = MESHLINK_EINVAL;
4368 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4372 utcp_shutdown(channel->c, direction);
4373 pthread_mutex_unlock(&mesh->mutex);
4376 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4377 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
4379 if(!mesh || !channel) {
4380 meshlink_errno = MESHLINK_EINVAL;
4384 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4389 utcp_close(channel->c);
4392 /* Clean up any outstanding AIO buffers. */
4393 aio_abort(mesh, channel, &channel->aio_send);
4394 aio_abort(mesh, channel, &channel->aio_receive);
4397 if(!channel->in_callback) {
4401 pthread_mutex_unlock(&mesh->mutex);
4404 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4405 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
4407 if(!mesh || !channel) {
4408 meshlink_errno = MESHLINK_EINVAL;
4412 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4417 utcp_abort(channel->c);
4420 /* Clean up any outstanding AIO buffers. */
4421 aio_abort(mesh, channel, &channel->aio_send);
4422 aio_abort(mesh, channel, &channel->aio_receive);
4425 if(!channel->in_callback) {
4429 pthread_mutex_unlock(&mesh->mutex);
4432 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
4433 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
4435 if(!mesh || !channel) {
4436 meshlink_errno = MESHLINK_EINVAL;
4445 meshlink_errno = MESHLINK_EINVAL;
4449 // TODO: more finegrained locking.
4450 // Ideally we want to put the data into the UTCP connection's send buffer.
4451 // Then, preferably only if there is room in the receiver window,
4452 // kick the meshlink thread to go send packets.
4456 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4460 /* Disallow direct calls to utcp_send() while we still have AIO active. */
4461 if(channel->aio_send) {
4464 retval = utcp_send(channel->c, data, len);
4467 pthread_mutex_unlock(&mesh->mutex);
4470 meshlink_errno = MESHLINK_ENETWORK;
4476 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) {
4477 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
4479 if(!mesh || !channel) {
4480 meshlink_errno = MESHLINK_EINVAL;
4485 meshlink_errno = MESHLINK_EINVAL;
4489 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4492 aio->cb.buffer = cb;
4495 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4499 /* Append the AIO buffer descriptor to the end of the chain */
4500 meshlink_aio_buffer_t **p = &channel->aio_send;
4508 /* Ensure the poll callback is set, and call it right now to push data if possible */
4509 utcp_set_poll_cb(channel->c, channel_poll);
4510 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
4513 channel_poll(channel->c, todo);
4516 pthread_mutex_unlock(&mesh->mutex);
4521 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) {
4522 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
4524 if(!mesh || !channel) {
4525 meshlink_errno = MESHLINK_EINVAL;
4529 if(!len || fd == -1) {
4530 meshlink_errno = MESHLINK_EINVAL;
4534 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4540 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4544 /* Append the AIO buffer descriptor to the end of the chain */
4545 meshlink_aio_buffer_t **p = &channel->aio_send;
4553 /* Ensure the poll callback is set, and call it right now to push data if possible */
4554 utcp_set_poll_cb(channel->c, channel_poll);
4555 size_t left = utcp_get_rcvbuf_free(channel->c);
4558 channel_poll(channel->c, left);
4561 pthread_mutex_unlock(&mesh->mutex);
4566 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) {
4567 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
4569 if(!mesh || !channel) {
4570 meshlink_errno = MESHLINK_EINVAL;
4575 meshlink_errno = MESHLINK_EINVAL;
4579 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4582 aio->cb.buffer = cb;
4585 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4589 /* Append the AIO buffer descriptor to the end of the chain */
4590 meshlink_aio_buffer_t **p = &channel->aio_receive;
4598 pthread_mutex_unlock(&mesh->mutex);
4603 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) {
4604 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
4606 if(!mesh || !channel) {
4607 meshlink_errno = MESHLINK_EINVAL;
4611 if(!len || fd == -1) {
4612 meshlink_errno = MESHLINK_EINVAL;
4616 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4622 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4626 /* Append the AIO buffer descriptor to the end of the chain */
4627 meshlink_aio_buffer_t **p = &channel->aio_receive;
4635 pthread_mutex_unlock(&mesh->mutex);
4640 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4641 if(!mesh || !channel) {
4642 meshlink_errno = MESHLINK_EINVAL;
4646 return channel->c->flags;
4649 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4650 if(!mesh || !channel) {
4651 meshlink_errno = MESHLINK_EINVAL;
4655 return utcp_get_sendq(channel->c);
4658 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4659 if(!mesh || !channel) {
4660 meshlink_errno = MESHLINK_EINVAL;
4664 return utcp_get_recvq(channel->c);
4667 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4668 if(!mesh || !channel) {
4669 meshlink_errno = MESHLINK_EINVAL;
4673 return utcp_get_mss(channel->node->utcp);
4676 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
4677 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
4679 if(!mesh || !node) {
4680 meshlink_errno = MESHLINK_EINVAL;
4684 node_t *n = (node_t *)node;
4686 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4691 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4692 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4693 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4696 utcp_set_user_timeout(n->utcp, timeout);
4698 pthread_mutex_unlock(&mesh->mutex);
4701 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4702 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4703 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4704 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4705 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4708 if(mesh->node_status_cb) {
4709 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4712 if(mesh->node_pmtu_cb) {
4713 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4717 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4718 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4720 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4721 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4725 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4726 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4730 n->status.duplicate = true;
4731 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4734 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4735 logger(mesh, MESHLINK_DEBUG, "meshlink_enable_discovery(%d)", enable);
4738 meshlink_errno = MESHLINK_EINVAL;
4742 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4746 if(mesh->discovery.enabled == enable) {
4750 if(mesh->threadstarted) {
4752 discovery_start(mesh);
4754 discovery_stop(mesh);
4758 mesh->discovery.enabled = enable;
4761 pthread_mutex_unlock(&mesh->mutex);
4764 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
4765 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
4768 meshlink_errno = MESHLINK_EINVAL;
4772 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4776 if(mesh->discovery.enabled) {
4780 if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
4781 mesh->discovery.last_update = mesh->loop.now.tv_sec;
4782 handle_network_change(mesh, 1);
4785 pthread_mutex_unlock(&mesh->mutex);
4788 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4789 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
4791 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4792 meshlink_errno = EINVAL;
4796 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4797 meshlink_errno = EINVAL;
4801 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4805 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4806 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4807 pthread_mutex_unlock(&mesh->mutex);
4810 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4811 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
4813 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4814 meshlink_errno = EINVAL;
4818 if(fast_retry_period < 0) {
4819 meshlink_errno = EINVAL;
4823 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4827 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4828 pthread_mutex_unlock(&mesh->mutex);
4831 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
4832 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
4834 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4835 meshlink_errno = EINVAL;
4839 if(maxtimeout < 0) {
4840 meshlink_errno = EINVAL;
4844 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4848 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
4849 pthread_mutex_unlock(&mesh->mutex);
4852 void meshlink_reset_timers(struct meshlink_handle *mesh) {
4853 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
4859 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4863 handle_network_change(mesh, true);
4865 if(mesh->discovery.enabled) {
4866 discovery_refresh(mesh);
4869 pthread_mutex_unlock(&mesh->mutex);
4872 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4873 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
4876 meshlink_errno = EINVAL;
4880 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4884 mesh->inviter_commits_first = inviter_commits_first;
4885 pthread_mutex_unlock(&mesh->mutex);
4888 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4889 logger(mesh, MESHLINK_DEBUG, "meshlink_set_external_address_discovery_url(%s)", url ? url : "(null)");
4892 meshlink_errno = EINVAL;
4896 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4897 meshlink_errno = EINVAL;
4901 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4905 free(mesh->external_address_url);
4906 mesh->external_address_url = url ? xstrdup(url) : NULL;
4907 pthread_mutex_unlock(&mesh->mutex);
4910 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4911 logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
4913 if(!mesh || granularity < 0) {
4914 meshlink_errno = EINVAL;
4918 utcp_set_clock_granularity(granularity);
4921 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
4922 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
4925 meshlink_errno = EINVAL;
4929 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4933 mesh->storage_policy = policy;
4934 pthread_mutex_unlock(&mesh->mutex);
4937 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4940 if(!mesh->connections || !mesh->loop.running) {
4945 signal_trigger(&mesh->loop, &mesh->datafromapp);
4948 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
4949 // We should only call the callback function if we are in the background thread.
4950 if(!mesh->error_cb) {
4954 if(!mesh->threadstarted) {
4958 if(mesh->thread == pthread_self()) {
4959 mesh->error_cb(mesh, cb_errno);
4963 static void __attribute__((constructor)) meshlink_init(void) {
4965 utcp_set_clock_granularity(10000);
4968 static void __attribute__((destructor)) meshlink_exit(void) {