2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2018 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.
26 #include "meshlink_internal.h"
37 #include "ed25519/sha512.h"
38 #include "discovery.h"
43 #define MSG_NOSIGNAL 0
45 __thread meshlink_errno_t meshlink_errno;
46 meshlink_log_cb_t global_log_cb;
47 meshlink_log_level_t global_log_level;
49 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
51 static int rstrip(char *value) {
52 int len = strlen(value);
54 while(len && strchr("\t\r\n ", value[len - 1])) {
61 static void get_canonical_address(node_t *n, char **hostname, char **port) {
62 if(!n->canonical_address) {
66 *hostname = xstrdup(n->canonical_address);
67 char *space = strchr(*hostname, ' ');
71 *port = xstrdup(space);
75 static bool is_valid_hostname(const char *hostname) {
80 for(const char *p = hostname; *p; p++) {
81 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
89 static bool is_valid_port(const char *port) {
96 unsigned long int result = strtoul(port, &end, 10);
97 return result && result < 65536 && !*end;
100 for(const char *p = port; *p; p++) {
101 if(!(isalnum(*p) || *p == '-')) {
109 static void set_timeout(int sock, int timeout) {
114 tv.tv_sec = timeout / 1000;
115 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
117 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
118 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
121 struct socket_in_netns_params {
130 static void *socket_in_netns_thread(void *arg) {
131 struct socket_in_netns_params *params = arg;
133 if(setns(params->netns, CLONE_NEWNET) == -1) {
134 meshlink_errno = MESHLINK_EINVAL;
138 params->fd = socket(params->domain, params->type, params->protocol);
144 static int socket_in_netns(int domain, int type, int protocol, int netns) {
146 return socket(domain, type, protocol);
150 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
154 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
155 pthread_join(thr, NULL);
165 // Find out what local address a socket would use if we connect to the given address.
166 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
167 // of both endpoints, but this will actually not send any UDP packet.
168 static bool getlocaladdr(char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
169 struct addrinfo *rai = NULL;
170 const struct addrinfo hint = {
171 .ai_family = AF_UNSPEC,
172 .ai_socktype = SOCK_DGRAM,
173 .ai_protocol = IPPROTO_UDP,
176 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
180 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
187 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
195 if(getsockname(sock, &sa->sa, salen)) {
204 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
206 socklen_t salen = sizeof(sa);
208 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
212 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
219 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
220 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
223 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
224 char *hostname = NULL;
226 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
227 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
228 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
231 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
232 if(family != AF_UNSPEC && aip->ai_family != family) {
236 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
239 set_timeout(s, 5000);
241 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
248 send(s, request, sizeof(request) - 1, 0);
249 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
254 if(line[len - 1] == '\n') {
258 char *p = strrchr(line, '\n');
261 hostname = xstrdup(p + 1);
277 // Check that the hostname is reasonable
278 if(hostname && !is_valid_hostname(hostname)) {
284 meshlink_errno = MESHLINK_ERESOLV;
290 static bool is_localaddr(sockaddr_t *sa) {
291 switch(sa->sa.sa_family) {
293 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
296 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
297 return first == 0 || (first & 0xffc0) == 0xfe80;
305 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
308 // Determine address of the local interface used for outgoing connections.
309 char localaddr[NI_MAXHOST];
310 bool success = false;
312 if(family == AF_INET) {
313 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
314 } else if(family == AF_INET6) {
315 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
318 #ifdef HAVE_GETIFADDRS
321 struct ifaddrs *ifa = NULL;
324 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
325 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
327 if(sa->sa.sa_family != family) {
331 if(is_localaddr(sa)) {
335 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
347 meshlink_errno = MESHLINK_ENETWORK;
351 return xstrdup(localaddr);
354 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
355 for(int i = 0; i < n; i++) {
360 // Ignore duplicate hostnames
363 for(int j = 0; j < i; j++) {
368 if(strcmp(host[i], host[j])) {
372 if(strcmp(port[i], port[j])) {
380 if(found || !is_valid_hostname(host[i])) {
390 // This gets the hostname part for use in invitation URLs
391 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
392 char *hostname[4] = {NULL};
393 char *port[4] = {NULL};
394 char *hostport = NULL;
396 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
397 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
400 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
401 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
404 // Add local addresses if requested
405 if(flags & MESHLINK_INVITE_LOCAL) {
406 if(flags & MESHLINK_INVITE_IPV4) {
407 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
410 if(flags & MESHLINK_INVITE_IPV6) {
411 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
415 // Add public/canonical addresses if requested
416 if(flags & MESHLINK_INVITE_PUBLIC) {
417 // Try the CanonicalAddress first
418 get_canonical_address(mesh->self, &hostname[2], &port[2]);
421 if(flags & MESHLINK_INVITE_IPV4) {
422 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
425 if(flags & MESHLINK_INVITE_IPV6) {
426 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
431 for(int i = 0; i < 4; i++) {
432 // Ensure we always have a port number
433 if(hostname[i] && !port[i]) {
434 port[i] = xstrdup(mesh->myport);
438 remove_duplicate_hostnames(hostname, port, 4);
440 // Resolve the hostnames
441 for(int i = 0; i < 4; i++) {
446 // Convert what we have to a sockaddr
447 struct addrinfo *ai_in, *ai_out;
448 struct addrinfo hint = {
449 .ai_family = AF_UNSPEC,
450 .ai_flags = AI_NUMERICSERV,
451 .ai_socktype = SOCK_STREAM,
453 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
459 // Remember the address
460 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)ai_in->ai_addr);
462 if(flags & MESHLINK_INVITE_NUMERIC) {
463 // We don't need to do any further conversion
468 // Convert it to a hostname
469 char resolved_host[NI_MAXHOST];
470 char resolved_port[NI_MAXSERV];
471 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
473 if(err || !is_valid_hostname(resolved_host)) {
478 // Convert the hostname back to a sockaddr
479 hint.ai_family = ai_in->ai_family;
480 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
487 // Check if it's still the same sockaddr
488 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
490 freeaddrinfo(ai_out);
494 // Yes: replace the hostname with the resolved one
496 hostname[i] = xstrdup(resolved_host);
499 freeaddrinfo(ai_out);
502 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
503 remove_duplicate_hostnames(hostname, port, 4);
505 // Concatenate all unique address to the hostport string
506 for(int i = 0; i < 4; i++) {
511 // Append the address to the hostport string
513 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
515 hostport = newhostport;
524 static bool try_bind(int port) {
525 struct addrinfo *ai = NULL;
526 struct addrinfo hint = {
527 .ai_flags = AI_PASSIVE,
528 .ai_family = AF_UNSPEC,
529 .ai_socktype = SOCK_STREAM,
530 .ai_protocol = IPPROTO_TCP,
534 snprintf(portstr, sizeof(portstr), "%d", port);
536 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
540 bool success = false;
542 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
543 if(!(aip->ai_family == AF_INET || aip->ai_family == AF_INET6)) {
547 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
554 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
569 static int check_port(meshlink_handle_t *mesh) {
570 for(int i = 0; i < 1000; i++) {
571 int port = 0x1000 + prng(mesh, 0x8000);
575 xasprintf(&mesh->myport, "%d", port);
580 meshlink_errno = MESHLINK_ENETWORK;
581 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
585 static bool write_main_config_files(meshlink_handle_t *mesh) {
586 if(!mesh->confbase) {
592 /* Write the main config file */
593 packmsg_output_t out = {buf, sizeof buf};
595 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
596 packmsg_add_str(&out, mesh->name);
597 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
598 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
599 packmsg_add_uint16(&out, atoi(mesh->myport));
601 if(!packmsg_output_ok(&out)) {
605 config_t config = {buf, packmsg_output_size(&out, buf)};
607 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
611 /* Write our own host config file */
612 if(!node_write_config(mesh, mesh->self)) {
620 meshlink_handle_t *mesh;
622 char cookie[18 + 32];
633 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
634 meshlink_handle_t *mesh = state->mesh;
635 packmsg_input_t in = {buf, len};
636 uint32_t version = packmsg_get_uint32(&in);
638 if(version != MESHLINK_INVITATION_VERSION) {
639 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
643 char *name = packmsg_get_str_dup(&in);
644 packmsg_skip_element(&in); /* submesh */
645 dev_class_t devclass = packmsg_get_int32(&in);
646 uint32_t count = packmsg_get_array(&in);
649 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
653 if(!check_id(name)) {
654 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
660 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
666 free(mesh->self->name);
668 mesh->self->name = xstrdup(name);
669 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
671 // Initialize configuration directory
672 if(!config_init(mesh, "current")) {
676 if(!write_main_config_files(mesh)) {
680 // Write host config files
681 for(uint32_t i = 0; i < count; i++) {
683 uint32_t len = packmsg_get_bin_raw(&in, &data);
686 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
690 packmsg_input_t in2 = {data, len};
691 uint32_t version = packmsg_get_uint32(&in2);
692 char *name = packmsg_get_str_dup(&in2);
694 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
696 packmsg_input_invalidate(&in);
700 if(!check_id(name)) {
705 if(!strcmp(name, mesh->name)) {
706 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
708 meshlink_errno = MESHLINK_EPEER;
712 node_t *n = new_node();
715 config_t config = {data, len};
717 if(!node_read_from_config(mesh, n, &config)) {
719 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
720 meshlink_errno = MESHLINK_EPEER;
725 /* The first host config file is of the inviter itself;
726 * remember the address we are currently using for the invitation connection.
729 socklen_t salen = sizeof(sa);
731 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
732 node_add_recent_address(mesh, n, &sa);
736 /* Clear the reachability times, since we ourself have never seen these nodes yet */
737 n->last_reachable = 0;
738 n->last_unreachable = 0;
740 if(!node_write_config(mesh, n)) {
748 /* Ensure the configuration directory metadata is on disk */
749 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
753 if(!mesh->inviter_commits_first) {
754 devtool_set_inviter_commits_first(false);
757 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
759 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
764 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
766 join_state_t *state = handle;
767 const char *ptr = data;
770 int result = send(state->sock, ptr, len, 0);
772 if(result == -1 && errno == EINTR) {
774 } else if(result <= 0) {
785 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
786 join_state_t *state = handle;
787 meshlink_handle_t *mesh = state->mesh;
789 if(mesh->inviter_commits_first) {
791 case SPTPS_HANDSHAKE:
792 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
798 if(!finalize_join(state, msg, len)) {
802 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
803 shutdown(state->sock, SHUT_RDWR);
804 state->success = true;
812 case SPTPS_HANDSHAKE:
813 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
816 return finalize_join(state, msg, len);
819 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
820 shutdown(state->sock, SHUT_RDWR);
821 state->success = true;
832 static bool recvline(join_state_t *state) {
833 char *newline = NULL;
835 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
836 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
838 if(result == -1 && errno == EINTR) {
840 } else if(result <= 0) {
844 state->blen += result;
847 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
851 size_t len = newline - state->buffer;
853 memcpy(state->line, state->buffer, len);
854 state->line[len] = 0;
855 memmove(state->buffer, newline + 1, state->blen - len - 1);
856 state->blen -= len + 1;
861 static bool sendline(int fd, char *format, ...) {
867 va_start(ap, format);
868 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
871 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
879 int result = send(fd, p, blen, MSG_NOSIGNAL);
881 if(result == -1 && errno == EINTR) {
883 } else if(result <= 0) {
894 static const char *errstr[] = {
895 [MESHLINK_OK] = "No error",
896 [MESHLINK_EINVAL] = "Invalid argument",
897 [MESHLINK_ENOMEM] = "Out of memory",
898 [MESHLINK_ENOENT] = "No such node",
899 [MESHLINK_EEXIST] = "Node already exists",
900 [MESHLINK_EINTERNAL] = "Internal error",
901 [MESHLINK_ERESOLV] = "Could not resolve hostname",
902 [MESHLINK_ESTORAGE] = "Storage error",
903 [MESHLINK_ENETWORK] = "Network error",
904 [MESHLINK_EPEER] = "Error communicating with peer",
905 [MESHLINK_ENOTSUP] = "Operation not supported",
906 [MESHLINK_EBUSY] = "MeshLink instance already in use",
907 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
910 const char *meshlink_strerror(meshlink_errno_t err) {
911 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
912 return "Invalid error code";
918 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
919 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
921 mesh->private_key = ecdsa_generate();
922 mesh->invitation_key = ecdsa_generate();
924 if(!mesh->private_key || !mesh->invitation_key) {
925 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
926 meshlink_errno = MESHLINK_EINTERNAL;
930 logger(mesh, MESHLINK_DEBUG, "Done.\n");
935 static struct timeval idle(event_loop_t *loop, void *data) {
937 meshlink_handle_t *mesh = data;
938 struct timeval t, tmin = {3600, 0};
940 for splay_each(node_t, n, mesh->nodes) {
945 t = utcp_timeout(n->utcp);
947 if(timercmp(&t, &tmin, <)) {
955 // Get our local address(es) by simulating connecting to an Internet host.
956 static void add_local_addresses(meshlink_handle_t *mesh) {
958 sa.storage.ss_family = AF_UNKNOWN;
959 socklen_t salen = sizeof(sa);
963 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
964 sa.in.sin_port = ntohs(atoi(mesh->myport));
965 node_add_recent_address(mesh, mesh->self, &sa);
972 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
973 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
974 node_add_recent_address(mesh, mesh->self, &sa);
978 static bool meshlink_setup(meshlink_handle_t *mesh) {
979 if(!config_destroy(mesh->confbase, "new")) {
980 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
981 meshlink_errno = MESHLINK_ESTORAGE;
985 if(!config_destroy(mesh->confbase, "old")) {
986 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
987 meshlink_errno = MESHLINK_ESTORAGE;
991 if(!config_init(mesh, "current")) {
992 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
993 meshlink_errno = MESHLINK_ESTORAGE;
997 if(!ecdsa_keygen(mesh)) {
998 meshlink_errno = MESHLINK_EINTERNAL;
1002 if(check_port(mesh) == 0) {
1003 meshlink_errno = MESHLINK_ENETWORK;
1007 /* Create a node for ourself */
1009 mesh->self = new_node();
1010 mesh->self->name = xstrdup(mesh->name);
1011 mesh->self->devclass = mesh->devclass;
1012 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1013 mesh->self->session_id = mesh->session_id;
1015 if(!write_main_config_files(mesh)) {
1016 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1017 meshlink_errno = MESHLINK_ESTORAGE;
1021 /* Ensure the configuration directory metadata is on disk */
1022 if(!config_sync(mesh, "current")) {
1029 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1032 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1033 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1037 packmsg_input_t in = {config.buf, config.len};
1038 const void *private_key;
1039 const void *invitation_key;
1041 uint32_t version = packmsg_get_uint32(&in);
1042 char *name = packmsg_get_str_dup(&in);
1043 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1044 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1045 uint16_t myport = packmsg_get_uint16(&in);
1047 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1048 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1050 config_free(&config);
1056 // TODO: check this?
1057 if(mesh->name && strcmp(mesh->name, name)) {
1058 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1059 meshlink_errno = MESHLINK_ESTORAGE;
1061 config_free(&config);
1069 xasprintf(&mesh->myport, "%u", myport);
1070 mesh->private_key = ecdsa_set_private_key(private_key);
1071 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1072 config_free(&config);
1074 /* Create a node for ourself and read our host configuration file */
1076 mesh->self = new_node();
1077 mesh->self->name = xstrdup(name);
1078 mesh->self->devclass = mesh->devclass;
1079 mesh->self->session_id = mesh->session_id;
1081 if(!node_read_public_key(mesh, mesh->self)) {
1082 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1083 meshlink_errno = MESHLINK_ESTORAGE;
1084 free_node(mesh->self);
1093 static void *setup_network_in_netns_thread(void *arg) {
1094 meshlink_handle_t *mesh = arg;
1096 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1100 bool success = setup_network(mesh);
1101 add_local_addresses(mesh);
1102 return success ? arg : NULL;
1104 #endif // HAVE_SETNS
1106 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1107 if(!confbase || !*confbase) {
1108 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1109 meshlink_errno = MESHLINK_EINVAL;
1113 if(!appname || !*appname) {
1114 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1115 meshlink_errno = MESHLINK_EINVAL;
1119 if(strchr(appname, ' ')) {
1120 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1121 meshlink_errno = MESHLINK_EINVAL;
1125 if(!name || !*name) {
1126 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1127 meshlink_errno = MESHLINK_EINVAL;
1131 if(!check_id(name)) {
1132 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1133 meshlink_errno = MESHLINK_EINVAL;
1137 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1138 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1139 meshlink_errno = MESHLINK_EINVAL;
1143 meshlink_open_params_t *params = xzalloc(sizeof * params);
1145 params->confbase = xstrdup(confbase);
1146 params->name = xstrdup(name);
1147 params->appname = xstrdup(appname);
1148 params->devclass = devclass;
1154 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1156 meshlink_errno = MESHLINK_EINVAL;
1160 params->netns = netns;
1165 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1167 meshlink_errno = MESHLINK_EINVAL;
1171 if((!key && keylen) || (key && !keylen)) {
1172 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1173 meshlink_errno = MESHLINK_EINVAL;
1178 params->keylen = keylen;
1183 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1184 if(!mesh || !new_key || !new_keylen) {
1185 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1186 meshlink_errno = MESHLINK_EINVAL;
1190 pthread_mutex_lock(&mesh->mutex);
1192 // Create hash for the new key
1193 void *new_config_key;
1194 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1196 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1197 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1198 meshlink_errno = MESHLINK_EINTERNAL;
1199 pthread_mutex_unlock(&mesh->mutex);
1203 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1205 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1206 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1207 meshlink_errno = MESHLINK_ESTORAGE;
1208 pthread_mutex_unlock(&mesh->mutex);
1212 devtool_keyrotate_probe(1);
1214 // Rename confbase/current/ to confbase/old
1216 if(!config_rename(mesh, "current", "old")) {
1217 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1218 meshlink_errno = MESHLINK_ESTORAGE;
1219 pthread_mutex_unlock(&mesh->mutex);
1223 devtool_keyrotate_probe(2);
1225 // Rename confbase/new/ to confbase/current
1227 if(!config_rename(mesh, "new", "current")) {
1228 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1229 meshlink_errno = MESHLINK_ESTORAGE;
1230 pthread_mutex_unlock(&mesh->mutex);
1234 devtool_keyrotate_probe(3);
1236 // Cleanup the "old" confbase sub-directory
1238 if(!config_destroy(mesh->confbase, "old")) {
1239 pthread_mutex_unlock(&mesh->mutex);
1243 // Change the mesh handle key with new key
1245 free(mesh->config_key);
1246 mesh->config_key = new_config_key;
1248 pthread_mutex_unlock(&mesh->mutex);
1253 void meshlink_open_params_free(meshlink_open_params_t *params) {
1255 meshlink_errno = MESHLINK_EINVAL;
1259 free(params->confbase);
1261 free(params->appname);
1266 /// Device class traits
1267 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1268 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1269 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1270 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1271 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1274 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1275 if(!confbase || !*confbase) {
1276 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1277 meshlink_errno = MESHLINK_EINVAL;
1281 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1282 meshlink_open_params_t params;
1283 memset(¶ms, 0, sizeof(params));
1285 params.confbase = (char *)confbase;
1286 params.name = (char *)name;
1287 params.appname = (char *)appname;
1288 params.devclass = devclass;
1291 return meshlink_open_ex(¶ms);
1294 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) {
1295 if(!confbase || !*confbase) {
1296 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1297 meshlink_errno = MESHLINK_EINVAL;
1301 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1302 meshlink_open_params_t params;
1303 memset(¶ms, 0, sizeof(params));
1305 params.confbase = (char *)confbase;
1306 params.name = (char *)name;
1307 params.appname = (char *)appname;
1308 params.devclass = devclass;
1311 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1315 return meshlink_open_ex(¶ms);
1318 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1319 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1320 meshlink_open_params_t params;
1321 memset(¶ms, 0, sizeof(params));
1323 params.name = (char *)name;
1324 params.appname = (char *)appname;
1325 params.devclass = devclass;
1328 return meshlink_open_ex(¶ms);
1331 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1332 // Validate arguments provided by the application
1333 bool usingname = false;
1335 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1337 if(!params->appname || !*params->appname) {
1338 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1339 meshlink_errno = MESHLINK_EINVAL;
1343 if(strchr(params->appname, ' ')) {
1344 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1345 meshlink_errno = MESHLINK_EINVAL;
1349 if(!params->name || !*params->name) {
1350 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1352 } else { //check name only if there is a name != NULL
1354 if(!check_id(params->name)) {
1355 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1356 meshlink_errno = MESHLINK_EINVAL;
1363 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1364 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1365 meshlink_errno = MESHLINK_EINVAL;
1369 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1370 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1371 meshlink_errno = MESHLINK_EINVAL;
1375 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1377 if(params->confbase) {
1378 mesh->confbase = xstrdup(params->confbase);
1381 mesh->appname = xstrdup(params->appname);
1382 mesh->devclass = params->devclass;
1383 mesh->discovery = true;
1384 mesh->invitation_timeout = 604800; // 1 week
1385 mesh->netns = params->netns;
1386 mesh->submeshes = NULL;
1387 mesh->log_cb = global_log_cb;
1388 mesh->log_level = global_log_level;
1390 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1393 randomize(&mesh->session_id, sizeof(mesh->session_id));
1394 } while(mesh->session_id == 0);
1396 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1399 mesh->name = xstrdup(params->name);
1404 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1406 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1407 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1408 meshlink_close(mesh);
1409 meshlink_errno = MESHLINK_EINTERNAL;
1415 pthread_mutexattr_t attr;
1416 pthread_mutexattr_init(&attr);
1417 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1418 pthread_mutex_init(&mesh->mutex, &attr);
1420 mesh->threadstarted = false;
1421 event_loop_init(&mesh->loop);
1422 mesh->loop.data = mesh;
1424 meshlink_queue_init(&mesh->outpacketqueue);
1426 // Atomically lock the configuration directory.
1427 if(!main_config_lock(mesh)) {
1428 meshlink_close(mesh);
1432 // If no configuration exists yet, create it.
1434 if(!meshlink_confbase_exists(mesh)) {
1435 if(!meshlink_setup(mesh)) {
1436 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1437 meshlink_close(mesh);
1441 if(!meshlink_read_config(mesh)) {
1442 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1443 meshlink_close(mesh);
1449 struct WSAData wsa_state;
1450 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1453 // Setup up everything
1454 // TODO: we should not open listening sockets yet
1456 bool success = false;
1458 if(mesh->netns != -1) {
1462 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1463 void *retval = NULL;
1464 success = pthread_join(thr, &retval) == 0 && retval;
1468 meshlink_errno = MESHLINK_EINTERNAL;
1471 #endif // HAVE_SETNS
1473 success = setup_network(mesh);
1474 add_local_addresses(mesh);
1478 meshlink_close(mesh);
1479 meshlink_errno = MESHLINK_ENETWORK;
1483 add_local_addresses(mesh);
1485 if(!node_write_config(mesh, mesh->self)) {
1486 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1490 idle_set(&mesh->loop, idle, mesh);
1492 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1496 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1497 meshlink_submesh_t *s = NULL;
1500 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1501 meshlink_errno = MESHLINK_EINVAL;
1505 if(!submesh || !*submesh) {
1506 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1507 meshlink_errno = MESHLINK_EINVAL;
1512 pthread_mutex_lock(&mesh->mutex);
1514 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1516 pthread_mutex_unlock(&mesh->mutex);
1521 static void *meshlink_main_loop(void *arg) {
1522 meshlink_handle_t *mesh = arg;
1524 if(mesh->netns != -1) {
1527 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1528 pthread_cond_signal(&mesh->cond);
1533 pthread_cond_signal(&mesh->cond);
1535 #endif // HAVE_SETNS
1540 if(mesh->discovery) {
1541 discovery_start(mesh);
1546 pthread_mutex_lock(&mesh->mutex);
1548 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1549 pthread_cond_broadcast(&mesh->cond);
1551 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1553 pthread_mutex_unlock(&mesh->mutex);
1558 if(mesh->discovery) {
1559 discovery_stop(mesh);
1567 bool meshlink_start(meshlink_handle_t *mesh) {
1569 meshlink_errno = MESHLINK_EINVAL;
1573 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1575 pthread_mutex_lock(&mesh->mutex);
1578 assert(mesh->private_key);
1579 assert(mesh->self->ecdsa);
1580 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1582 if(mesh->threadstarted) {
1583 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1584 pthread_mutex_unlock(&mesh->mutex);
1588 if(mesh->listen_socket[0].tcp.fd < 0) {
1589 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1590 meshlink_errno = MESHLINK_ENETWORK;
1594 // TODO: open listening sockets first
1596 //Check that a valid name is set
1598 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1599 meshlink_errno = MESHLINK_EINVAL;
1600 pthread_mutex_unlock(&mesh->mutex);
1604 init_outgoings(mesh);
1606 // Start the main thread
1608 event_loop_start(&mesh->loop);
1610 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1611 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1612 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1613 meshlink_errno = MESHLINK_EINTERNAL;
1614 event_loop_stop(&mesh->loop);
1615 pthread_mutex_unlock(&mesh->mutex);
1619 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1620 mesh->threadstarted = true;
1622 // Ensure we are considered reachable
1625 pthread_mutex_unlock(&mesh->mutex);
1629 void meshlink_stop(meshlink_handle_t *mesh) {
1631 meshlink_errno = MESHLINK_EINVAL;
1635 pthread_mutex_lock(&mesh->mutex);
1636 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1638 // Shut down the main thread
1639 event_loop_stop(&mesh->loop);
1641 // Send ourselves a UDP packet to kick the event loop
1642 for(int i = 0; i < mesh->listen_sockets; i++) {
1644 socklen_t salen = sizeof(sa);
1646 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1647 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1651 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1652 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1656 if(mesh->threadstarted) {
1657 // Wait for the main thread to finish
1658 pthread_mutex_unlock(&mesh->mutex);
1659 pthread_join(mesh->thread, NULL);
1660 pthread_mutex_lock(&mesh->mutex);
1662 mesh->threadstarted = false;
1665 // Close all metaconnections
1666 if(mesh->connections) {
1667 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1669 connection_t *c = node->data;
1671 terminate_connection(mesh, c, false);
1675 exit_outgoings(mesh);
1677 // Ensure we are considered unreachable
1682 // Try to write out any changed node config files, ignore errors at this point.
1684 for splay_each(node_t, n, mesh->nodes) {
1685 if(n->status.dirty) {
1686 n->status.dirty = !node_write_config(mesh, n);
1691 pthread_mutex_unlock(&mesh->mutex);
1694 void meshlink_close(meshlink_handle_t *mesh) {
1696 meshlink_errno = MESHLINK_EINVAL;
1700 // stop can be called even if mesh has not been started
1701 meshlink_stop(mesh);
1703 // lock is not released after this
1704 pthread_mutex_lock(&mesh->mutex);
1706 // Close and free all resources used.
1708 close_network_connections(mesh);
1710 logger(mesh, MESHLINK_INFO, "Terminating");
1712 event_loop_exit(&mesh->loop);
1716 if(mesh->confbase) {
1722 ecdsa_free(mesh->invitation_key);
1724 if(mesh->netns != -1) {
1728 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1732 meshlink_queue_exit(&mesh->outpacketqueue);
1735 free(mesh->appname);
1736 free(mesh->confbase);
1737 free(mesh->config_key);
1738 ecdsa_free(mesh->private_key);
1740 main_config_unlock(mesh);
1742 pthread_mutex_unlock(&mesh->mutex);
1743 pthread_mutex_destroy(&mesh->mutex);
1745 memset(mesh, 0, sizeof(*mesh));
1750 bool meshlink_destroy(const char *confbase) {
1752 meshlink_errno = MESHLINK_EINVAL;
1756 /* Exit early if the confbase directory itself doesn't exist */
1757 if(access(confbase, F_OK) && errno == ENOENT) {
1761 /* Take the lock the same way meshlink_open() would. */
1762 char lockfilename[PATH_MAX];
1763 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1765 FILE *lockfile = fopen(lockfilename, "w+");
1768 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1769 meshlink_errno = MESHLINK_ESTORAGE;
1774 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1778 // TODO: use _locking()?
1781 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1782 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1784 meshlink_errno = MESHLINK_EBUSY;
1790 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1791 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1795 if(unlink(lockfilename)) {
1796 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1798 meshlink_errno = MESHLINK_ESTORAGE;
1804 if(!sync_path(confbase)) {
1805 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1806 meshlink_errno = MESHLINK_ESTORAGE;
1813 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1815 meshlink_errno = MESHLINK_EINVAL;
1819 pthread_mutex_lock(&mesh->mutex);
1820 mesh->receive_cb = cb;
1821 pthread_mutex_unlock(&mesh->mutex);
1824 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1826 meshlink_errno = MESHLINK_EINVAL;
1830 pthread_mutex_lock(&mesh->mutex);
1831 mesh->connection_try_cb = cb;
1832 pthread_mutex_unlock(&mesh->mutex);
1835 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1837 meshlink_errno = MESHLINK_EINVAL;
1841 pthread_mutex_lock(&mesh->mutex);
1842 mesh->node_status_cb = cb;
1843 pthread_mutex_unlock(&mesh->mutex);
1846 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1848 meshlink_errno = MESHLINK_EINVAL;
1852 pthread_mutex_lock(&mesh->mutex);
1853 mesh->node_pmtu_cb = cb;
1854 pthread_mutex_unlock(&mesh->mutex);
1857 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1859 meshlink_errno = MESHLINK_EINVAL;
1863 pthread_mutex_lock(&mesh->mutex);
1864 mesh->node_duplicate_cb = cb;
1865 pthread_mutex_unlock(&mesh->mutex);
1868 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1870 pthread_mutex_lock(&mesh->mutex);
1872 mesh->log_level = cb ? level : 0;
1873 pthread_mutex_unlock(&mesh->mutex);
1876 global_log_level = cb ? level : 0;
1880 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1882 meshlink_errno = MESHLINK_EINVAL;
1886 pthread_mutex_lock(&mesh->mutex);
1887 mesh->error_cb = cb;
1888 pthread_mutex_unlock(&mesh->mutex);
1891 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1892 meshlink_packethdr_t *hdr;
1894 // Validate arguments
1895 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1896 meshlink_errno = MESHLINK_EINVAL;
1905 meshlink_errno = MESHLINK_EINVAL;
1909 node_t *n = (node_t *)destination;
1911 if(n->status.blacklisted) {
1912 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1913 meshlink_errno = MESHLINK_EBLACKLISTED;
1917 // Prepare the packet
1918 vpn_packet_t *packet = malloc(sizeof(*packet));
1921 meshlink_errno = MESHLINK_ENOMEM;
1925 packet->probe = false;
1926 packet->tcp = false;
1927 packet->len = len + sizeof(*hdr);
1929 hdr = (meshlink_packethdr_t *)packet->data;
1930 memset(hdr, 0, sizeof(*hdr));
1931 // leave the last byte as 0 to make sure strings are always
1932 // null-terminated if they are longer than the buffer
1933 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1934 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1936 memcpy(packet->data + sizeof(*hdr), data, len);
1939 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1941 meshlink_errno = MESHLINK_ENOMEM;
1945 // Notify event loop
1946 signal_trigger(&mesh->loop, &mesh->datafromapp);
1951 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1953 meshlink_handle_t *mesh = data;
1954 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1960 mesh->self->in_packets++;
1961 mesh->self->in_bytes += packet->len;
1962 route(mesh, mesh->self, packet);
1967 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1968 if(!mesh || !destination) {
1969 meshlink_errno = MESHLINK_EINVAL;
1973 pthread_mutex_lock(&mesh->mutex);
1975 node_t *n = (node_t *)destination;
1977 if(!n->status.reachable) {
1978 pthread_mutex_unlock(&mesh->mutex);
1981 } else if(n->mtuprobes > 30 && n->minmtu) {
1982 pthread_mutex_unlock(&mesh->mutex);
1985 pthread_mutex_unlock(&mesh->mutex);
1990 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1991 if(!mesh || !node) {
1992 meshlink_errno = MESHLINK_EINVAL;
1996 pthread_mutex_lock(&mesh->mutex);
1998 node_t *n = (node_t *)node;
2000 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2001 meshlink_errno = MESHLINK_EINTERNAL;
2002 pthread_mutex_unlock(&mesh->mutex);
2006 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2009 meshlink_errno = MESHLINK_EINTERNAL;
2012 pthread_mutex_unlock(&mesh->mutex);
2016 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2018 meshlink_errno = MESHLINK_EINVAL;
2022 return (meshlink_node_t *)mesh->self;
2025 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2026 if(!mesh || !name) {
2027 meshlink_errno = MESHLINK_EINVAL;
2033 pthread_mutex_lock(&mesh->mutex);
2034 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2035 pthread_mutex_unlock(&mesh->mutex);
2038 meshlink_errno = MESHLINK_ENOENT;
2041 return (meshlink_node_t *)n;
2044 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2045 if(!mesh || !name) {
2046 meshlink_errno = MESHLINK_EINVAL;
2050 meshlink_submesh_t *submesh = NULL;
2052 pthread_mutex_lock(&mesh->mutex);
2053 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2054 pthread_mutex_unlock(&mesh->mutex);
2057 meshlink_errno = MESHLINK_ENOENT;
2063 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2064 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2065 meshlink_errno = MESHLINK_EINVAL;
2069 meshlink_node_t **result;
2072 pthread_mutex_lock(&mesh->mutex);
2074 *nmemb = mesh->nodes->count;
2075 result = realloc(nodes, *nmemb * sizeof(*nodes));
2078 meshlink_node_t **p = result;
2080 for splay_each(node_t, n, mesh->nodes) {
2081 *p++ = (meshlink_node_t *)n;
2086 meshlink_errno = MESHLINK_ENOMEM;
2089 pthread_mutex_unlock(&mesh->mutex);
2094 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) {
2095 meshlink_node_t **result;
2097 pthread_mutex_lock(&mesh->mutex);
2101 for splay_each(node_t, n, mesh->nodes) {
2102 if(search_node(n, condition)) {
2109 pthread_mutex_unlock(&mesh->mutex);
2113 result = realloc(nodes, *nmemb * sizeof(*nodes));
2116 meshlink_node_t **p = result;
2118 for splay_each(node_t, n, mesh->nodes) {
2119 if(search_node(n, condition)) {
2120 *p++ = (meshlink_node_t *)n;
2126 meshlink_errno = MESHLINK_ENOMEM;
2129 pthread_mutex_unlock(&mesh->mutex);
2134 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2135 dev_class_t *devclass = (dev_class_t *)condition;
2137 if(*devclass == (dev_class_t)node->devclass) {
2144 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2145 if(condition == node->submesh) {
2157 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2158 const struct time_range *range = condition;
2159 time_t start = node->last_reachable;
2160 time_t end = node->last_unreachable;
2170 if(range->end >= range->start) {
2171 return start <= range->end && end >= range->start;
2173 return start > range->start || end < range->end;
2177 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) {
2178 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2179 meshlink_errno = MESHLINK_EINVAL;
2183 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2186 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2187 if(!mesh || !submesh || !nmemb) {
2188 meshlink_errno = MESHLINK_EINVAL;
2192 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2195 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) {
2196 if(!mesh || !nmemb) {
2197 meshlink_errno = MESHLINK_EINVAL;
2201 struct time_range range = {start, end};
2203 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2206 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2207 if(!mesh || !node) {
2208 meshlink_errno = MESHLINK_EINVAL;
2212 dev_class_t devclass;
2214 pthread_mutex_lock(&mesh->mutex);
2216 devclass = ((node_t *)node)->devclass;
2218 pthread_mutex_unlock(&mesh->mutex);
2223 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2224 if(!mesh || !node) {
2225 meshlink_errno = MESHLINK_EINVAL;
2229 node_t *n = (node_t *)node;
2231 meshlink_submesh_t *s;
2233 s = (meshlink_submesh_t *)n->submesh;
2238 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2239 if(!mesh || !node) {
2240 meshlink_errno = MESHLINK_EINVAL;
2244 node_t *n = (node_t *)node;
2247 pthread_mutex_lock(&mesh->mutex);
2248 reachable = n->status.reachable && !n->status.blacklisted;
2250 if(last_reachable) {
2251 *last_reachable = n->last_reachable;
2254 if(last_unreachable) {
2255 *last_unreachable = n->last_unreachable;
2258 pthread_mutex_unlock(&mesh->mutex);
2263 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2264 if(!mesh || !data || !len || !signature || !siglen) {
2265 meshlink_errno = MESHLINK_EINVAL;
2269 if(*siglen < MESHLINK_SIGLEN) {
2270 meshlink_errno = MESHLINK_EINVAL;
2274 pthread_mutex_lock(&mesh->mutex);
2276 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2277 meshlink_errno = MESHLINK_EINTERNAL;
2278 pthread_mutex_unlock(&mesh->mutex);
2282 *siglen = MESHLINK_SIGLEN;
2283 pthread_mutex_unlock(&mesh->mutex);
2287 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2288 if(!mesh || !source || !data || !len || !signature) {
2289 meshlink_errno = MESHLINK_EINVAL;
2293 if(siglen != MESHLINK_SIGLEN) {
2294 meshlink_errno = MESHLINK_EINVAL;
2298 pthread_mutex_lock(&mesh->mutex);
2302 struct node_t *n = (struct node_t *)source;
2304 if(!node_read_public_key(mesh, n)) {
2305 meshlink_errno = MESHLINK_EINTERNAL;
2308 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2311 pthread_mutex_unlock(&mesh->mutex);
2315 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2316 pthread_mutex_lock(&mesh->mutex);
2318 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2321 // TODO: Update invitation key if necessary?
2324 pthread_mutex_unlock(&mesh->mutex);
2326 return mesh->invitation_key;
2329 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2330 if(!mesh || !node || !address) {
2331 meshlink_errno = MESHLINK_EINVAL;
2335 if(!is_valid_hostname(address)) {
2336 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2337 meshlink_errno = MESHLINK_EINVAL;
2341 if(port && !is_valid_port(port)) {
2342 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2343 meshlink_errno = MESHLINK_EINVAL;
2347 char *canonical_address;
2350 xasprintf(&canonical_address, "%s %s", address, port);
2352 canonical_address = xstrdup(address);
2355 pthread_mutex_lock(&mesh->mutex);
2357 node_t *n = (node_t *)node;
2358 free(n->canonical_address);
2359 n->canonical_address = canonical_address;
2361 if(!node_write_config(mesh, n)) {
2362 pthread_mutex_unlock(&mesh->mutex);
2366 pthread_mutex_unlock(&mesh->mutex);
2368 return config_sync(mesh, "current");
2371 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2372 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2375 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2377 meshlink_errno = MESHLINK_EINVAL;
2381 char *address = meshlink_get_external_address(mesh);
2387 bool rval = meshlink_add_address(mesh, address);
2393 int meshlink_get_port(meshlink_handle_t *mesh) {
2395 meshlink_errno = MESHLINK_EINVAL;
2400 meshlink_errno = MESHLINK_EINTERNAL;
2406 pthread_mutex_lock(&mesh->mutex);
2407 port = atoi(mesh->myport);
2408 pthread_mutex_unlock(&mesh->mutex);
2413 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2414 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2415 meshlink_errno = MESHLINK_EINVAL;
2419 if(mesh->myport && port == atoi(mesh->myport)) {
2423 if(!try_bind(port)) {
2424 meshlink_errno = MESHLINK_ENETWORK;
2428 devtool_trybind_probe();
2432 pthread_mutex_lock(&mesh->mutex);
2434 if(mesh->threadstarted) {
2435 meshlink_errno = MESHLINK_EINVAL;
2440 xasprintf(&mesh->myport, "%d", port);
2442 /* Close down the network. This also deletes mesh->self. */
2443 close_network_connections(mesh);
2445 /* Recreate mesh->self. */
2446 mesh->self = new_node();
2447 mesh->self->name = xstrdup(mesh->name);
2448 mesh->self->devclass = mesh->devclass;
2449 mesh->self->session_id = mesh->session_id;
2450 xasprintf(&mesh->myport, "%d", port);
2452 if(!node_read_public_key(mesh, mesh->self)) {
2453 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2454 meshlink_errno = MESHLINK_ESTORAGE;
2455 free_node(mesh->self);
2458 } else if(!setup_network(mesh)) {
2459 meshlink_errno = MESHLINK_ENETWORK;
2463 /* Rebuild our own list of recent addresses */
2464 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2465 add_local_addresses(mesh);
2467 /* Write meshlink.conf with the updated port number */
2468 write_main_config_files(mesh);
2470 rval = config_sync(mesh, "current");
2473 pthread_mutex_unlock(&mesh->mutex);
2475 return rval && meshlink_get_port(mesh) == port;
2478 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2479 mesh->invitation_timeout = timeout;
2482 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2483 meshlink_submesh_t *s = NULL;
2486 meshlink_errno = MESHLINK_EINVAL;
2491 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2494 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2495 meshlink_errno = MESHLINK_EINVAL;
2499 s = (meshlink_submesh_t *)mesh->self->submesh;
2502 pthread_mutex_lock(&mesh->mutex);
2504 // Check validity of the new node's name
2505 if(!check_id(name)) {
2506 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2507 meshlink_errno = MESHLINK_EINVAL;
2508 pthread_mutex_unlock(&mesh->mutex);
2512 // Ensure no host configuration file with that name exists
2513 if(config_exists(mesh, "current", name)) {
2514 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2515 meshlink_errno = MESHLINK_EEXIST;
2516 pthread_mutex_unlock(&mesh->mutex);
2520 // Ensure no other nodes know about this name
2521 if(lookup_node(mesh, name)) {
2522 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2523 meshlink_errno = MESHLINK_EEXIST;
2524 pthread_mutex_unlock(&mesh->mutex);
2528 // Get the local address
2529 char *address = get_my_hostname(mesh, flags);
2532 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2533 meshlink_errno = MESHLINK_ERESOLV;
2534 pthread_mutex_unlock(&mesh->mutex);
2538 if(!refresh_invitation_key(mesh)) {
2539 meshlink_errno = MESHLINK_EINTERNAL;
2540 pthread_mutex_unlock(&mesh->mutex);
2544 // If we changed our own host config file, write it out now
2545 if(mesh->self->status.dirty) {
2546 if(!node_write_config(mesh, mesh->self)) {
2547 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2548 pthread_mutex_unlock(&mesh->mutex);
2555 // Create a hash of the key.
2556 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2557 sha512(fingerprint, strlen(fingerprint), hash);
2558 b64encode_urlsafe(hash, hash, 18);
2560 // Create a random cookie for this invitation.
2562 randomize(cookie, 18);
2564 // Create a filename that doesn't reveal the cookie itself
2565 char buf[18 + strlen(fingerprint)];
2566 char cookiehash[64];
2567 memcpy(buf, cookie, 18);
2568 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2569 sha512(buf, sizeof(buf), cookiehash);
2570 b64encode_urlsafe(cookiehash, cookiehash, 18);
2572 b64encode_urlsafe(cookie, cookie, 18);
2576 /* Construct the invitation file */
2577 uint8_t outbuf[4096];
2578 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2580 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2581 packmsg_add_str(&inv, name);
2582 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2583 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2585 /* TODO: Add several host config files to bootstrap connections.
2586 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2587 * and are not blacklisted.
2589 config_t configs[5];
2590 memset(configs, 0, sizeof(configs));
2593 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2597 /* Append host config files to the invitation file */
2598 packmsg_add_array(&inv, count);
2600 for(int i = 0; i < count; i++) {
2601 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2602 config_free(&configs[i]);
2605 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2607 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2608 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2609 meshlink_errno = MESHLINK_ESTORAGE;
2610 pthread_mutex_unlock(&mesh->mutex);
2614 // Create an URL from the local address, key hash and cookie
2616 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2619 pthread_mutex_unlock(&mesh->mutex);
2623 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2624 return meshlink_invite_ex(mesh, submesh, name, 0);
2627 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2628 if(!mesh || !invitation) {
2629 meshlink_errno = MESHLINK_EINVAL;
2633 join_state_t state = {
2638 ecdsa_t *key = NULL;
2639 ecdsa_t *hiskey = NULL;
2641 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2642 char copy[strlen(invitation) + 1];
2644 pthread_mutex_lock(&mesh->mutex);
2646 //Before doing meshlink_join make sure we are not connected to another mesh
2647 if(mesh->threadstarted) {
2648 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2649 meshlink_errno = MESHLINK_EINVAL;
2653 // 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.
2654 if(mesh->nodes->count > 1) {
2655 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2656 meshlink_errno = MESHLINK_EINVAL;
2660 strcpy(copy, invitation);
2662 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2664 char *slash = strchr(copy, '/');
2672 if(strlen(slash) != 48) {
2676 char *address = copy;
2679 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2683 if(mesh->inviter_commits_first) {
2684 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2687 // Generate a throw-away key for the invitation.
2688 key = ecdsa_generate();
2691 meshlink_errno = MESHLINK_EINTERNAL;
2695 char *b64key = ecdsa_get_base64_public_key(key);
2698 while(address && *address) {
2699 // We allow commas in the address part to support multiple addresses in one invitation URL.
2700 comma = strchr(address, ',');
2706 // Split of the port
2707 port = strrchr(address, ':');
2715 // IPv6 address are enclosed in brackets, per RFC 3986
2716 if(*address == '[') {
2718 char *bracket = strchr(address, ']');
2731 // Connect to the meshlink daemon mentioned in the URL.
2732 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2735 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2736 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2738 if(state.sock == -1) {
2739 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2740 meshlink_errno = MESHLINK_ENETWORK;
2744 set_timeout(state.sock, 5000);
2746 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2747 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2748 meshlink_errno = MESHLINK_ENETWORK;
2749 closesocket(state.sock);
2757 meshlink_errno = MESHLINK_ERESOLV;
2760 if(state.sock != -1 || !comma) {
2767 if(state.sock == -1) {
2771 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2773 // Tell him we have an invitation, and give him our throw-away key.
2777 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2778 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2779 meshlink_errno = MESHLINK_ENETWORK;
2785 char hisname[4096] = "";
2786 int code, hismajor, hisminor = 0;
2788 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) {
2789 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2790 meshlink_errno = MESHLINK_ENETWORK;
2794 // Check if the hash of the key he gave us matches the hash in the URL.
2795 char *fingerprint = state.line + 2;
2798 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2799 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2800 meshlink_errno = MESHLINK_EINTERNAL;
2804 if(memcmp(hishash, state.hash, 18)) {
2805 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2806 meshlink_errno = MESHLINK_EPEER;
2810 hiskey = ecdsa_set_base64_public_key(fingerprint);
2813 meshlink_errno = MESHLINK_EINTERNAL;
2817 // Start an SPTPS session
2818 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2819 meshlink_errno = MESHLINK_EINTERNAL;
2823 // Feed rest of input buffer to SPTPS
2824 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2825 meshlink_errno = MESHLINK_EPEER;
2830 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2832 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2834 if(errno == EINTR) {
2838 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2839 meshlink_errno = MESHLINK_ENETWORK;
2843 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2844 meshlink_errno = MESHLINK_EPEER;
2849 if(!state.success) {
2850 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2851 meshlink_errno = MESHLINK_EPEER;
2855 sptps_stop(&state.sptps);
2858 closesocket(state.sock);
2860 pthread_mutex_unlock(&mesh->mutex);
2864 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2865 meshlink_errno = MESHLINK_EINVAL;
2867 sptps_stop(&state.sptps);
2871 if(state.sock != -1) {
2872 closesocket(state.sock);
2875 pthread_mutex_unlock(&mesh->mutex);
2879 char *meshlink_export(meshlink_handle_t *mesh) {
2881 meshlink_errno = MESHLINK_EINVAL;
2885 // Create a config file on the fly.
2888 packmsg_output_t out = {buf, sizeof(buf)};
2889 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2890 packmsg_add_str(&out, mesh->name);
2891 packmsg_add_str(&out, CORE_MESH);
2893 pthread_mutex_lock(&mesh->mutex);
2895 packmsg_add_int32(&out, mesh->self->devclass);
2896 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2897 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2898 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2902 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2903 if(mesh->self->recent[i].sa.sa_family) {
2910 packmsg_add_array(&out, count);
2912 for(uint32_t i = 0; i < count; i++) {
2913 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2916 packmsg_add_int64(&out, 0);
2917 packmsg_add_int64(&out, 0);
2919 pthread_mutex_unlock(&mesh->mutex);
2921 if(!packmsg_output_ok(&out)) {
2922 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2923 meshlink_errno = MESHLINK_EINTERNAL;
2927 // Prepare a base64-encoded packmsg array containing our config file
2929 uint32_t len = packmsg_output_size(&out, buf);
2930 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2931 uint8_t *buf2 = xmalloc(len2);
2932 packmsg_output_t out2 = {buf2, len2};
2933 packmsg_add_array(&out2, 1);
2934 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2936 if(!packmsg_output_ok(&out2)) {
2937 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2938 meshlink_errno = MESHLINK_EINTERNAL;
2943 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2945 return (char *)buf2;
2948 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2949 if(!mesh || !data) {
2950 meshlink_errno = MESHLINK_EINVAL;
2954 size_t datalen = strlen(data);
2955 uint8_t *buf = xmalloc(datalen);
2956 int buflen = b64decode(data, buf, datalen);
2959 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2960 meshlink_errno = MESHLINK_EPEER;
2964 packmsg_input_t in = {buf, buflen};
2965 uint32_t count = packmsg_get_array(&in);
2968 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2969 meshlink_errno = MESHLINK_EPEER;
2973 pthread_mutex_lock(&mesh->mutex);
2977 uint32_t len = packmsg_get_bin_raw(&in, &data);
2983 packmsg_input_t in2 = {data, len};
2984 uint32_t version = packmsg_get_uint32(&in2);
2985 char *name = packmsg_get_str_dup(&in2);
2987 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2989 packmsg_input_invalidate(&in);
2993 if(!check_id(name)) {
2998 node_t *n = lookup_node(mesh, name);
3001 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3009 config_t config = {data, len};
3011 if(!node_read_from_config(mesh, n, &config)) {
3013 packmsg_input_invalidate(&in);
3017 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3018 n->last_reachable = 0;
3019 n->last_unreachable = 0;
3021 if(!node_write_config(mesh, n)) {
3029 pthread_mutex_unlock(&mesh->mutex);
3033 if(!packmsg_done(&in)) {
3034 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3035 meshlink_errno = MESHLINK_EPEER;
3039 if(!config_sync(mesh, "current")) {
3046 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3047 if(n == mesh->self) {
3048 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3049 meshlink_errno = MESHLINK_EINVAL;
3053 if(n->status.blacklisted) {
3054 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3058 n->status.blacklisted = true;
3060 /* Immediately shut down any connections we have with the blacklisted node.
3061 * We can't call terminate_connection(), because we might be called from a callback function.
3063 for list_each(connection_t, c, mesh->connections) {
3065 shutdown(c->socket, SHUT_RDWR);
3069 utcp_abort_all_connections(n->utcp);
3075 n->status.udp_confirmed = false;
3077 if(n->status.reachable) {
3078 n->last_unreachable = mesh->loop.now.tv_sec;
3081 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3082 * manually call the status callback if necessary.
3084 if(n->status.reachable && mesh->node_status_cb) {
3085 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3088 return node_write_config(mesh, n) && config_sync(mesh, "current");
3091 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3092 if(!mesh || !node) {
3093 meshlink_errno = MESHLINK_EINVAL;
3097 pthread_mutex_lock(&mesh->mutex);
3099 if(!blacklist(mesh, (node_t *)node)) {
3100 pthread_mutex_unlock(&mesh->mutex);
3104 pthread_mutex_unlock(&mesh->mutex);
3106 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3110 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3111 if(!mesh || !name) {
3112 meshlink_errno = MESHLINK_EINVAL;
3116 pthread_mutex_lock(&mesh->mutex);
3118 node_t *n = lookup_node(mesh, (char *)name);
3122 n->name = xstrdup(name);
3126 if(!blacklist(mesh, (node_t *)n)) {
3127 pthread_mutex_unlock(&mesh->mutex);
3131 pthread_mutex_unlock(&mesh->mutex);
3133 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3137 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3138 if(n == mesh->self) {
3139 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3140 meshlink_errno = MESHLINK_EINVAL;
3144 if(!n->status.blacklisted) {
3145 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3149 n->status.blacklisted = false;
3151 if(n->status.reachable) {
3152 n->last_reachable = mesh->loop.now.tv_sec;
3153 update_node_status(mesh, n);
3156 return node_write_config(mesh, n) && config_sync(mesh, "current");
3159 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3160 if(!mesh || !node) {
3161 meshlink_errno = MESHLINK_EINVAL;
3165 pthread_mutex_lock(&mesh->mutex);
3167 if(!whitelist(mesh, (node_t *)node)) {
3168 pthread_mutex_unlock(&mesh->mutex);
3172 pthread_mutex_unlock(&mesh->mutex);
3174 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3178 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3179 if(!mesh || !name) {
3180 meshlink_errno = MESHLINK_EINVAL;
3184 pthread_mutex_lock(&mesh->mutex);
3186 node_t *n = lookup_node(mesh, (char *)name);
3190 n->name = xstrdup(name);
3194 if(!whitelist(mesh, (node_t *)n)) {
3195 pthread_mutex_unlock(&mesh->mutex);
3199 pthread_mutex_unlock(&mesh->mutex);
3201 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3205 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3206 mesh->default_blacklist = blacklist;
3209 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3210 if(!mesh || !node) {
3211 meshlink_errno = MESHLINK_EINVAL;
3215 node_t *n = (node_t *)node;
3217 pthread_mutex_lock(&mesh->mutex);
3219 /* Check that the node is not reachable */
3220 if(n->status.reachable || n->connection) {
3221 pthread_mutex_unlock(&mesh->mutex);
3222 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3226 /* Check that we don't have any active UTCP connections */
3227 if(n->utcp && utcp_is_active(n->utcp)) {
3228 pthread_mutex_unlock(&mesh->mutex);
3229 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3233 /* Check that we have no active connections to this node */
3234 for list_each(connection_t, c, mesh->connections) {
3236 pthread_mutex_unlock(&mesh->mutex);
3237 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3242 /* Remove any pending outgoings to this node */
3243 if(mesh->outgoings) {
3244 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3245 if(outgoing->node == n) {
3246 list_delete_node(mesh->outgoings, node);
3251 /* Delete the config file for this node */
3252 if(!config_delete(mesh, "current", n->name)) {
3253 pthread_mutex_unlock(&mesh->mutex);
3257 /* Delete the node struct and any remaining edges referencing this node */
3260 pthread_mutex_unlock(&mesh->mutex);
3262 return config_sync(mesh, "current");
3265 /* Hint that a hostname may be found at an address
3266 * See header file for detailed comment.
3268 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3269 if(!mesh || !node || !addr) {
3270 meshlink_errno = EINVAL;
3274 pthread_mutex_lock(&mesh->mutex);
3276 node_t *n = (node_t *)node;
3278 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3279 if(!node_write_config(mesh, n)) {
3280 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3284 pthread_mutex_unlock(&mesh->mutex);
3285 // @TODO do we want to fire off a connection attempt right away?
3288 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3290 node_t *n = utcp->priv;
3291 meshlink_handle_t *mesh = n->mesh;
3292 return mesh->channel_accept_cb;
3295 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3297 if(aio->cb.buffer) {
3298 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3302 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3307 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3308 meshlink_channel_t *channel = connection->priv;
3314 node_t *n = channel->node;
3315 meshlink_handle_t *mesh = n->mesh;
3317 if(n->status.destroyed) {
3318 meshlink_channel_close(mesh, channel);
3322 const char *p = data;
3325 while(channel->aio_receive) {
3326 meshlink_aio_buffer_t *aio = channel->aio_receive;
3327 size_t todo = aio->len - aio->done;
3334 memcpy((char *)aio->data + aio->done, p, todo);
3336 ssize_t result = write(aio->fd, p, todo);
3345 if(aio->done == aio->len) {
3346 channel->aio_receive = aio->next;
3347 aio_signal(mesh, channel, aio);
3359 if(channel->receive_cb) {
3360 channel->receive_cb(mesh, channel, p, left);
3366 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3367 node_t *n = utcp_connection->utcp->priv;
3373 meshlink_handle_t *mesh = n->mesh;
3375 if(!mesh->channel_accept_cb) {
3379 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3381 channel->c = utcp_connection;
3383 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3384 utcp_accept(utcp_connection, channel_recv, channel);
3390 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3391 node_t *n = utcp->priv;
3393 if(n->status.destroyed) {
3397 meshlink_handle_t *mesh = n->mesh;
3398 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3401 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3402 if(!mesh || !channel) {
3403 meshlink_errno = MESHLINK_EINVAL;
3407 channel->receive_cb = cb;
3410 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3412 node_t *n = (node_t *)source;
3418 utcp_recv(n->utcp, data, len);
3421 static void channel_poll(struct utcp_connection *connection, size_t len) {
3422 meshlink_channel_t *channel = connection->priv;
3428 node_t *n = channel->node;
3429 meshlink_handle_t *mesh = n->mesh;
3430 meshlink_aio_buffer_t *aio = channel->aio_send;
3433 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3434 size_t left = aio->len - aio->done;
3442 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3445 size_t todo = utcp_get_sndbuf_free(connection);
3451 if(todo > sizeof(buf)) {
3455 ssize_t result = read(aio->fd, buf, todo);
3458 sent = utcp_send(connection, buf, result);
3468 /* If the buffer is now completely sent, call the callback and dispose of it. */
3469 if(aio->done >= aio->len) {
3470 channel->aio_send = aio->next;
3471 aio_signal(mesh, channel, aio);
3475 if(channel->poll_cb) {
3476 channel->poll_cb(mesh, channel, len);
3478 utcp_set_poll_cb(connection, NULL);
3483 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3484 if(!mesh || !channel) {
3485 meshlink_errno = MESHLINK_EINVAL;
3489 pthread_mutex_lock(&mesh->mutex);
3490 channel->poll_cb = cb;
3491 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3492 pthread_mutex_unlock(&mesh->mutex);
3495 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3497 meshlink_errno = MESHLINK_EINVAL;
3501 pthread_mutex_lock(&mesh->mutex);
3502 mesh->channel_accept_cb = cb;
3503 mesh->receive_cb = channel_receive;
3505 for splay_each(node_t, n, mesh->nodes) {
3506 if(!n->utcp && n != mesh->self) {
3507 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3511 pthread_mutex_unlock(&mesh->mutex);
3514 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3518 meshlink_errno = MESHLINK_EINVAL;
3522 pthread_mutex_lock(&mesh->mutex);
3523 utcp_set_sndbuf(channel->c, size);
3524 pthread_mutex_unlock(&mesh->mutex);
3527 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3531 meshlink_errno = MESHLINK_EINVAL;
3535 pthread_mutex_lock(&mesh->mutex);
3536 utcp_set_rcvbuf(channel->c, size);
3537 pthread_mutex_unlock(&mesh->mutex);
3540 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) {
3542 abort(); // TODO: handle non-NULL data
3545 if(!mesh || !node) {
3546 meshlink_errno = MESHLINK_EINVAL;
3550 pthread_mutex_lock(&mesh->mutex);
3552 node_t *n = (node_t *)node;
3555 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3556 mesh->receive_cb = channel_receive;
3559 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3560 pthread_mutex_unlock(&mesh->mutex);
3565 if(n->status.blacklisted) {
3566 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3567 meshlink_errno = MESHLINK_EBLACKLISTED;
3568 pthread_mutex_unlock(&mesh->mutex);
3572 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3574 channel->receive_cb = cb;
3577 channel->priv = (void *)data;
3580 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3582 pthread_mutex_unlock(&mesh->mutex);
3585 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3593 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) {
3594 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3597 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3598 if(!mesh || !channel) {
3599 meshlink_errno = MESHLINK_EINVAL;
3603 pthread_mutex_lock(&mesh->mutex);
3604 utcp_shutdown(channel->c, direction);
3605 pthread_mutex_unlock(&mesh->mutex);
3608 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3609 if(!mesh || !channel) {
3610 meshlink_errno = MESHLINK_EINVAL;
3614 pthread_mutex_lock(&mesh->mutex);
3616 utcp_close(channel->c);
3618 /* Clean up any outstanding AIO buffers. */
3619 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3621 aio_signal(mesh, channel, aio);
3625 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3627 aio_signal(mesh, channel, aio);
3631 pthread_mutex_unlock(&mesh->mutex);
3636 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3637 if(!mesh || !channel) {
3638 meshlink_errno = MESHLINK_EINVAL;
3647 meshlink_errno = MESHLINK_EINVAL;
3651 // TODO: more finegrained locking.
3652 // Ideally we want to put the data into the UTCP connection's send buffer.
3653 // Then, preferably only if there is room in the receiver window,
3654 // kick the meshlink thread to go send packets.
3658 pthread_mutex_lock(&mesh->mutex);
3660 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3661 if(channel->aio_send) {
3664 retval = utcp_send(channel->c, data, len);
3667 pthread_mutex_unlock(&mesh->mutex);
3670 meshlink_errno = MESHLINK_ENETWORK;
3676 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) {
3677 if(!mesh || !channel) {
3678 meshlink_errno = MESHLINK_EINVAL;
3683 meshlink_errno = MESHLINK_EINVAL;
3687 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3690 aio->cb.buffer = cb;
3693 pthread_mutex_lock(&mesh->mutex);
3695 /* Append the AIO buffer descriptor to the end of the chain */
3696 meshlink_aio_buffer_t **p = &channel->aio_send;
3704 /* Ensure the poll callback is set, and call it right now to push data if possible */
3705 utcp_set_poll_cb(channel->c, channel_poll);
3706 channel_poll(channel->c, len);
3708 pthread_mutex_unlock(&mesh->mutex);
3713 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) {
3714 if(!mesh || !channel) {
3715 meshlink_errno = MESHLINK_EINVAL;
3719 if(!len || fd == -1) {
3720 meshlink_errno = MESHLINK_EINVAL;
3724 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3730 pthread_mutex_lock(&mesh->mutex);
3732 /* Append the AIO buffer descriptor to the end of the chain */
3733 meshlink_aio_buffer_t **p = &channel->aio_send;
3741 /* Ensure the poll callback is set, and call it right now to push data if possible */
3742 utcp_set_poll_cb(channel->c, channel_poll);
3743 channel_poll(channel->c, len);
3745 pthread_mutex_unlock(&mesh->mutex);
3750 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) {
3751 if(!mesh || !channel) {
3752 meshlink_errno = MESHLINK_EINVAL;
3757 meshlink_errno = MESHLINK_EINVAL;
3761 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3764 aio->cb.buffer = cb;
3767 pthread_mutex_lock(&mesh->mutex);
3769 /* Append the AIO buffer descriptor to the end of the chain */
3770 meshlink_aio_buffer_t **p = &channel->aio_receive;
3778 pthread_mutex_unlock(&mesh->mutex);
3783 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) {
3784 if(!mesh || !channel) {
3785 meshlink_errno = MESHLINK_EINVAL;
3789 if(!len || fd == -1) {
3790 meshlink_errno = MESHLINK_EINVAL;
3794 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3800 pthread_mutex_lock(&mesh->mutex);
3802 /* Append the AIO buffer descriptor to the end of the chain */
3803 meshlink_aio_buffer_t **p = &channel->aio_receive;
3811 pthread_mutex_unlock(&mesh->mutex);
3816 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3817 if(!mesh || !channel) {
3818 meshlink_errno = MESHLINK_EINVAL;
3822 return channel->c->flags;
3825 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3826 if(!mesh || !channel) {
3827 meshlink_errno = MESHLINK_EINVAL;
3831 return utcp_get_sendq(channel->c);
3834 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3835 if(!mesh || !channel) {
3836 meshlink_errno = MESHLINK_EINVAL;
3840 return utcp_get_recvq(channel->c);
3843 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3844 if(!mesh || !node) {
3845 meshlink_errno = MESHLINK_EINVAL;
3849 node_t *n = (node_t *)node;
3851 pthread_mutex_lock(&mesh->mutex);
3854 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3857 utcp_set_user_timeout(n->utcp, timeout);
3859 pthread_mutex_unlock(&mesh->mutex);
3862 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3863 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3864 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3867 if(mesh->node_status_cb) {
3868 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3871 if(mesh->node_pmtu_cb) {
3872 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3876 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3877 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3878 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3882 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3883 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3887 n->status.duplicate = true;
3888 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3891 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3895 meshlink_errno = MESHLINK_EINVAL;
3899 pthread_mutex_lock(&mesh->mutex);
3901 if(mesh->discovery == enable) {
3905 if(mesh->threadstarted) {
3907 discovery_start(mesh);
3909 discovery_stop(mesh);
3913 mesh->discovery = enable;
3916 pthread_mutex_unlock(&mesh->mutex);
3920 meshlink_errno = MESHLINK_ENOTSUP;
3924 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3925 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3926 meshlink_errno = EINVAL;
3930 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3931 meshlink_errno = EINVAL;
3935 pthread_mutex_lock(&mesh->mutex);
3936 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3937 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3938 pthread_mutex_unlock(&mesh->mutex);
3941 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3942 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3943 meshlink_errno = EINVAL;
3947 if(fast_retry_period < 0) {
3948 meshlink_errno = EINVAL;
3952 pthread_mutex_lock(&mesh->mutex);
3953 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3954 pthread_mutex_unlock(&mesh->mutex);
3957 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3959 meshlink_errno = EINVAL;
3963 pthread_mutex_lock(&mesh->mutex);
3964 mesh->inviter_commits_first = inviter_commits_first;
3965 pthread_mutex_unlock(&mesh->mutex);
3968 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3971 if(!mesh->connections || !mesh->loop.running) {
3978 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3979 // We should only call the callback function if we are in the background thread.
3980 if(!mesh->error_cb) {
3984 if(!mesh->threadstarted) {
3988 if(mesh->thread == pthread_self()) {
3989 mesh->error_cb(mesh, meshlink_errno);
3993 static void __attribute__((constructor)) meshlink_init(void) {
3997 static void __attribute__((destructor)) meshlink_exit(void) {