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) {
541 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
542 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
549 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
562 static int check_port(meshlink_handle_t *mesh) {
563 for(int i = 0; i < 1000; i++) {
564 int port = 0x1000 + prng(mesh, 0x8000);
568 xasprintf(&mesh->myport, "%d", port);
573 meshlink_errno = MESHLINK_ENETWORK;
574 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
578 static bool write_main_config_files(meshlink_handle_t *mesh) {
579 if(!mesh->confbase) {
585 /* Write the main config file */
586 packmsg_output_t out = {buf, sizeof buf};
588 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
589 packmsg_add_str(&out, mesh->name);
590 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
591 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
592 packmsg_add_uint16(&out, atoi(mesh->myport));
594 if(!packmsg_output_ok(&out)) {
598 config_t config = {buf, packmsg_output_size(&out, buf)};
600 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
604 /* Write our own host config file */
605 if(!node_write_config(mesh, mesh->self)) {
613 meshlink_handle_t *mesh;
615 char cookie[18 + 32];
626 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
627 meshlink_handle_t *mesh = state->mesh;
628 packmsg_input_t in = {buf, len};
629 uint32_t version = packmsg_get_uint32(&in);
631 if(version != MESHLINK_INVITATION_VERSION) {
632 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
636 char *name = packmsg_get_str_dup(&in);
637 packmsg_skip_element(&in); /* submesh */
638 dev_class_t devclass = packmsg_get_int32(&in);
639 uint32_t count = packmsg_get_array(&in);
642 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
646 if(!check_id(name)) {
647 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
653 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
659 free(mesh->self->name);
661 mesh->self->name = xstrdup(name);
662 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
664 // Initialize configuration directory
665 if(!config_init(mesh, "current")) {
669 if(!write_main_config_files(mesh)) {
673 // Write host config files
674 for(uint32_t i = 0; i < count; i++) {
676 uint32_t len = packmsg_get_bin_raw(&in, &data);
679 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
683 packmsg_input_t in2 = {data, len};
684 uint32_t version = packmsg_get_uint32(&in2);
685 char *name = packmsg_get_str_dup(&in2);
687 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
689 packmsg_input_invalidate(&in);
693 if(!check_id(name)) {
698 if(!strcmp(name, mesh->name)) {
699 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
701 meshlink_errno = MESHLINK_EPEER;
705 node_t *n = new_node();
708 config_t config = {data, len};
710 if(!node_read_from_config(mesh, n, &config)) {
712 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
713 meshlink_errno = MESHLINK_EPEER;
718 /* The first host config file is of the inviter itself;
719 * remember the address we are currently using for the invitation connection.
722 socklen_t salen = sizeof(sa);
724 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
725 node_add_recent_address(mesh, n, &sa);
729 /* Clear the reachability times, since we ourself have never seen these nodes yet */
730 n->last_reachable = 0;
731 n->last_unreachable = 0;
733 if(!node_write_config(mesh, n)) {
741 /* Ensure the configuration directory metadata is on disk */
742 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
746 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
748 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
753 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
755 join_state_t *state = handle;
756 const char *ptr = data;
759 int result = send(state->sock, ptr, len, 0);
761 if(result == -1 && errno == EINTR) {
763 } else if(result <= 0) {
774 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
775 join_state_t *state = handle;
776 meshlink_handle_t *mesh = state->mesh;
779 case SPTPS_HANDSHAKE:
780 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
783 return finalize_join(state, msg, len);
786 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
787 shutdown(state->sock, SHUT_RDWR);
788 state->success = true;
798 static bool recvline(join_state_t *state) {
799 char *newline = NULL;
801 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
802 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
804 if(result == -1 && errno == EINTR) {
806 } else if(result <= 0) {
810 state->blen += result;
813 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
817 size_t len = newline - state->buffer;
819 memcpy(state->line, state->buffer, len);
820 state->line[len] = 0;
821 memmove(state->buffer, newline + 1, state->blen - len - 1);
822 state->blen -= len + 1;
827 static bool sendline(int fd, char *format, ...) {
833 va_start(ap, format);
834 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
837 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
845 int result = send(fd, p, blen, MSG_NOSIGNAL);
847 if(result == -1 && errno == EINTR) {
849 } else if(result <= 0) {
860 static const char *errstr[] = {
861 [MESHLINK_OK] = "No error",
862 [MESHLINK_EINVAL] = "Invalid argument",
863 [MESHLINK_ENOMEM] = "Out of memory",
864 [MESHLINK_ENOENT] = "No such node",
865 [MESHLINK_EEXIST] = "Node already exists",
866 [MESHLINK_EINTERNAL] = "Internal error",
867 [MESHLINK_ERESOLV] = "Could not resolve hostname",
868 [MESHLINK_ESTORAGE] = "Storage error",
869 [MESHLINK_ENETWORK] = "Network error",
870 [MESHLINK_EPEER] = "Error communicating with peer",
871 [MESHLINK_ENOTSUP] = "Operation not supported",
872 [MESHLINK_EBUSY] = "MeshLink instance already in use",
873 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
876 const char *meshlink_strerror(meshlink_errno_t err) {
877 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
878 return "Invalid error code";
884 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
885 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
887 mesh->private_key = ecdsa_generate();
888 mesh->invitation_key = ecdsa_generate();
890 if(!mesh->private_key || !mesh->invitation_key) {
891 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
892 meshlink_errno = MESHLINK_EINTERNAL;
896 logger(mesh, MESHLINK_DEBUG, "Done.\n");
901 static struct timeval idle(event_loop_t *loop, void *data) {
903 meshlink_handle_t *mesh = data;
904 struct timeval t, tmin = {3600, 0};
906 for splay_each(node_t, n, mesh->nodes) {
911 t = utcp_timeout(n->utcp);
913 if(timercmp(&t, &tmin, <)) {
921 // Get our local address(es) by simulating connecting to an Internet host.
922 static void add_local_addresses(meshlink_handle_t *mesh) {
924 sa.storage.ss_family = AF_UNKNOWN;
925 socklen_t salen = sizeof(sa);
929 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
930 sa.in.sin_port = ntohs(atoi(mesh->myport));
931 node_add_recent_address(mesh, mesh->self, &sa);
938 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
939 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
940 node_add_recent_address(mesh, mesh->self, &sa);
944 static bool meshlink_setup(meshlink_handle_t *mesh) {
945 if(!config_destroy(mesh->confbase, "new")) {
946 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
947 meshlink_errno = MESHLINK_ESTORAGE;
951 if(!config_destroy(mesh->confbase, "old")) {
952 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
953 meshlink_errno = MESHLINK_ESTORAGE;
957 if(!config_init(mesh, "current")) {
958 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
959 meshlink_errno = MESHLINK_ESTORAGE;
963 if(!ecdsa_keygen(mesh)) {
964 meshlink_errno = MESHLINK_EINTERNAL;
968 if(check_port(mesh) == 0) {
969 meshlink_errno = MESHLINK_ENETWORK;
973 /* Create a node for ourself */
975 mesh->self = new_node();
976 mesh->self->name = xstrdup(mesh->name);
977 mesh->self->devclass = mesh->devclass;
978 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
979 mesh->self->session_id = mesh->session_id;
981 if(!write_main_config_files(mesh)) {
982 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
983 meshlink_errno = MESHLINK_ESTORAGE;
987 /* Ensure the configuration directory metadata is on disk */
988 if(!config_sync(mesh, "current")) {
995 static bool meshlink_read_config(meshlink_handle_t *mesh) {
998 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
999 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1003 packmsg_input_t in = {config.buf, config.len};
1004 const void *private_key;
1005 const void *invitation_key;
1007 uint32_t version = packmsg_get_uint32(&in);
1008 char *name = packmsg_get_str_dup(&in);
1009 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1010 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1011 uint16_t myport = packmsg_get_uint16(&in);
1013 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1014 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1016 config_free(&config);
1022 // TODO: check this?
1023 if(mesh->name && strcmp(mesh->name, name)) {
1024 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1025 meshlink_errno = MESHLINK_ESTORAGE;
1027 config_free(&config);
1035 xasprintf(&mesh->myport, "%u", myport);
1036 mesh->private_key = ecdsa_set_private_key(private_key);
1037 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1038 config_free(&config);
1040 /* Create a node for ourself and read our host configuration file */
1042 mesh->self = new_node();
1043 mesh->self->name = xstrdup(name);
1044 mesh->self->devclass = mesh->devclass;
1045 mesh->self->session_id = mesh->session_id;
1047 if(!node_read_public_key(mesh, mesh->self)) {
1048 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1049 meshlink_errno = MESHLINK_ESTORAGE;
1050 free_node(mesh->self);
1059 static void *setup_network_in_netns_thread(void *arg) {
1060 meshlink_handle_t *mesh = arg;
1062 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1066 bool success = setup_network(mesh);
1067 add_local_addresses(mesh);
1068 return success ? arg : NULL;
1070 #endif // HAVE_SETNS
1072 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1073 if(!confbase || !*confbase) {
1074 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1075 meshlink_errno = MESHLINK_EINVAL;
1079 if(!appname || !*appname) {
1080 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1081 meshlink_errno = MESHLINK_EINVAL;
1085 if(strchr(appname, ' ')) {
1086 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1087 meshlink_errno = MESHLINK_EINVAL;
1091 if(!name || !*name) {
1092 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1093 meshlink_errno = MESHLINK_EINVAL;
1097 if(!check_id(name)) {
1098 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1099 meshlink_errno = MESHLINK_EINVAL;
1103 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1104 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1105 meshlink_errno = MESHLINK_EINVAL;
1109 meshlink_open_params_t *params = xzalloc(sizeof * params);
1111 params->confbase = xstrdup(confbase);
1112 params->name = xstrdup(name);
1113 params->appname = xstrdup(appname);
1114 params->devclass = devclass;
1120 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1122 meshlink_errno = MESHLINK_EINVAL;
1126 params->netns = netns;
1131 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1133 meshlink_errno = MESHLINK_EINVAL;
1137 if((!key && keylen) || (key && !keylen)) {
1138 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1139 meshlink_errno = MESHLINK_EINVAL;
1144 params->keylen = keylen;
1149 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1150 if(!mesh || !new_key || !new_keylen) {
1151 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1152 meshlink_errno = MESHLINK_EINVAL;
1156 pthread_mutex_lock(&mesh->mutex);
1158 // Create hash for the new key
1159 void *new_config_key;
1160 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1162 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1163 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1164 meshlink_errno = MESHLINK_EINTERNAL;
1165 pthread_mutex_unlock(&mesh->mutex);
1169 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1171 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1172 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1173 meshlink_errno = MESHLINK_ESTORAGE;
1174 pthread_mutex_unlock(&mesh->mutex);
1178 devtool_keyrotate_probe(1);
1180 // Rename confbase/current/ to confbase/old
1182 if(!config_rename(mesh, "current", "old")) {
1183 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1184 meshlink_errno = MESHLINK_ESTORAGE;
1185 pthread_mutex_unlock(&mesh->mutex);
1189 devtool_keyrotate_probe(2);
1191 // Rename confbase/new/ to confbase/current
1193 if(!config_rename(mesh, "new", "current")) {
1194 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1195 meshlink_errno = MESHLINK_ESTORAGE;
1196 pthread_mutex_unlock(&mesh->mutex);
1200 devtool_keyrotate_probe(3);
1202 // Cleanup the "old" confbase sub-directory
1204 if(!config_destroy(mesh->confbase, "old")) {
1205 pthread_mutex_unlock(&mesh->mutex);
1209 // Change the mesh handle key with new key
1211 free(mesh->config_key);
1212 mesh->config_key = new_config_key;
1214 pthread_mutex_unlock(&mesh->mutex);
1219 void meshlink_open_params_free(meshlink_open_params_t *params) {
1221 meshlink_errno = MESHLINK_EINVAL;
1225 free(params->confbase);
1227 free(params->appname);
1232 /// Device class traits
1233 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1234 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1235 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1236 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1237 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1240 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1241 if(!confbase || !*confbase) {
1242 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1243 meshlink_errno = MESHLINK_EINVAL;
1247 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1248 meshlink_open_params_t params;
1249 memset(¶ms, 0, sizeof(params));
1251 params.confbase = (char *)confbase;
1252 params.name = (char *)name;
1253 params.appname = (char *)appname;
1254 params.devclass = devclass;
1257 return meshlink_open_ex(¶ms);
1260 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) {
1261 if(!confbase || !*confbase) {
1262 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1263 meshlink_errno = MESHLINK_EINVAL;
1267 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1268 meshlink_open_params_t params;
1269 memset(¶ms, 0, sizeof(params));
1271 params.confbase = (char *)confbase;
1272 params.name = (char *)name;
1273 params.appname = (char *)appname;
1274 params.devclass = devclass;
1277 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1281 return meshlink_open_ex(¶ms);
1284 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1285 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1286 meshlink_open_params_t params;
1287 memset(¶ms, 0, sizeof(params));
1289 params.name = (char *)name;
1290 params.appname = (char *)appname;
1291 params.devclass = devclass;
1294 return meshlink_open_ex(¶ms);
1297 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1298 // Validate arguments provided by the application
1299 bool usingname = false;
1301 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1303 if(!params->appname || !*params->appname) {
1304 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1305 meshlink_errno = MESHLINK_EINVAL;
1309 if(strchr(params->appname, ' ')) {
1310 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1311 meshlink_errno = MESHLINK_EINVAL;
1315 if(!params->name || !*params->name) {
1316 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1318 } else { //check name only if there is a name != NULL
1320 if(!check_id(params->name)) {
1321 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1322 meshlink_errno = MESHLINK_EINVAL;
1329 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1330 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1331 meshlink_errno = MESHLINK_EINVAL;
1335 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1336 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1337 meshlink_errno = MESHLINK_EINVAL;
1341 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1343 if(params->confbase) {
1344 mesh->confbase = xstrdup(params->confbase);
1347 mesh->appname = xstrdup(params->appname);
1348 mesh->devclass = params->devclass;
1349 mesh->discovery = true;
1350 mesh->invitation_timeout = 604800; // 1 week
1351 mesh->netns = params->netns;
1352 mesh->submeshes = NULL;
1353 mesh->log_cb = global_log_cb;
1354 mesh->log_level = global_log_level;
1356 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1359 randomize(&mesh->session_id, sizeof(mesh->session_id));
1360 } while(mesh->session_id == 0);
1362 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1365 mesh->name = xstrdup(params->name);
1370 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1372 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1373 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1374 meshlink_close(mesh);
1375 meshlink_errno = MESHLINK_EINTERNAL;
1381 pthread_mutexattr_t attr;
1382 pthread_mutexattr_init(&attr);
1383 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1384 pthread_mutex_init(&mesh->mutex, &attr);
1386 mesh->threadstarted = false;
1387 event_loop_init(&mesh->loop);
1388 mesh->loop.data = mesh;
1390 meshlink_queue_init(&mesh->outpacketqueue);
1392 // Atomically lock the configuration directory.
1393 if(!main_config_lock(mesh)) {
1394 meshlink_close(mesh);
1398 // If no configuration exists yet, create it.
1400 if(!meshlink_confbase_exists(mesh)) {
1401 if(!meshlink_setup(mesh)) {
1402 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1403 meshlink_close(mesh);
1407 if(!meshlink_read_config(mesh)) {
1408 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1409 meshlink_close(mesh);
1415 struct WSAData wsa_state;
1416 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1419 // Setup up everything
1420 // TODO: we should not open listening sockets yet
1422 bool success = false;
1424 if(mesh->netns != -1) {
1428 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1429 void *retval = NULL;
1430 success = pthread_join(thr, &retval) == 0 && retval;
1434 meshlink_errno = MESHLINK_EINTERNAL;
1437 #endif // HAVE_SETNS
1439 success = setup_network(mesh);
1440 add_local_addresses(mesh);
1444 meshlink_close(mesh);
1445 meshlink_errno = MESHLINK_ENETWORK;
1449 add_local_addresses(mesh);
1451 if(!node_write_config(mesh, mesh->self)) {
1452 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1456 idle_set(&mesh->loop, idle, mesh);
1458 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1462 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1463 meshlink_submesh_t *s = NULL;
1466 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1467 meshlink_errno = MESHLINK_EINVAL;
1471 if(!submesh || !*submesh) {
1472 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1473 meshlink_errno = MESHLINK_EINVAL;
1478 pthread_mutex_lock(&mesh->mutex);
1480 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1482 pthread_mutex_unlock(&mesh->mutex);
1487 static void *meshlink_main_loop(void *arg) {
1488 meshlink_handle_t *mesh = arg;
1490 if(mesh->netns != -1) {
1493 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1494 pthread_cond_signal(&mesh->cond);
1499 pthread_cond_signal(&mesh->cond);
1501 #endif // HAVE_SETNS
1506 if(mesh->discovery) {
1507 discovery_start(mesh);
1512 pthread_mutex_lock(&mesh->mutex);
1514 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1515 pthread_cond_broadcast(&mesh->cond);
1517 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1519 pthread_mutex_unlock(&mesh->mutex);
1524 if(mesh->discovery) {
1525 discovery_stop(mesh);
1533 bool meshlink_start(meshlink_handle_t *mesh) {
1535 assert(mesh->private_key);
1538 meshlink_errno = MESHLINK_EINVAL;
1542 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1544 pthread_mutex_lock(&mesh->mutex);
1546 assert(mesh->self->ecdsa);
1547 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1549 if(mesh->threadstarted) {
1550 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1551 pthread_mutex_unlock(&mesh->mutex);
1555 if(mesh->listen_socket[0].tcp.fd < 0) {
1556 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1557 meshlink_errno = MESHLINK_ENETWORK;
1561 // TODO: open listening sockets first
1563 //Check that a valid name is set
1565 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1566 meshlink_errno = MESHLINK_EINVAL;
1567 pthread_mutex_unlock(&mesh->mutex);
1571 init_outgoings(mesh);
1573 // Start the main thread
1575 event_loop_start(&mesh->loop);
1577 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1578 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1579 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1580 meshlink_errno = MESHLINK_EINTERNAL;
1581 event_loop_stop(&mesh->loop);
1582 pthread_mutex_unlock(&mesh->mutex);
1586 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1587 mesh->threadstarted = true;
1589 // Ensure we are considered reachable
1592 pthread_mutex_unlock(&mesh->mutex);
1596 void meshlink_stop(meshlink_handle_t *mesh) {
1598 meshlink_errno = MESHLINK_EINVAL;
1602 pthread_mutex_lock(&mesh->mutex);
1603 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1605 // Shut down the main thread
1606 event_loop_stop(&mesh->loop);
1608 // Send ourselves a UDP packet to kick the event loop
1609 for(int i = 0; i < mesh->listen_sockets; i++) {
1611 socklen_t salen = sizeof(sa);
1613 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1614 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1618 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1619 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1623 if(mesh->threadstarted) {
1624 // Wait for the main thread to finish
1625 pthread_mutex_unlock(&mesh->mutex);
1626 pthread_join(mesh->thread, NULL);
1627 pthread_mutex_lock(&mesh->mutex);
1629 mesh->threadstarted = false;
1632 // Close all metaconnections
1633 if(mesh->connections) {
1634 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1636 connection_t *c = node->data;
1638 terminate_connection(mesh, c, false);
1642 exit_outgoings(mesh);
1644 // Ensure we are considered unreachable
1649 // Try to write out any changed node config files, ignore errors at this point.
1651 for splay_each(node_t, n, mesh->nodes) {
1652 if(n->status.dirty) {
1653 n->status.dirty = !node_write_config(mesh, n);
1658 pthread_mutex_unlock(&mesh->mutex);
1661 void meshlink_close(meshlink_handle_t *mesh) {
1663 meshlink_errno = MESHLINK_EINVAL;
1667 // stop can be called even if mesh has not been started
1668 meshlink_stop(mesh);
1670 // lock is not released after this
1671 pthread_mutex_lock(&mesh->mutex);
1673 // Close and free all resources used.
1675 close_network_connections(mesh);
1677 logger(mesh, MESHLINK_INFO, "Terminating");
1679 event_loop_exit(&mesh->loop);
1683 if(mesh->confbase) {
1689 ecdsa_free(mesh->invitation_key);
1691 if(mesh->netns != -1) {
1695 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1699 meshlink_queue_exit(&mesh->outpacketqueue);
1702 free(mesh->appname);
1703 free(mesh->confbase);
1704 free(mesh->config_key);
1705 ecdsa_free(mesh->private_key);
1707 main_config_unlock(mesh);
1709 pthread_mutex_unlock(&mesh->mutex);
1710 pthread_mutex_destroy(&mesh->mutex);
1712 memset(mesh, 0, sizeof(*mesh));
1717 bool meshlink_destroy(const char *confbase) {
1719 meshlink_errno = MESHLINK_EINVAL;
1723 /* Exit early if the confbase directory itself doesn't exist */
1724 if(access(confbase, F_OK) && errno == ENOENT) {
1728 /* Take the lock the same way meshlink_open() would. */
1729 char lockfilename[PATH_MAX];
1730 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1732 FILE *lockfile = fopen(lockfilename, "w+");
1735 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1736 meshlink_errno = MESHLINK_ESTORAGE;
1741 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1745 // TODO: use _locking()?
1748 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1749 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1751 meshlink_errno = MESHLINK_EBUSY;
1757 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1758 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1762 if(unlink(lockfilename)) {
1763 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1765 meshlink_errno = MESHLINK_ESTORAGE;
1771 if(!sync_path(confbase)) {
1772 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1773 meshlink_errno = MESHLINK_ESTORAGE;
1780 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1782 meshlink_errno = MESHLINK_EINVAL;
1786 pthread_mutex_lock(&mesh->mutex);
1787 mesh->receive_cb = cb;
1788 pthread_mutex_unlock(&mesh->mutex);
1791 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1793 meshlink_errno = MESHLINK_EINVAL;
1797 pthread_mutex_lock(&mesh->mutex);
1798 mesh->connection_try_cb = cb;
1799 pthread_mutex_unlock(&mesh->mutex);
1802 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1804 meshlink_errno = MESHLINK_EINVAL;
1808 pthread_mutex_lock(&mesh->mutex);
1809 mesh->node_status_cb = cb;
1810 pthread_mutex_unlock(&mesh->mutex);
1813 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1815 meshlink_errno = MESHLINK_EINVAL;
1819 pthread_mutex_lock(&mesh->mutex);
1820 mesh->node_pmtu_cb = cb;
1821 pthread_mutex_unlock(&mesh->mutex);
1824 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1826 meshlink_errno = MESHLINK_EINVAL;
1830 pthread_mutex_lock(&mesh->mutex);
1831 mesh->node_duplicate_cb = cb;
1832 pthread_mutex_unlock(&mesh->mutex);
1835 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1837 pthread_mutex_lock(&mesh->mutex);
1839 mesh->log_level = cb ? level : 0;
1840 pthread_mutex_unlock(&mesh->mutex);
1843 global_log_level = cb ? level : 0;
1847 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1849 meshlink_errno = MESHLINK_EINVAL;
1853 pthread_mutex_lock(&mesh->mutex);
1854 mesh->error_cb = cb;
1855 pthread_mutex_unlock(&mesh->mutex);
1858 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1859 meshlink_packethdr_t *hdr;
1861 // Validate arguments
1862 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1863 meshlink_errno = MESHLINK_EINVAL;
1872 meshlink_errno = MESHLINK_EINVAL;
1876 node_t *n = (node_t *)destination;
1878 if(n->status.blacklisted) {
1879 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1880 meshlink_errno = MESHLINK_EBLACKLISTED;
1884 // Prepare the packet
1885 vpn_packet_t *packet = malloc(sizeof(*packet));
1888 meshlink_errno = MESHLINK_ENOMEM;
1892 packet->probe = false;
1893 packet->tcp = false;
1894 packet->len = len + sizeof(*hdr);
1896 hdr = (meshlink_packethdr_t *)packet->data;
1897 memset(hdr, 0, sizeof(*hdr));
1898 // leave the last byte as 0 to make sure strings are always
1899 // null-terminated if they are longer than the buffer
1900 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1901 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1903 memcpy(packet->data + sizeof(*hdr), data, len);
1906 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1908 meshlink_errno = MESHLINK_ENOMEM;
1912 // Notify event loop
1913 signal_trigger(&mesh->loop, &mesh->datafromapp);
1918 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1920 meshlink_handle_t *mesh = data;
1921 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1927 mesh->self->in_packets++;
1928 mesh->self->in_bytes += packet->len;
1929 route(mesh, mesh->self, packet);
1934 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1935 if(!mesh || !destination) {
1936 meshlink_errno = MESHLINK_EINVAL;
1940 pthread_mutex_lock(&mesh->mutex);
1942 node_t *n = (node_t *)destination;
1944 if(!n->status.reachable) {
1945 pthread_mutex_unlock(&mesh->mutex);
1948 } else if(n->mtuprobes > 30 && n->minmtu) {
1949 pthread_mutex_unlock(&mesh->mutex);
1952 pthread_mutex_unlock(&mesh->mutex);
1957 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1958 if(!mesh || !node) {
1959 meshlink_errno = MESHLINK_EINVAL;
1963 pthread_mutex_lock(&mesh->mutex);
1965 node_t *n = (node_t *)node;
1967 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1968 meshlink_errno = MESHLINK_EINTERNAL;
1969 pthread_mutex_unlock(&mesh->mutex);
1973 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1976 meshlink_errno = MESHLINK_EINTERNAL;
1979 pthread_mutex_unlock(&mesh->mutex);
1983 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1985 meshlink_errno = MESHLINK_EINVAL;
1989 return (meshlink_node_t *)mesh->self;
1992 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1993 if(!mesh || !name) {
1994 meshlink_errno = MESHLINK_EINVAL;
2000 pthread_mutex_lock(&mesh->mutex);
2001 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2002 pthread_mutex_unlock(&mesh->mutex);
2005 meshlink_errno = MESHLINK_ENOENT;
2008 return (meshlink_node_t *)n;
2011 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2012 if(!mesh || !name) {
2013 meshlink_errno = MESHLINK_EINVAL;
2017 meshlink_submesh_t *submesh = NULL;
2019 pthread_mutex_lock(&mesh->mutex);
2020 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2021 pthread_mutex_unlock(&mesh->mutex);
2024 meshlink_errno = MESHLINK_ENOENT;
2030 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2031 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2032 meshlink_errno = MESHLINK_EINVAL;
2036 meshlink_node_t **result;
2039 pthread_mutex_lock(&mesh->mutex);
2041 *nmemb = mesh->nodes->count;
2042 result = realloc(nodes, *nmemb * sizeof(*nodes));
2045 meshlink_node_t **p = result;
2047 for splay_each(node_t, n, mesh->nodes) {
2048 *p++ = (meshlink_node_t *)n;
2053 meshlink_errno = MESHLINK_ENOMEM;
2056 pthread_mutex_unlock(&mesh->mutex);
2061 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) {
2062 meshlink_node_t **result;
2064 pthread_mutex_lock(&mesh->mutex);
2068 for splay_each(node_t, n, mesh->nodes) {
2069 if(search_node(n, condition)) {
2076 pthread_mutex_unlock(&mesh->mutex);
2080 result = realloc(nodes, *nmemb * sizeof(*nodes));
2083 meshlink_node_t **p = result;
2085 for splay_each(node_t, n, mesh->nodes) {
2086 if(search_node(n, condition)) {
2087 *p++ = (meshlink_node_t *)n;
2093 meshlink_errno = MESHLINK_ENOMEM;
2096 pthread_mutex_unlock(&mesh->mutex);
2101 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2102 dev_class_t *devclass = (dev_class_t *)condition;
2104 if(*devclass == (dev_class_t)node->devclass) {
2111 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2112 if(condition == node->submesh) {
2124 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2125 const struct time_range *range = condition;
2126 time_t start = node->last_reachable;
2127 time_t end = node->last_unreachable;
2137 if(range->end >= range->start) {
2138 return start <= range->end && end >= range->start;
2140 return start > range->start || end < range->end;
2144 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) {
2145 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2146 meshlink_errno = MESHLINK_EINVAL;
2150 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2153 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2154 if(!mesh || !submesh || !nmemb) {
2155 meshlink_errno = MESHLINK_EINVAL;
2159 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2162 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) {
2163 if(!mesh || !nmemb) {
2164 meshlink_errno = MESHLINK_EINVAL;
2168 struct time_range range = {start, end};
2170 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2173 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2174 if(!mesh || !node) {
2175 meshlink_errno = MESHLINK_EINVAL;
2179 dev_class_t devclass;
2181 pthread_mutex_lock(&mesh->mutex);
2183 devclass = ((node_t *)node)->devclass;
2185 pthread_mutex_unlock(&mesh->mutex);
2190 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2191 if(!mesh || !node) {
2192 meshlink_errno = MESHLINK_EINVAL;
2196 node_t *n = (node_t *)node;
2198 meshlink_submesh_t *s;
2200 s = (meshlink_submesh_t *)n->submesh;
2205 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2206 if(!mesh || !node) {
2207 meshlink_errno = MESHLINK_EINVAL;
2211 node_t *n = (node_t *)node;
2214 pthread_mutex_lock(&mesh->mutex);
2215 reachable = n->status.reachable && !n->status.blacklisted;
2217 if(last_reachable) {
2218 *last_reachable = n->last_reachable;
2221 if(last_unreachable) {
2222 *last_unreachable = n->last_unreachable;
2225 pthread_mutex_unlock(&mesh->mutex);
2230 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2231 if(!mesh || !data || !len || !signature || !siglen) {
2232 meshlink_errno = MESHLINK_EINVAL;
2236 if(*siglen < MESHLINK_SIGLEN) {
2237 meshlink_errno = MESHLINK_EINVAL;
2241 pthread_mutex_lock(&mesh->mutex);
2243 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2244 meshlink_errno = MESHLINK_EINTERNAL;
2245 pthread_mutex_unlock(&mesh->mutex);
2249 *siglen = MESHLINK_SIGLEN;
2250 pthread_mutex_unlock(&mesh->mutex);
2254 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2255 if(!mesh || !data || !len || !signature) {
2256 meshlink_errno = MESHLINK_EINVAL;
2260 if(siglen != MESHLINK_SIGLEN) {
2261 meshlink_errno = MESHLINK_EINVAL;
2265 pthread_mutex_lock(&mesh->mutex);
2269 struct node_t *n = (struct node_t *)source;
2271 if(!node_read_public_key(mesh, n)) {
2272 meshlink_errno = MESHLINK_EINTERNAL;
2275 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2278 pthread_mutex_unlock(&mesh->mutex);
2282 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2283 pthread_mutex_lock(&mesh->mutex);
2285 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2288 // TODO: Update invitation key if necessary?
2291 pthread_mutex_unlock(&mesh->mutex);
2293 return mesh->invitation_key;
2296 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2297 if(!mesh || !node || !address) {
2298 meshlink_errno = MESHLINK_EINVAL;
2302 if(!is_valid_hostname(address)) {
2303 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2304 meshlink_errno = MESHLINK_EINVAL;
2308 if(port && !is_valid_port(port)) {
2309 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2310 meshlink_errno = MESHLINK_EINVAL;
2314 char *canonical_address;
2317 xasprintf(&canonical_address, "%s %s", address, port);
2319 canonical_address = xstrdup(address);
2322 pthread_mutex_lock(&mesh->mutex);
2324 node_t *n = (node_t *)node;
2325 free(n->canonical_address);
2326 n->canonical_address = canonical_address;
2328 if(!node_write_config(mesh, n)) {
2329 pthread_mutex_unlock(&mesh->mutex);
2333 pthread_mutex_unlock(&mesh->mutex);
2335 return config_sync(mesh, "current");
2338 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2339 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2342 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2344 meshlink_errno = MESHLINK_EINVAL;
2348 char *address = meshlink_get_external_address(mesh);
2354 bool rval = meshlink_add_address(mesh, address);
2360 int meshlink_get_port(meshlink_handle_t *mesh) {
2362 meshlink_errno = MESHLINK_EINVAL;
2367 meshlink_errno = MESHLINK_EINTERNAL;
2373 pthread_mutex_lock(&mesh->mutex);
2374 port = atoi(mesh->myport);
2375 pthread_mutex_unlock(&mesh->mutex);
2380 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2381 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2382 meshlink_errno = MESHLINK_EINVAL;
2386 if(mesh->myport && port == atoi(mesh->myport)) {
2390 if(!try_bind(port)) {
2391 meshlink_errno = MESHLINK_ENETWORK;
2395 devtool_trybind_probe();
2399 pthread_mutex_lock(&mesh->mutex);
2401 if(mesh->threadstarted) {
2402 meshlink_errno = MESHLINK_EINVAL;
2407 xasprintf(&mesh->myport, "%d", port);
2409 /* Close down the network. This also deletes mesh->self. */
2410 close_network_connections(mesh);
2412 /* Recreate mesh->self. */
2413 mesh->self = new_node();
2414 mesh->self->name = xstrdup(mesh->name);
2415 mesh->self->devclass = mesh->devclass;
2416 mesh->self->session_id = mesh->session_id;
2417 xasprintf(&mesh->myport, "%d", port);
2419 if(!node_read_public_key(mesh, mesh->self)) {
2420 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2421 meshlink_errno = MESHLINK_ESTORAGE;
2422 free_node(mesh->self);
2425 } else if(!setup_network(mesh)) {
2426 meshlink_errno = MESHLINK_ENETWORK;
2430 /* Rebuild our own list of recent addresses */
2431 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2432 add_local_addresses(mesh);
2434 /* Write meshlink.conf with the updated port number */
2435 write_main_config_files(mesh);
2437 rval = config_sync(mesh, "current");
2440 pthread_mutex_unlock(&mesh->mutex);
2442 return rval && meshlink_get_port(mesh) == port;
2445 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2446 mesh->invitation_timeout = timeout;
2449 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2450 meshlink_submesh_t *s = NULL;
2453 meshlink_errno = MESHLINK_EINVAL;
2458 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2461 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2462 meshlink_errno = MESHLINK_EINVAL;
2466 s = (meshlink_submesh_t *)mesh->self->submesh;
2469 pthread_mutex_lock(&mesh->mutex);
2471 // Check validity of the new node's name
2472 if(!check_id(name)) {
2473 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2474 meshlink_errno = MESHLINK_EINVAL;
2475 pthread_mutex_unlock(&mesh->mutex);
2479 // Ensure no host configuration file with that name exists
2480 if(config_exists(mesh, "current", name)) {
2481 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2482 meshlink_errno = MESHLINK_EEXIST;
2483 pthread_mutex_unlock(&mesh->mutex);
2487 // Ensure no other nodes know about this name
2488 if(lookup_node(mesh, name)) {
2489 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2490 meshlink_errno = MESHLINK_EEXIST;
2491 pthread_mutex_unlock(&mesh->mutex);
2495 // Get the local address
2496 char *address = get_my_hostname(mesh, flags);
2499 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2500 meshlink_errno = MESHLINK_ERESOLV;
2501 pthread_mutex_unlock(&mesh->mutex);
2505 if(!refresh_invitation_key(mesh)) {
2506 meshlink_errno = MESHLINK_EINTERNAL;
2507 pthread_mutex_unlock(&mesh->mutex);
2511 // If we changed our own host config file, write it out now
2512 if(mesh->self->status.dirty) {
2513 if(!node_write_config(mesh, mesh->self)) {
2514 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2515 pthread_mutex_unlock(&mesh->mutex);
2522 // Create a hash of the key.
2523 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2524 sha512(fingerprint, strlen(fingerprint), hash);
2525 b64encode_urlsafe(hash, hash, 18);
2527 // Create a random cookie for this invitation.
2529 randomize(cookie, 18);
2531 // Create a filename that doesn't reveal the cookie itself
2532 char buf[18 + strlen(fingerprint)];
2533 char cookiehash[64];
2534 memcpy(buf, cookie, 18);
2535 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2536 sha512(buf, sizeof(buf), cookiehash);
2537 b64encode_urlsafe(cookiehash, cookiehash, 18);
2539 b64encode_urlsafe(cookie, cookie, 18);
2543 /* Construct the invitation file */
2544 uint8_t outbuf[4096];
2545 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2547 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2548 packmsg_add_str(&inv, name);
2549 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2550 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2552 /* TODO: Add several host config files to bootstrap connections.
2553 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2554 * and are not blacklisted.
2556 config_t configs[5];
2557 memset(configs, 0, sizeof(configs));
2560 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2564 /* Append host config files to the invitation file */
2565 packmsg_add_array(&inv, count);
2567 for(int i = 0; i < count; i++) {
2568 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2569 config_free(&configs[i]);
2572 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2574 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2575 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2576 meshlink_errno = MESHLINK_ESTORAGE;
2577 pthread_mutex_unlock(&mesh->mutex);
2581 // Create an URL from the local address, key hash and cookie
2583 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2586 pthread_mutex_unlock(&mesh->mutex);
2590 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2591 return meshlink_invite_ex(mesh, submesh, name, 0);
2594 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2595 if(!mesh || !invitation) {
2596 meshlink_errno = MESHLINK_EINVAL;
2600 join_state_t state = {
2605 ecdsa_t *key = NULL;
2606 ecdsa_t *hiskey = NULL;
2608 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2609 char copy[strlen(invitation) + 1];
2611 pthread_mutex_lock(&mesh->mutex);
2613 //Before doing meshlink_join make sure we are not connected to another mesh
2614 if(mesh->threadstarted) {
2615 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2616 meshlink_errno = MESHLINK_EINVAL;
2620 // 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.
2621 if(mesh->nodes->count > 1) {
2622 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2623 meshlink_errno = MESHLINK_EINVAL;
2627 strcpy(copy, invitation);
2629 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2631 char *slash = strchr(copy, '/');
2639 if(strlen(slash) != 48) {
2643 char *address = copy;
2646 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2650 // Generate a throw-away key for the invitation.
2651 key = ecdsa_generate();
2654 meshlink_errno = MESHLINK_EINTERNAL;
2658 char *b64key = ecdsa_get_base64_public_key(key);
2661 while(address && *address) {
2662 // We allow commas in the address part to support multiple addresses in one invitation URL.
2663 comma = strchr(address, ',');
2669 // Split of the port
2670 port = strrchr(address, ':');
2678 // IPv6 address are enclosed in brackets, per RFC 3986
2679 if(*address == '[') {
2681 char *bracket = strchr(address, ']');
2694 // Connect to the meshlink daemon mentioned in the URL.
2695 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2698 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2699 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2701 if(state.sock == -1) {
2702 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2703 meshlink_errno = MESHLINK_ENETWORK;
2707 set_timeout(state.sock, 5000);
2709 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2710 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2711 meshlink_errno = MESHLINK_ENETWORK;
2712 closesocket(state.sock);
2720 meshlink_errno = MESHLINK_ERESOLV;
2723 if(state.sock != -1 || !comma) {
2730 if(state.sock == -1) {
2734 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2736 // Tell him we have an invitation, and give him our throw-away key.
2740 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2741 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2742 meshlink_errno = MESHLINK_ENETWORK;
2748 char hisname[4096] = "";
2749 int code, hismajor, hisminor = 0;
2751 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) {
2752 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2753 meshlink_errno = MESHLINK_ENETWORK;
2757 // Check if the hash of the key he gave us matches the hash in the URL.
2758 char *fingerprint = state.line + 2;
2761 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2762 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2763 meshlink_errno = MESHLINK_EINTERNAL;
2767 if(memcmp(hishash, state.hash, 18)) {
2768 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2769 meshlink_errno = MESHLINK_EPEER;
2773 hiskey = ecdsa_set_base64_public_key(fingerprint);
2776 meshlink_errno = MESHLINK_EINTERNAL;
2780 // Start an SPTPS session
2781 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2782 meshlink_errno = MESHLINK_EINTERNAL;
2786 // Feed rest of input buffer to SPTPS
2787 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2788 meshlink_errno = MESHLINK_EPEER;
2793 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2795 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2797 if(errno == EINTR) {
2801 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2802 meshlink_errno = MESHLINK_ENETWORK;
2806 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2807 meshlink_errno = MESHLINK_EPEER;
2812 if(!state.success) {
2813 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2814 meshlink_errno = MESHLINK_EPEER;
2818 sptps_stop(&state.sptps);
2821 closesocket(state.sock);
2823 pthread_mutex_unlock(&mesh->mutex);
2827 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2828 meshlink_errno = MESHLINK_EINVAL;
2830 sptps_stop(&state.sptps);
2834 if(state.sock != -1) {
2835 closesocket(state.sock);
2838 pthread_mutex_unlock(&mesh->mutex);
2842 char *meshlink_export(meshlink_handle_t *mesh) {
2844 meshlink_errno = MESHLINK_EINVAL;
2848 // Create a config file on the fly.
2851 packmsg_output_t out = {buf, sizeof(buf)};
2852 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2853 packmsg_add_str(&out, mesh->name);
2854 packmsg_add_str(&out, CORE_MESH);
2856 pthread_mutex_lock(&mesh->mutex);
2858 packmsg_add_int32(&out, mesh->self->devclass);
2859 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2860 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2861 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2865 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2866 if(mesh->self->recent[i].sa.sa_family) {
2873 packmsg_add_array(&out, count);
2875 for(uint32_t i = 0; i < count; i++) {
2876 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2879 packmsg_add_int64(&out, 0);
2880 packmsg_add_int64(&out, 0);
2882 pthread_mutex_unlock(&mesh->mutex);
2884 if(!packmsg_output_ok(&out)) {
2885 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2886 meshlink_errno = MESHLINK_EINTERNAL;
2890 // Prepare a base64-encoded packmsg array containing our config file
2892 uint32_t len = packmsg_output_size(&out, buf);
2893 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2894 uint8_t *buf2 = xmalloc(len2);
2895 packmsg_output_t out2 = {buf2, len2};
2896 packmsg_add_array(&out2, 1);
2897 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2899 if(!packmsg_output_ok(&out2)) {
2900 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2901 meshlink_errno = MESHLINK_EINTERNAL;
2906 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2908 return (char *)buf2;
2911 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2912 if(!mesh || !data) {
2913 meshlink_errno = MESHLINK_EINVAL;
2917 size_t datalen = strlen(data);
2918 uint8_t *buf = xmalloc(datalen);
2919 int buflen = b64decode(data, buf, datalen);
2922 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2923 meshlink_errno = MESHLINK_EPEER;
2927 packmsg_input_t in = {buf, buflen};
2928 uint32_t count = packmsg_get_array(&in);
2931 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2932 meshlink_errno = MESHLINK_EPEER;
2936 pthread_mutex_lock(&mesh->mutex);
2940 uint32_t len = packmsg_get_bin_raw(&in, &data);
2946 packmsg_input_t in2 = {data, len};
2947 uint32_t version = packmsg_get_uint32(&in2);
2948 char *name = packmsg_get_str_dup(&in2);
2950 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2952 packmsg_input_invalidate(&in);
2956 if(!check_id(name)) {
2961 node_t *n = lookup_node(mesh, name);
2964 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2972 config_t config = {data, len};
2974 if(!node_read_from_config(mesh, n, &config)) {
2976 packmsg_input_invalidate(&in);
2980 /* Clear the reachability times, since we ourself have never seen these nodes yet */
2981 n->last_reachable = 0;
2982 n->last_unreachable = 0;
2984 if(!node_write_config(mesh, n)) {
2992 pthread_mutex_unlock(&mesh->mutex);
2996 if(!packmsg_done(&in)) {
2997 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2998 meshlink_errno = MESHLINK_EPEER;
3002 if(!config_sync(mesh, "current")) {
3009 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3010 if(n == mesh->self) {
3011 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3012 meshlink_errno = MESHLINK_EINVAL;
3016 if(n->status.blacklisted) {
3017 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3021 n->status.blacklisted = true;
3023 /* Immediately shut down any connections we have with the blacklisted node.
3024 * We can't call terminate_connection(), because we might be called from a callback function.
3026 for list_each(connection_t, c, mesh->connections) {
3028 shutdown(c->socket, SHUT_RDWR);
3032 utcp_abort_all_connections(n->utcp);
3038 n->status.udp_confirmed = false;
3040 if(n->status.reachable) {
3041 n->last_unreachable = mesh->loop.now.tv_sec;
3044 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3045 * manually call the status callback if necessary.
3047 if(n->status.reachable && mesh->node_status_cb) {
3048 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3051 return node_write_config(mesh, n) && config_sync(mesh, "current");
3054 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3055 if(!mesh || !node) {
3056 meshlink_errno = MESHLINK_EINVAL;
3060 pthread_mutex_lock(&mesh->mutex);
3062 if(!blacklist(mesh, (node_t *)node)) {
3063 pthread_mutex_unlock(&mesh->mutex);
3067 pthread_mutex_unlock(&mesh->mutex);
3069 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3073 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3074 if(!mesh || !name) {
3075 meshlink_errno = MESHLINK_EINVAL;
3079 pthread_mutex_lock(&mesh->mutex);
3081 node_t *n = lookup_node(mesh, (char *)name);
3085 n->name = xstrdup(name);
3089 if(!blacklist(mesh, (node_t *)n)) {
3090 pthread_mutex_unlock(&mesh->mutex);
3094 pthread_mutex_unlock(&mesh->mutex);
3096 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3100 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3101 if(n == mesh->self) {
3102 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3103 meshlink_errno = MESHLINK_EINVAL;
3107 if(!n->status.blacklisted) {
3108 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3112 n->status.blacklisted = false;
3114 if(n->status.reachable) {
3115 n->last_reachable = mesh->loop.now.tv_sec;
3116 update_node_status(mesh, n);
3119 return node_write_config(mesh, n) && config_sync(mesh, "current");
3122 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3123 if(!mesh || !node) {
3124 meshlink_errno = MESHLINK_EINVAL;
3128 pthread_mutex_lock(&mesh->mutex);
3130 if(!whitelist(mesh, (node_t *)node)) {
3131 pthread_mutex_unlock(&mesh->mutex);
3135 pthread_mutex_unlock(&mesh->mutex);
3137 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3141 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3142 if(!mesh || !name) {
3143 meshlink_errno = MESHLINK_EINVAL;
3147 pthread_mutex_lock(&mesh->mutex);
3149 node_t *n = lookup_node(mesh, (char *)name);
3153 n->name = xstrdup(name);
3157 if(!whitelist(mesh, (node_t *)n)) {
3158 pthread_mutex_unlock(&mesh->mutex);
3162 pthread_mutex_unlock(&mesh->mutex);
3164 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3168 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3169 mesh->default_blacklist = blacklist;
3172 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3173 if(!mesh || !node) {
3174 meshlink_errno = MESHLINK_EINVAL;
3178 node_t *n = (node_t *)node;
3180 pthread_mutex_lock(&mesh->mutex);
3182 /* Check that the node is not reachable */
3183 if(n->status.reachable || n->connection) {
3184 pthread_mutex_unlock(&mesh->mutex);
3185 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3189 /* Check that we don't have any active UTCP connections */
3190 if(n->utcp && utcp_is_active(n->utcp)) {
3191 pthread_mutex_unlock(&mesh->mutex);
3192 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3196 /* Check that we have no active connections to this node */
3197 for list_each(connection_t, c, mesh->connections) {
3199 pthread_mutex_unlock(&mesh->mutex);
3200 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3205 /* Remove any pending outgoings to this node */
3206 if(mesh->outgoings) {
3207 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3208 if(outgoing->node == n) {
3209 list_delete_node(mesh->outgoings, node);
3214 /* Delete the config file for this node */
3215 if(!config_delete(mesh, "current", n->name)) {
3216 pthread_mutex_unlock(&mesh->mutex);
3220 /* Delete the node struct and any remaining edges referencing this node */
3223 pthread_mutex_unlock(&mesh->mutex);
3225 return config_sync(mesh, "current");
3228 /* Hint that a hostname may be found at an address
3229 * See header file for detailed comment.
3231 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3232 if(!mesh || !node || !addr) {
3233 meshlink_errno = EINVAL;
3237 pthread_mutex_lock(&mesh->mutex);
3239 node_t *n = (node_t *)node;
3241 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3242 if(!node_write_config(mesh, n)) {
3243 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3247 pthread_mutex_unlock(&mesh->mutex);
3248 // @TODO do we want to fire off a connection attempt right away?
3251 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3253 node_t *n = utcp->priv;
3254 meshlink_handle_t *mesh = n->mesh;
3255 return mesh->channel_accept_cb;
3258 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3260 if(aio->cb.buffer) {
3261 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3265 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3270 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3271 meshlink_channel_t *channel = connection->priv;
3277 node_t *n = channel->node;
3278 meshlink_handle_t *mesh = n->mesh;
3280 if(n->status.destroyed) {
3281 meshlink_channel_close(mesh, channel);
3285 const char *p = data;
3288 while(channel->aio_receive) {
3289 meshlink_aio_buffer_t *aio = channel->aio_receive;
3290 size_t todo = aio->len - aio->done;
3297 memcpy((char *)aio->data + aio->done, p, todo);
3299 ssize_t result = write(aio->fd, p, todo);
3308 if(aio->done == aio->len) {
3309 channel->aio_receive = aio->next;
3310 aio_signal(mesh, channel, aio);
3322 if(channel->receive_cb) {
3323 channel->receive_cb(mesh, channel, p, left);
3329 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3330 node_t *n = utcp_connection->utcp->priv;
3336 meshlink_handle_t *mesh = n->mesh;
3338 if(!mesh->channel_accept_cb) {
3342 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3344 channel->c = utcp_connection;
3346 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3347 utcp_accept(utcp_connection, channel_recv, channel);
3353 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3354 node_t *n = utcp->priv;
3356 if(n->status.destroyed) {
3360 meshlink_handle_t *mesh = n->mesh;
3361 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3364 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3365 if(!mesh || !channel) {
3366 meshlink_errno = MESHLINK_EINVAL;
3370 channel->receive_cb = cb;
3373 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3375 node_t *n = (node_t *)source;
3381 utcp_recv(n->utcp, data, len);
3384 static void channel_poll(struct utcp_connection *connection, size_t len) {
3385 meshlink_channel_t *channel = connection->priv;
3391 node_t *n = channel->node;
3392 meshlink_handle_t *mesh = n->mesh;
3393 meshlink_aio_buffer_t *aio = channel->aio_send;
3396 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3397 size_t left = aio->len - aio->done;
3405 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3408 size_t todo = utcp_get_sndbuf_free(connection);
3414 if(todo > sizeof(buf)) {
3418 ssize_t result = read(aio->fd, buf, todo);
3421 sent = utcp_send(connection, buf, result);
3431 /* If the buffer is now completely sent, call the callback and dispose of it. */
3432 if(aio->done >= aio->len) {
3433 channel->aio_send = aio->next;
3434 aio_signal(mesh, channel, aio);
3438 if(channel->poll_cb) {
3439 channel->poll_cb(mesh, channel, len);
3441 utcp_set_poll_cb(connection, NULL);
3446 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3447 if(!mesh || !channel) {
3448 meshlink_errno = MESHLINK_EINVAL;
3452 pthread_mutex_lock(&mesh->mutex);
3453 channel->poll_cb = cb;
3454 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3455 pthread_mutex_unlock(&mesh->mutex);
3458 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3460 meshlink_errno = MESHLINK_EINVAL;
3464 pthread_mutex_lock(&mesh->mutex);
3465 mesh->channel_accept_cb = cb;
3466 mesh->receive_cb = channel_receive;
3468 for splay_each(node_t, n, mesh->nodes) {
3469 if(!n->utcp && n != mesh->self) {
3470 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3474 pthread_mutex_unlock(&mesh->mutex);
3477 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3481 meshlink_errno = MESHLINK_EINVAL;
3485 pthread_mutex_lock(&mesh->mutex);
3486 utcp_set_sndbuf(channel->c, size);
3487 pthread_mutex_unlock(&mesh->mutex);
3490 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3494 meshlink_errno = MESHLINK_EINVAL;
3498 pthread_mutex_lock(&mesh->mutex);
3499 utcp_set_rcvbuf(channel->c, size);
3500 pthread_mutex_unlock(&mesh->mutex);
3503 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) {
3505 abort(); // TODO: handle non-NULL data
3508 if(!mesh || !node) {
3509 meshlink_errno = MESHLINK_EINVAL;
3513 pthread_mutex_lock(&mesh->mutex);
3515 node_t *n = (node_t *)node;
3518 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3519 mesh->receive_cb = channel_receive;
3522 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3523 pthread_mutex_unlock(&mesh->mutex);
3528 if(n->status.blacklisted) {
3529 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3530 meshlink_errno = MESHLINK_EBLACKLISTED;
3531 pthread_mutex_unlock(&mesh->mutex);
3535 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3537 channel->receive_cb = cb;
3540 channel->priv = (void *)data;
3543 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3545 pthread_mutex_unlock(&mesh->mutex);
3548 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3556 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) {
3557 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3560 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3561 if(!mesh || !channel) {
3562 meshlink_errno = MESHLINK_EINVAL;
3566 pthread_mutex_lock(&mesh->mutex);
3567 utcp_shutdown(channel->c, direction);
3568 pthread_mutex_unlock(&mesh->mutex);
3571 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3572 if(!mesh || !channel) {
3573 meshlink_errno = MESHLINK_EINVAL;
3577 pthread_mutex_lock(&mesh->mutex);
3579 utcp_close(channel->c);
3581 /* Clean up any outstanding AIO buffers. */
3582 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3584 aio_signal(mesh, channel, aio);
3588 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3590 aio_signal(mesh, channel, aio);
3594 pthread_mutex_unlock(&mesh->mutex);
3599 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3600 if(!mesh || !channel) {
3601 meshlink_errno = MESHLINK_EINVAL;
3610 meshlink_errno = MESHLINK_EINVAL;
3614 // TODO: more finegrained locking.
3615 // Ideally we want to put the data into the UTCP connection's send buffer.
3616 // Then, preferably only if there is room in the receiver window,
3617 // kick the meshlink thread to go send packets.
3621 pthread_mutex_lock(&mesh->mutex);
3623 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3624 if(channel->aio_send) {
3627 retval = utcp_send(channel->c, data, len);
3630 pthread_mutex_unlock(&mesh->mutex);
3633 meshlink_errno = MESHLINK_ENETWORK;
3639 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) {
3640 if(!mesh || !channel) {
3641 meshlink_errno = MESHLINK_EINVAL;
3646 meshlink_errno = MESHLINK_EINVAL;
3650 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3653 aio->cb.buffer = cb;
3656 pthread_mutex_lock(&mesh->mutex);
3658 /* Append the AIO buffer descriptor to the end of the chain */
3659 meshlink_aio_buffer_t **p = &channel->aio_send;
3667 /* Ensure the poll callback is set, and call it right now to push data if possible */
3668 utcp_set_poll_cb(channel->c, channel_poll);
3669 channel_poll(channel->c, len);
3671 pthread_mutex_unlock(&mesh->mutex);
3676 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) {
3677 if(!mesh || !channel) {
3678 meshlink_errno = MESHLINK_EINVAL;
3682 if(!len || fd == -1) {
3683 meshlink_errno = MESHLINK_EINVAL;
3687 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
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_receive(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len, meshlink_aio_cb_t cb, void *priv) {
3714 if(!mesh || !channel) {
3715 meshlink_errno = MESHLINK_EINVAL;
3720 meshlink_errno = MESHLINK_EINVAL;
3724 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3727 aio->cb.buffer = cb;
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_receive;
3741 pthread_mutex_unlock(&mesh->mutex);
3746 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) {
3747 if(!mesh || !channel) {
3748 meshlink_errno = MESHLINK_EINVAL;
3752 if(!len || fd == -1) {
3753 meshlink_errno = MESHLINK_EINVAL;
3757 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3763 pthread_mutex_lock(&mesh->mutex);
3765 /* Append the AIO buffer descriptor to the end of the chain */
3766 meshlink_aio_buffer_t **p = &channel->aio_receive;
3774 pthread_mutex_unlock(&mesh->mutex);
3779 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3780 if(!mesh || !channel) {
3781 meshlink_errno = MESHLINK_EINVAL;
3785 return channel->c->flags;
3788 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3789 if(!mesh || !channel) {
3790 meshlink_errno = MESHLINK_EINVAL;
3794 return utcp_get_sendq(channel->c);
3797 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3798 if(!mesh || !channel) {
3799 meshlink_errno = MESHLINK_EINVAL;
3803 return utcp_get_recvq(channel->c);
3806 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3807 if(!mesh || !node) {
3808 meshlink_errno = MESHLINK_EINVAL;
3812 node_t *n = (node_t *)node;
3814 pthread_mutex_lock(&mesh->mutex);
3817 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3820 utcp_set_user_timeout(n->utcp, timeout);
3822 pthread_mutex_unlock(&mesh->mutex);
3825 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3826 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3827 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3830 if(mesh->node_status_cb) {
3831 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3834 if(mesh->node_pmtu_cb) {
3835 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3839 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3840 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3841 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3845 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3846 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3850 n->status.duplicate = true;
3851 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3854 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3858 meshlink_errno = MESHLINK_EINVAL;
3862 pthread_mutex_lock(&mesh->mutex);
3864 if(mesh->discovery == enable) {
3868 if(mesh->threadstarted) {
3870 discovery_start(mesh);
3872 discovery_stop(mesh);
3876 mesh->discovery = enable;
3879 pthread_mutex_unlock(&mesh->mutex);
3883 meshlink_errno = MESHLINK_ENOTSUP;
3887 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3888 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3889 meshlink_errno = EINVAL;
3893 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3894 meshlink_errno = EINVAL;
3898 pthread_mutex_lock(&mesh->mutex);
3899 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3900 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3901 pthread_mutex_unlock(&mesh->mutex);
3904 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3905 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3906 meshlink_errno = EINVAL;
3910 if(fast_retry_period < 0) {
3911 meshlink_errno = EINVAL;
3915 pthread_mutex_lock(&mesh->mutex);
3916 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3917 pthread_mutex_unlock(&mesh->mutex);
3920 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3922 meshlink_errno = EINVAL;
3926 pthread_mutex_lock(&mesh->mutex);
3927 mesh->inviter_commits_first = inviter_commits_first;
3928 pthread_mutex_unlock(&mesh->mutex);
3931 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3934 if(!mesh->connections || !mesh->loop.running) {
3941 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3942 // We should only call the callback function if we are in the background thread.
3943 if(!mesh->error_cb) {
3947 if(!mesh->threadstarted) {
3951 if(mesh->thread == pthread_self()) {
3952 mesh->error_cb(mesh, meshlink_errno);
3956 static void __attribute__((constructor)) meshlink_init(void) {
3960 static void __attribute__((destructor)) meshlink_exit(void) {