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 /* Try to bind to TCP. */
545 int tcp_fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
551 int result = bind(tcp_fd, aip->ai_addr, aip->ai_addrlen);
555 if(errno == EADDRINUSE) {
556 /* If this port is in use for any address family, avoid it. */
564 /* If TCP worked, then we require that UDP works as well. */
566 int udp_fd = socket(aip->ai_family, SOCK_DGRAM, IPPROTO_UDP);
573 result = bind(udp_fd, aip->ai_addr, aip->ai_addrlen);
588 static int check_port(meshlink_handle_t *mesh) {
589 for(int i = 0; i < 1000; i++) {
590 int port = 0x1000 + prng(mesh, 0x8000);
594 xasprintf(&mesh->myport, "%d", port);
599 meshlink_errno = MESHLINK_ENETWORK;
600 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
604 static bool write_main_config_files(meshlink_handle_t *mesh) {
605 if(!mesh->confbase) {
611 /* Write the main config file */
612 packmsg_output_t out = {buf, sizeof buf};
614 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
615 packmsg_add_str(&out, mesh->name);
616 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
617 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
618 packmsg_add_uint16(&out, atoi(mesh->myport));
620 if(!packmsg_output_ok(&out)) {
624 config_t config = {buf, packmsg_output_size(&out, buf)};
626 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
630 /* Write our own host config file */
631 if(!node_write_config(mesh, mesh->self)) {
639 meshlink_handle_t *mesh;
641 char cookie[18 + 32];
652 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
653 meshlink_handle_t *mesh = state->mesh;
654 packmsg_input_t in = {buf, len};
655 uint32_t version = packmsg_get_uint32(&in);
657 if(version != MESHLINK_INVITATION_VERSION) {
658 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
662 char *name = packmsg_get_str_dup(&in);
663 packmsg_skip_element(&in); /* submesh */
664 dev_class_t devclass = packmsg_get_int32(&in);
665 uint32_t count = packmsg_get_array(&in);
668 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
672 if(!check_id(name)) {
673 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
679 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
685 free(mesh->self->name);
687 mesh->self->name = xstrdup(name);
688 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
690 // Initialize configuration directory
691 if(!config_init(mesh, "current")) {
695 if(!write_main_config_files(mesh)) {
699 // Write host config files
700 for(uint32_t i = 0; i < count; i++) {
702 uint32_t len = packmsg_get_bin_raw(&in, &data);
705 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
709 packmsg_input_t in2 = {data, len};
710 uint32_t version = packmsg_get_uint32(&in2);
711 char *name = packmsg_get_str_dup(&in2);
713 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
715 packmsg_input_invalidate(&in);
719 if(!check_id(name)) {
724 if(!strcmp(name, mesh->name)) {
725 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
727 meshlink_errno = MESHLINK_EPEER;
731 node_t *n = new_node();
734 config_t config = {data, len};
736 if(!node_read_from_config(mesh, n, &config)) {
738 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
739 meshlink_errno = MESHLINK_EPEER;
744 /* The first host config file is of the inviter itself;
745 * remember the address we are currently using for the invitation connection.
748 socklen_t salen = sizeof(sa);
750 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
751 node_add_recent_address(mesh, n, &sa);
755 /* Clear the reachability times, since we ourself have never seen these nodes yet */
756 n->last_reachable = 0;
757 n->last_unreachable = 0;
759 if(!node_write_config(mesh, n)) {
767 /* Ensure the configuration directory metadata is on disk */
768 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
772 if(!mesh->inviter_commits_first) {
773 devtool_set_inviter_commits_first(false);
776 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
778 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
783 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
785 join_state_t *state = handle;
786 const char *ptr = data;
789 int result = send(state->sock, ptr, len, 0);
791 if(result == -1 && errno == EINTR) {
793 } else if(result <= 0) {
804 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
805 join_state_t *state = handle;
806 meshlink_handle_t *mesh = state->mesh;
808 if(mesh->inviter_commits_first) {
810 case SPTPS_HANDSHAKE:
811 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
817 if(!finalize_join(state, msg, len)) {
821 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
822 shutdown(state->sock, SHUT_RDWR);
823 state->success = true;
831 case SPTPS_HANDSHAKE:
832 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
835 return finalize_join(state, msg, len);
838 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
839 shutdown(state->sock, SHUT_RDWR);
840 state->success = true;
851 static bool recvline(join_state_t *state) {
852 char *newline = NULL;
854 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
855 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
857 if(result == -1 && errno == EINTR) {
859 } else if(result <= 0) {
863 state->blen += result;
866 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
870 size_t len = newline - state->buffer;
872 memcpy(state->line, state->buffer, len);
873 state->line[len] = 0;
874 memmove(state->buffer, newline + 1, state->blen - len - 1);
875 state->blen -= len + 1;
880 static bool sendline(int fd, char *format, ...) {
886 va_start(ap, format);
887 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
890 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
898 int result = send(fd, p, blen, MSG_NOSIGNAL);
900 if(result == -1 && errno == EINTR) {
902 } else if(result <= 0) {
913 static const char *errstr[] = {
914 [MESHLINK_OK] = "No error",
915 [MESHLINK_EINVAL] = "Invalid argument",
916 [MESHLINK_ENOMEM] = "Out of memory",
917 [MESHLINK_ENOENT] = "No such node",
918 [MESHLINK_EEXIST] = "Node already exists",
919 [MESHLINK_EINTERNAL] = "Internal error",
920 [MESHLINK_ERESOLV] = "Could not resolve hostname",
921 [MESHLINK_ESTORAGE] = "Storage error",
922 [MESHLINK_ENETWORK] = "Network error",
923 [MESHLINK_EPEER] = "Error communicating with peer",
924 [MESHLINK_ENOTSUP] = "Operation not supported",
925 [MESHLINK_EBUSY] = "MeshLink instance already in use",
926 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
929 const char *meshlink_strerror(meshlink_errno_t err) {
930 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
931 return "Invalid error code";
937 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
938 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
940 mesh->private_key = ecdsa_generate();
941 mesh->invitation_key = ecdsa_generate();
943 if(!mesh->private_key || !mesh->invitation_key) {
944 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
945 meshlink_errno = MESHLINK_EINTERNAL;
949 logger(mesh, MESHLINK_DEBUG, "Done.\n");
954 static struct timeval idle(event_loop_t *loop, void *data) {
956 meshlink_handle_t *mesh = data;
957 struct timeval t, tmin = {3600, 0};
959 for splay_each(node_t, n, mesh->nodes) {
964 t = utcp_timeout(n->utcp);
966 if(timercmp(&t, &tmin, <)) {
974 // Get our local address(es) by simulating connecting to an Internet host.
975 static void add_local_addresses(meshlink_handle_t *mesh) {
977 sa.storage.ss_family = AF_UNKNOWN;
978 socklen_t salen = sizeof(sa);
982 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
983 sa.in.sin_port = ntohs(atoi(mesh->myport));
984 node_add_recent_address(mesh, mesh->self, &sa);
991 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
992 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
993 node_add_recent_address(mesh, mesh->self, &sa);
997 static bool meshlink_setup(meshlink_handle_t *mesh) {
998 if(!config_destroy(mesh->confbase, "new")) {
999 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1000 meshlink_errno = MESHLINK_ESTORAGE;
1004 if(!config_destroy(mesh->confbase, "old")) {
1005 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1006 meshlink_errno = MESHLINK_ESTORAGE;
1010 if(!config_init(mesh, "current")) {
1011 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1012 meshlink_errno = MESHLINK_ESTORAGE;
1016 if(!ecdsa_keygen(mesh)) {
1017 meshlink_errno = MESHLINK_EINTERNAL;
1021 if(check_port(mesh) == 0) {
1022 meshlink_errno = MESHLINK_ENETWORK;
1026 /* Create a node for ourself */
1028 mesh->self = new_node();
1029 mesh->self->name = xstrdup(mesh->name);
1030 mesh->self->devclass = mesh->devclass;
1031 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1032 mesh->self->session_id = mesh->session_id;
1034 if(!write_main_config_files(mesh)) {
1035 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1036 meshlink_errno = MESHLINK_ESTORAGE;
1040 /* Ensure the configuration directory metadata is on disk */
1041 if(!config_sync(mesh, "current")) {
1048 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1051 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1052 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1056 packmsg_input_t in = {config.buf, config.len};
1057 const void *private_key;
1058 const void *invitation_key;
1060 uint32_t version = packmsg_get_uint32(&in);
1061 char *name = packmsg_get_str_dup(&in);
1062 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1063 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1064 uint16_t myport = packmsg_get_uint16(&in);
1066 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1067 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1069 config_free(&config);
1075 // TODO: check this?
1076 if(mesh->name && strcmp(mesh->name, name)) {
1077 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1078 meshlink_errno = MESHLINK_ESTORAGE;
1080 config_free(&config);
1088 xasprintf(&mesh->myport, "%u", myport);
1089 mesh->private_key = ecdsa_set_private_key(private_key);
1090 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1091 config_free(&config);
1093 /* Create a node for ourself and read our host configuration file */
1095 mesh->self = new_node();
1096 mesh->self->name = xstrdup(name);
1097 mesh->self->devclass = mesh->devclass;
1098 mesh->self->session_id = mesh->session_id;
1100 if(!node_read_public_key(mesh, mesh->self)) {
1101 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1102 meshlink_errno = MESHLINK_ESTORAGE;
1103 free_node(mesh->self);
1112 static void *setup_network_in_netns_thread(void *arg) {
1113 meshlink_handle_t *mesh = arg;
1115 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1119 bool success = setup_network(mesh);
1120 add_local_addresses(mesh);
1121 return success ? arg : NULL;
1123 #endif // HAVE_SETNS
1125 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1126 if(!confbase || !*confbase) {
1127 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1128 meshlink_errno = MESHLINK_EINVAL;
1132 if(!appname || !*appname) {
1133 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1134 meshlink_errno = MESHLINK_EINVAL;
1138 if(strchr(appname, ' ')) {
1139 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1140 meshlink_errno = MESHLINK_EINVAL;
1144 if(!name || !*name) {
1145 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1146 meshlink_errno = MESHLINK_EINVAL;
1150 if(!check_id(name)) {
1151 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1152 meshlink_errno = MESHLINK_EINVAL;
1156 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1157 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1158 meshlink_errno = MESHLINK_EINVAL;
1162 meshlink_open_params_t *params = xzalloc(sizeof * params);
1164 params->confbase = xstrdup(confbase);
1165 params->name = xstrdup(name);
1166 params->appname = xstrdup(appname);
1167 params->devclass = devclass;
1173 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1175 meshlink_errno = MESHLINK_EINVAL;
1179 params->netns = netns;
1184 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1186 meshlink_errno = MESHLINK_EINVAL;
1190 if((!key && keylen) || (key && !keylen)) {
1191 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1192 meshlink_errno = MESHLINK_EINVAL;
1197 params->keylen = keylen;
1202 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1203 if(!mesh || !new_key || !new_keylen) {
1204 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1205 meshlink_errno = MESHLINK_EINVAL;
1209 pthread_mutex_lock(&mesh->mutex);
1211 // Create hash for the new key
1212 void *new_config_key;
1213 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1215 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1216 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1217 meshlink_errno = MESHLINK_EINTERNAL;
1218 pthread_mutex_unlock(&mesh->mutex);
1222 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1224 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1225 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1226 meshlink_errno = MESHLINK_ESTORAGE;
1227 pthread_mutex_unlock(&mesh->mutex);
1231 devtool_keyrotate_probe(1);
1233 // Rename confbase/current/ to confbase/old
1235 if(!config_rename(mesh, "current", "old")) {
1236 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1237 meshlink_errno = MESHLINK_ESTORAGE;
1238 pthread_mutex_unlock(&mesh->mutex);
1242 devtool_keyrotate_probe(2);
1244 // Rename confbase/new/ to confbase/current
1246 if(!config_rename(mesh, "new", "current")) {
1247 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1248 meshlink_errno = MESHLINK_ESTORAGE;
1249 pthread_mutex_unlock(&mesh->mutex);
1253 devtool_keyrotate_probe(3);
1255 // Cleanup the "old" confbase sub-directory
1257 if(!config_destroy(mesh->confbase, "old")) {
1258 pthread_mutex_unlock(&mesh->mutex);
1262 // Change the mesh handle key with new key
1264 free(mesh->config_key);
1265 mesh->config_key = new_config_key;
1267 pthread_mutex_unlock(&mesh->mutex);
1272 void meshlink_open_params_free(meshlink_open_params_t *params) {
1274 meshlink_errno = MESHLINK_EINVAL;
1278 free(params->confbase);
1280 free(params->appname);
1285 /// Device class traits
1286 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1287 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1288 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1289 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1290 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1293 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1294 if(!confbase || !*confbase) {
1295 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1296 meshlink_errno = MESHLINK_EINVAL;
1300 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1301 meshlink_open_params_t params;
1302 memset(¶ms, 0, sizeof(params));
1304 params.confbase = (char *)confbase;
1305 params.name = (char *)name;
1306 params.appname = (char *)appname;
1307 params.devclass = devclass;
1310 return meshlink_open_ex(¶ms);
1313 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) {
1314 if(!confbase || !*confbase) {
1315 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1316 meshlink_errno = MESHLINK_EINVAL;
1320 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1321 meshlink_open_params_t params;
1322 memset(¶ms, 0, sizeof(params));
1324 params.confbase = (char *)confbase;
1325 params.name = (char *)name;
1326 params.appname = (char *)appname;
1327 params.devclass = devclass;
1330 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1334 return meshlink_open_ex(¶ms);
1337 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1338 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1339 meshlink_open_params_t params;
1340 memset(¶ms, 0, sizeof(params));
1342 params.name = (char *)name;
1343 params.appname = (char *)appname;
1344 params.devclass = devclass;
1347 return meshlink_open_ex(¶ms);
1350 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1351 // Validate arguments provided by the application
1352 bool usingname = false;
1354 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1356 if(!params->appname || !*params->appname) {
1357 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1358 meshlink_errno = MESHLINK_EINVAL;
1362 if(strchr(params->appname, ' ')) {
1363 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1364 meshlink_errno = MESHLINK_EINVAL;
1368 if(!params->name || !*params->name) {
1369 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1371 } else { //check name only if there is a name != NULL
1373 if(!check_id(params->name)) {
1374 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1375 meshlink_errno = MESHLINK_EINVAL;
1382 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1383 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1384 meshlink_errno = MESHLINK_EINVAL;
1388 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1389 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1390 meshlink_errno = MESHLINK_EINVAL;
1394 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1396 if(params->confbase) {
1397 mesh->confbase = xstrdup(params->confbase);
1400 mesh->appname = xstrdup(params->appname);
1401 mesh->devclass = params->devclass;
1402 mesh->discovery = true;
1403 mesh->invitation_timeout = 604800; // 1 week
1404 mesh->netns = params->netns;
1405 mesh->submeshes = NULL;
1406 mesh->log_cb = global_log_cb;
1407 mesh->log_level = global_log_level;
1409 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1412 randomize(&mesh->session_id, sizeof(mesh->session_id));
1413 } while(mesh->session_id == 0);
1415 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1418 mesh->name = xstrdup(params->name);
1423 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1425 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1426 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1427 meshlink_close(mesh);
1428 meshlink_errno = MESHLINK_EINTERNAL;
1434 pthread_mutexattr_t attr;
1435 pthread_mutexattr_init(&attr);
1436 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1437 pthread_mutex_init(&mesh->mutex, &attr);
1439 mesh->threadstarted = false;
1440 event_loop_init(&mesh->loop);
1441 mesh->loop.data = mesh;
1443 meshlink_queue_init(&mesh->outpacketqueue);
1445 // Atomically lock the configuration directory.
1446 if(!main_config_lock(mesh)) {
1447 meshlink_close(mesh);
1451 // If no configuration exists yet, create it.
1453 if(!meshlink_confbase_exists(mesh)) {
1454 if(!meshlink_setup(mesh)) {
1455 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1456 meshlink_close(mesh);
1460 if(!meshlink_read_config(mesh)) {
1461 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1462 meshlink_close(mesh);
1468 struct WSAData wsa_state;
1469 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1472 // Setup up everything
1473 // TODO: we should not open listening sockets yet
1475 bool success = false;
1477 if(mesh->netns != -1) {
1481 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1482 void *retval = NULL;
1483 success = pthread_join(thr, &retval) == 0 && retval;
1487 meshlink_errno = MESHLINK_EINTERNAL;
1490 #endif // HAVE_SETNS
1492 success = setup_network(mesh);
1493 add_local_addresses(mesh);
1497 meshlink_close(mesh);
1498 meshlink_errno = MESHLINK_ENETWORK;
1502 add_local_addresses(mesh);
1504 if(!node_write_config(mesh, mesh->self)) {
1505 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1509 idle_set(&mesh->loop, idle, mesh);
1511 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1515 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1516 meshlink_submesh_t *s = NULL;
1519 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1520 meshlink_errno = MESHLINK_EINVAL;
1524 if(!submesh || !*submesh) {
1525 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1526 meshlink_errno = MESHLINK_EINVAL;
1531 pthread_mutex_lock(&mesh->mutex);
1533 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1535 pthread_mutex_unlock(&mesh->mutex);
1540 static void *meshlink_main_loop(void *arg) {
1541 meshlink_handle_t *mesh = arg;
1543 if(mesh->netns != -1) {
1546 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1547 pthread_cond_signal(&mesh->cond);
1552 pthread_cond_signal(&mesh->cond);
1554 #endif // HAVE_SETNS
1559 if(mesh->discovery) {
1560 discovery_start(mesh);
1565 pthread_mutex_lock(&mesh->mutex);
1567 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1568 pthread_cond_broadcast(&mesh->cond);
1570 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1572 pthread_mutex_unlock(&mesh->mutex);
1577 if(mesh->discovery) {
1578 discovery_stop(mesh);
1586 bool meshlink_start(meshlink_handle_t *mesh) {
1588 meshlink_errno = MESHLINK_EINVAL;
1592 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1594 pthread_mutex_lock(&mesh->mutex);
1597 assert(mesh->private_key);
1598 assert(mesh->self->ecdsa);
1599 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1601 if(mesh->threadstarted) {
1602 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1603 pthread_mutex_unlock(&mesh->mutex);
1607 if(mesh->listen_socket[0].tcp.fd < 0) {
1608 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1609 meshlink_errno = MESHLINK_ENETWORK;
1613 // TODO: open listening sockets first
1615 //Check that a valid name is set
1617 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1618 meshlink_errno = MESHLINK_EINVAL;
1619 pthread_mutex_unlock(&mesh->mutex);
1623 init_outgoings(mesh);
1625 // Start the main thread
1627 event_loop_start(&mesh->loop);
1629 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1630 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1631 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1632 meshlink_errno = MESHLINK_EINTERNAL;
1633 event_loop_stop(&mesh->loop);
1634 pthread_mutex_unlock(&mesh->mutex);
1638 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1639 mesh->threadstarted = true;
1641 // Ensure we are considered reachable
1644 pthread_mutex_unlock(&mesh->mutex);
1648 void meshlink_stop(meshlink_handle_t *mesh) {
1650 meshlink_errno = MESHLINK_EINVAL;
1654 pthread_mutex_lock(&mesh->mutex);
1655 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1657 // Shut down the main thread
1658 event_loop_stop(&mesh->loop);
1660 // Send ourselves a UDP packet to kick the event loop
1661 for(int i = 0; i < mesh->listen_sockets; i++) {
1663 socklen_t salen = sizeof(sa);
1665 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1666 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1670 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1671 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1675 if(mesh->threadstarted) {
1676 // Wait for the main thread to finish
1677 pthread_mutex_unlock(&mesh->mutex);
1678 pthread_join(mesh->thread, NULL);
1679 pthread_mutex_lock(&mesh->mutex);
1681 mesh->threadstarted = false;
1684 // Close all metaconnections
1685 if(mesh->connections) {
1686 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1688 connection_t *c = node->data;
1690 terminate_connection(mesh, c, false);
1694 exit_outgoings(mesh);
1696 // Ensure we are considered unreachable
1701 // Try to write out any changed node config files, ignore errors at this point.
1703 for splay_each(node_t, n, mesh->nodes) {
1704 if(n->status.dirty) {
1705 n->status.dirty = !node_write_config(mesh, n);
1710 pthread_mutex_unlock(&mesh->mutex);
1713 void meshlink_close(meshlink_handle_t *mesh) {
1715 meshlink_errno = MESHLINK_EINVAL;
1719 // stop can be called even if mesh has not been started
1720 meshlink_stop(mesh);
1722 // lock is not released after this
1723 pthread_mutex_lock(&mesh->mutex);
1725 // Close and free all resources used.
1727 close_network_connections(mesh);
1729 logger(mesh, MESHLINK_INFO, "Terminating");
1731 event_loop_exit(&mesh->loop);
1735 if(mesh->confbase) {
1741 ecdsa_free(mesh->invitation_key);
1743 if(mesh->netns != -1) {
1747 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1751 meshlink_queue_exit(&mesh->outpacketqueue);
1754 free(mesh->appname);
1755 free(mesh->confbase);
1756 free(mesh->config_key);
1757 ecdsa_free(mesh->private_key);
1759 main_config_unlock(mesh);
1761 pthread_mutex_unlock(&mesh->mutex);
1762 pthread_mutex_destroy(&mesh->mutex);
1764 memset(mesh, 0, sizeof(*mesh));
1769 bool meshlink_destroy(const char *confbase) {
1771 meshlink_errno = MESHLINK_EINVAL;
1775 /* Exit early if the confbase directory itself doesn't exist */
1776 if(access(confbase, F_OK) && errno == ENOENT) {
1780 /* Take the lock the same way meshlink_open() would. */
1781 char lockfilename[PATH_MAX];
1782 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1784 FILE *lockfile = fopen(lockfilename, "w+");
1787 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1788 meshlink_errno = MESHLINK_ESTORAGE;
1793 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1797 // TODO: use _locking()?
1800 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1801 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1803 meshlink_errno = MESHLINK_EBUSY;
1809 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1810 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1814 if(unlink(lockfilename)) {
1815 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1817 meshlink_errno = MESHLINK_ESTORAGE;
1823 if(!sync_path(confbase)) {
1824 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1825 meshlink_errno = MESHLINK_ESTORAGE;
1832 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1834 meshlink_errno = MESHLINK_EINVAL;
1838 pthread_mutex_lock(&mesh->mutex);
1839 mesh->receive_cb = cb;
1840 pthread_mutex_unlock(&mesh->mutex);
1843 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1845 meshlink_errno = MESHLINK_EINVAL;
1849 pthread_mutex_lock(&mesh->mutex);
1850 mesh->connection_try_cb = cb;
1851 pthread_mutex_unlock(&mesh->mutex);
1854 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1856 meshlink_errno = MESHLINK_EINVAL;
1860 pthread_mutex_lock(&mesh->mutex);
1861 mesh->node_status_cb = cb;
1862 pthread_mutex_unlock(&mesh->mutex);
1865 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1867 meshlink_errno = MESHLINK_EINVAL;
1871 pthread_mutex_lock(&mesh->mutex);
1872 mesh->node_pmtu_cb = cb;
1873 pthread_mutex_unlock(&mesh->mutex);
1876 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1878 meshlink_errno = MESHLINK_EINVAL;
1882 pthread_mutex_lock(&mesh->mutex);
1883 mesh->node_duplicate_cb = cb;
1884 pthread_mutex_unlock(&mesh->mutex);
1887 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1889 pthread_mutex_lock(&mesh->mutex);
1891 mesh->log_level = cb ? level : 0;
1892 pthread_mutex_unlock(&mesh->mutex);
1895 global_log_level = cb ? level : 0;
1899 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1901 meshlink_errno = MESHLINK_EINVAL;
1905 pthread_mutex_lock(&mesh->mutex);
1906 mesh->error_cb = cb;
1907 pthread_mutex_unlock(&mesh->mutex);
1910 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1911 meshlink_packethdr_t *hdr;
1913 // Validate arguments
1914 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1915 meshlink_errno = MESHLINK_EINVAL;
1924 meshlink_errno = MESHLINK_EINVAL;
1928 node_t *n = (node_t *)destination;
1930 if(n->status.blacklisted) {
1931 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1932 meshlink_errno = MESHLINK_EBLACKLISTED;
1936 // Prepare the packet
1937 vpn_packet_t *packet = malloc(sizeof(*packet));
1940 meshlink_errno = MESHLINK_ENOMEM;
1944 packet->probe = false;
1945 packet->tcp = false;
1946 packet->len = len + sizeof(*hdr);
1948 hdr = (meshlink_packethdr_t *)packet->data;
1949 memset(hdr, 0, sizeof(*hdr));
1950 // leave the last byte as 0 to make sure strings are always
1951 // null-terminated if they are longer than the buffer
1952 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1953 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1955 memcpy(packet->data + sizeof(*hdr), data, len);
1958 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1960 meshlink_errno = MESHLINK_ENOMEM;
1964 // Notify event loop
1965 signal_trigger(&mesh->loop, &mesh->datafromapp);
1970 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1972 meshlink_handle_t *mesh = data;
1973 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1979 mesh->self->in_packets++;
1980 mesh->self->in_bytes += packet->len;
1981 route(mesh, mesh->self, packet);
1986 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1987 if(!mesh || !destination) {
1988 meshlink_errno = MESHLINK_EINVAL;
1992 pthread_mutex_lock(&mesh->mutex);
1994 node_t *n = (node_t *)destination;
1996 if(!n->status.reachable) {
1997 pthread_mutex_unlock(&mesh->mutex);
2000 } else if(n->mtuprobes > 30 && n->minmtu) {
2001 pthread_mutex_unlock(&mesh->mutex);
2004 pthread_mutex_unlock(&mesh->mutex);
2009 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2010 if(!mesh || !node) {
2011 meshlink_errno = MESHLINK_EINVAL;
2015 pthread_mutex_lock(&mesh->mutex);
2017 node_t *n = (node_t *)node;
2019 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2020 meshlink_errno = MESHLINK_EINTERNAL;
2021 pthread_mutex_unlock(&mesh->mutex);
2025 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2028 meshlink_errno = MESHLINK_EINTERNAL;
2031 pthread_mutex_unlock(&mesh->mutex);
2035 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2037 meshlink_errno = MESHLINK_EINVAL;
2041 return (meshlink_node_t *)mesh->self;
2044 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2045 if(!mesh || !name) {
2046 meshlink_errno = MESHLINK_EINVAL;
2052 pthread_mutex_lock(&mesh->mutex);
2053 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2054 pthread_mutex_unlock(&mesh->mutex);
2057 meshlink_errno = MESHLINK_ENOENT;
2060 return (meshlink_node_t *)n;
2063 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2064 if(!mesh || !name) {
2065 meshlink_errno = MESHLINK_EINVAL;
2069 meshlink_submesh_t *submesh = NULL;
2071 pthread_mutex_lock(&mesh->mutex);
2072 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2073 pthread_mutex_unlock(&mesh->mutex);
2076 meshlink_errno = MESHLINK_ENOENT;
2082 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2083 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2084 meshlink_errno = MESHLINK_EINVAL;
2088 meshlink_node_t **result;
2091 pthread_mutex_lock(&mesh->mutex);
2093 *nmemb = mesh->nodes->count;
2094 result = realloc(nodes, *nmemb * sizeof(*nodes));
2097 meshlink_node_t **p = result;
2099 for splay_each(node_t, n, mesh->nodes) {
2100 *p++ = (meshlink_node_t *)n;
2105 meshlink_errno = MESHLINK_ENOMEM;
2108 pthread_mutex_unlock(&mesh->mutex);
2113 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) {
2114 meshlink_node_t **result;
2116 pthread_mutex_lock(&mesh->mutex);
2120 for splay_each(node_t, n, mesh->nodes) {
2121 if(search_node(n, condition)) {
2128 pthread_mutex_unlock(&mesh->mutex);
2132 result = realloc(nodes, *nmemb * sizeof(*nodes));
2135 meshlink_node_t **p = result;
2137 for splay_each(node_t, n, mesh->nodes) {
2138 if(search_node(n, condition)) {
2139 *p++ = (meshlink_node_t *)n;
2145 meshlink_errno = MESHLINK_ENOMEM;
2148 pthread_mutex_unlock(&mesh->mutex);
2153 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2154 dev_class_t *devclass = (dev_class_t *)condition;
2156 if(*devclass == (dev_class_t)node->devclass) {
2163 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2164 if(condition == node->submesh) {
2176 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2177 const struct time_range *range = condition;
2178 time_t start = node->last_reachable;
2179 time_t end = node->last_unreachable;
2189 if(range->end >= range->start) {
2190 return start <= range->end && end >= range->start;
2192 return start > range->start || end < range->end;
2196 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) {
2197 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2198 meshlink_errno = MESHLINK_EINVAL;
2202 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2205 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2206 if(!mesh || !submesh || !nmemb) {
2207 meshlink_errno = MESHLINK_EINVAL;
2211 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2214 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) {
2215 if(!mesh || !nmemb) {
2216 meshlink_errno = MESHLINK_EINVAL;
2220 struct time_range range = {start, end};
2222 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2225 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2226 if(!mesh || !node) {
2227 meshlink_errno = MESHLINK_EINVAL;
2231 dev_class_t devclass;
2233 pthread_mutex_lock(&mesh->mutex);
2235 devclass = ((node_t *)node)->devclass;
2237 pthread_mutex_unlock(&mesh->mutex);
2242 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2243 if(!mesh || !node) {
2244 meshlink_errno = MESHLINK_EINVAL;
2248 node_t *n = (node_t *)node;
2250 meshlink_submesh_t *s;
2252 s = (meshlink_submesh_t *)n->submesh;
2257 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2258 if(!mesh || !node) {
2259 meshlink_errno = MESHLINK_EINVAL;
2263 node_t *n = (node_t *)node;
2266 pthread_mutex_lock(&mesh->mutex);
2267 reachable = n->status.reachable && !n->status.blacklisted;
2269 if(last_reachable) {
2270 *last_reachable = n->last_reachable;
2273 if(last_unreachable) {
2274 *last_unreachable = n->last_unreachable;
2277 pthread_mutex_unlock(&mesh->mutex);
2282 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2283 if(!mesh || !data || !len || !signature || !siglen) {
2284 meshlink_errno = MESHLINK_EINVAL;
2288 if(*siglen < MESHLINK_SIGLEN) {
2289 meshlink_errno = MESHLINK_EINVAL;
2293 pthread_mutex_lock(&mesh->mutex);
2295 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2296 meshlink_errno = MESHLINK_EINTERNAL;
2297 pthread_mutex_unlock(&mesh->mutex);
2301 *siglen = MESHLINK_SIGLEN;
2302 pthread_mutex_unlock(&mesh->mutex);
2306 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2307 if(!mesh || !source || !data || !len || !signature) {
2308 meshlink_errno = MESHLINK_EINVAL;
2312 if(siglen != MESHLINK_SIGLEN) {
2313 meshlink_errno = MESHLINK_EINVAL;
2317 pthread_mutex_lock(&mesh->mutex);
2321 struct node_t *n = (struct node_t *)source;
2323 if(!node_read_public_key(mesh, n)) {
2324 meshlink_errno = MESHLINK_EINTERNAL;
2327 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2330 pthread_mutex_unlock(&mesh->mutex);
2334 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2335 pthread_mutex_lock(&mesh->mutex);
2337 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2340 // TODO: Update invitation key if necessary?
2343 pthread_mutex_unlock(&mesh->mutex);
2345 return mesh->invitation_key;
2348 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2349 if(!mesh || !node || !address) {
2350 meshlink_errno = MESHLINK_EINVAL;
2354 if(!is_valid_hostname(address)) {
2355 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2356 meshlink_errno = MESHLINK_EINVAL;
2360 if(port && !is_valid_port(port)) {
2361 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2362 meshlink_errno = MESHLINK_EINVAL;
2366 char *canonical_address;
2369 xasprintf(&canonical_address, "%s %s", address, port);
2371 canonical_address = xstrdup(address);
2374 pthread_mutex_lock(&mesh->mutex);
2376 node_t *n = (node_t *)node;
2377 free(n->canonical_address);
2378 n->canonical_address = canonical_address;
2380 if(!node_write_config(mesh, n)) {
2381 pthread_mutex_unlock(&mesh->mutex);
2385 pthread_mutex_unlock(&mesh->mutex);
2387 return config_sync(mesh, "current");
2390 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2391 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2394 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2396 meshlink_errno = MESHLINK_EINVAL;
2400 char *address = meshlink_get_external_address(mesh);
2406 bool rval = meshlink_add_address(mesh, address);
2412 int meshlink_get_port(meshlink_handle_t *mesh) {
2414 meshlink_errno = MESHLINK_EINVAL;
2419 meshlink_errno = MESHLINK_EINTERNAL;
2425 pthread_mutex_lock(&mesh->mutex);
2426 port = atoi(mesh->myport);
2427 pthread_mutex_unlock(&mesh->mutex);
2432 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2433 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2434 meshlink_errno = MESHLINK_EINVAL;
2438 if(mesh->myport && port == atoi(mesh->myport)) {
2442 if(!try_bind(port)) {
2443 meshlink_errno = MESHLINK_ENETWORK;
2447 devtool_trybind_probe();
2451 pthread_mutex_lock(&mesh->mutex);
2453 if(mesh->threadstarted) {
2454 meshlink_errno = MESHLINK_EINVAL;
2459 xasprintf(&mesh->myport, "%d", port);
2461 /* Close down the network. This also deletes mesh->self. */
2462 close_network_connections(mesh);
2464 /* Recreate mesh->self. */
2465 mesh->self = new_node();
2466 mesh->self->name = xstrdup(mesh->name);
2467 mesh->self->devclass = mesh->devclass;
2468 mesh->self->session_id = mesh->session_id;
2469 xasprintf(&mesh->myport, "%d", port);
2471 if(!node_read_public_key(mesh, mesh->self)) {
2472 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2473 meshlink_errno = MESHLINK_ESTORAGE;
2474 free_node(mesh->self);
2477 } else if(!setup_network(mesh)) {
2478 meshlink_errno = MESHLINK_ENETWORK;
2482 /* Rebuild our own list of recent addresses */
2483 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2484 add_local_addresses(mesh);
2486 /* Write meshlink.conf with the updated port number */
2487 write_main_config_files(mesh);
2489 rval = config_sync(mesh, "current");
2492 pthread_mutex_unlock(&mesh->mutex);
2494 return rval && meshlink_get_port(mesh) == port;
2497 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2498 mesh->invitation_timeout = timeout;
2501 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2502 meshlink_submesh_t *s = NULL;
2505 meshlink_errno = MESHLINK_EINVAL;
2510 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2513 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2514 meshlink_errno = MESHLINK_EINVAL;
2518 s = (meshlink_submesh_t *)mesh->self->submesh;
2521 pthread_mutex_lock(&mesh->mutex);
2523 // Check validity of the new node's name
2524 if(!check_id(name)) {
2525 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2526 meshlink_errno = MESHLINK_EINVAL;
2527 pthread_mutex_unlock(&mesh->mutex);
2531 // Ensure no host configuration file with that name exists
2532 if(config_exists(mesh, "current", name)) {
2533 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2534 meshlink_errno = MESHLINK_EEXIST;
2535 pthread_mutex_unlock(&mesh->mutex);
2539 // Ensure no other nodes know about this name
2540 if(lookup_node(mesh, name)) {
2541 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2542 meshlink_errno = MESHLINK_EEXIST;
2543 pthread_mutex_unlock(&mesh->mutex);
2547 // Get the local address
2548 char *address = get_my_hostname(mesh, flags);
2551 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2552 meshlink_errno = MESHLINK_ERESOLV;
2553 pthread_mutex_unlock(&mesh->mutex);
2557 if(!refresh_invitation_key(mesh)) {
2558 meshlink_errno = MESHLINK_EINTERNAL;
2559 pthread_mutex_unlock(&mesh->mutex);
2563 // If we changed our own host config file, write it out now
2564 if(mesh->self->status.dirty) {
2565 if(!node_write_config(mesh, mesh->self)) {
2566 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2567 pthread_mutex_unlock(&mesh->mutex);
2574 // Create a hash of the key.
2575 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2576 sha512(fingerprint, strlen(fingerprint), hash);
2577 b64encode_urlsafe(hash, hash, 18);
2579 // Create a random cookie for this invitation.
2581 randomize(cookie, 18);
2583 // Create a filename that doesn't reveal the cookie itself
2584 char buf[18 + strlen(fingerprint)];
2585 char cookiehash[64];
2586 memcpy(buf, cookie, 18);
2587 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2588 sha512(buf, sizeof(buf), cookiehash);
2589 b64encode_urlsafe(cookiehash, cookiehash, 18);
2591 b64encode_urlsafe(cookie, cookie, 18);
2595 /* Construct the invitation file */
2596 uint8_t outbuf[4096];
2597 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2599 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2600 packmsg_add_str(&inv, name);
2601 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2602 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2604 /* TODO: Add several host config files to bootstrap connections.
2605 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2606 * and are not blacklisted.
2608 config_t configs[5];
2609 memset(configs, 0, sizeof(configs));
2612 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2616 /* Append host config files to the invitation file */
2617 packmsg_add_array(&inv, count);
2619 for(int i = 0; i < count; i++) {
2620 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2621 config_free(&configs[i]);
2624 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2626 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2627 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2628 meshlink_errno = MESHLINK_ESTORAGE;
2629 pthread_mutex_unlock(&mesh->mutex);
2633 // Create an URL from the local address, key hash and cookie
2635 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2638 pthread_mutex_unlock(&mesh->mutex);
2642 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2643 return meshlink_invite_ex(mesh, submesh, name, 0);
2646 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2647 if(!mesh || !invitation) {
2648 meshlink_errno = MESHLINK_EINVAL;
2652 join_state_t state = {
2657 ecdsa_t *key = NULL;
2658 ecdsa_t *hiskey = NULL;
2660 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2661 char copy[strlen(invitation) + 1];
2663 pthread_mutex_lock(&mesh->mutex);
2665 //Before doing meshlink_join make sure we are not connected to another mesh
2666 if(mesh->threadstarted) {
2667 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2668 meshlink_errno = MESHLINK_EINVAL;
2672 // 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.
2673 if(mesh->nodes->count > 1) {
2674 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2675 meshlink_errno = MESHLINK_EINVAL;
2679 strcpy(copy, invitation);
2681 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2683 char *slash = strchr(copy, '/');
2691 if(strlen(slash) != 48) {
2695 char *address = copy;
2698 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2702 if(mesh->inviter_commits_first) {
2703 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2706 // Generate a throw-away key for the invitation.
2707 key = ecdsa_generate();
2710 meshlink_errno = MESHLINK_EINTERNAL;
2714 char *b64key = ecdsa_get_base64_public_key(key);
2717 while(address && *address) {
2718 // We allow commas in the address part to support multiple addresses in one invitation URL.
2719 comma = strchr(address, ',');
2725 // Split of the port
2726 port = strrchr(address, ':');
2734 // IPv6 address are enclosed in brackets, per RFC 3986
2735 if(*address == '[') {
2737 char *bracket = strchr(address, ']');
2750 // Connect to the meshlink daemon mentioned in the URL.
2751 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2754 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2755 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2757 if(state.sock == -1) {
2758 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2759 meshlink_errno = MESHLINK_ENETWORK;
2763 set_timeout(state.sock, 5000);
2765 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2766 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2767 meshlink_errno = MESHLINK_ENETWORK;
2768 closesocket(state.sock);
2778 meshlink_errno = MESHLINK_ERESOLV;
2781 if(state.sock != -1 || !comma) {
2788 if(state.sock == -1) {
2792 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2794 // Tell him we have an invitation, and give him our throw-away key.
2798 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2799 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2800 meshlink_errno = MESHLINK_ENETWORK;
2806 char hisname[4096] = "";
2807 int code, hismajor, hisminor = 0;
2809 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) {
2810 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2811 meshlink_errno = MESHLINK_ENETWORK;
2815 // Check if the hash of the key he gave us matches the hash in the URL.
2816 char *fingerprint = state.line + 2;
2819 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2820 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2821 meshlink_errno = MESHLINK_EINTERNAL;
2825 if(memcmp(hishash, state.hash, 18)) {
2826 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2827 meshlink_errno = MESHLINK_EPEER;
2831 hiskey = ecdsa_set_base64_public_key(fingerprint);
2834 meshlink_errno = MESHLINK_EINTERNAL;
2838 // Start an SPTPS session
2839 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2840 meshlink_errno = MESHLINK_EINTERNAL;
2844 // Feed rest of input buffer to SPTPS
2845 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2846 meshlink_errno = MESHLINK_EPEER;
2851 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2853 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2855 if(errno == EINTR) {
2859 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2860 meshlink_errno = MESHLINK_ENETWORK;
2864 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2865 meshlink_errno = MESHLINK_EPEER;
2870 if(!state.success) {
2871 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2872 meshlink_errno = MESHLINK_EPEER;
2876 sptps_stop(&state.sptps);
2879 closesocket(state.sock);
2881 pthread_mutex_unlock(&mesh->mutex);
2885 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2886 meshlink_errno = MESHLINK_EINVAL;
2888 sptps_stop(&state.sptps);
2892 if(state.sock != -1) {
2893 closesocket(state.sock);
2896 pthread_mutex_unlock(&mesh->mutex);
2900 char *meshlink_export(meshlink_handle_t *mesh) {
2902 meshlink_errno = MESHLINK_EINVAL;
2906 // Create a config file on the fly.
2909 packmsg_output_t out = {buf, sizeof(buf)};
2910 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2911 packmsg_add_str(&out, mesh->name);
2912 packmsg_add_str(&out, CORE_MESH);
2914 pthread_mutex_lock(&mesh->mutex);
2916 packmsg_add_int32(&out, mesh->self->devclass);
2917 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2918 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2919 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2923 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2924 if(mesh->self->recent[i].sa.sa_family) {
2931 packmsg_add_array(&out, count);
2933 for(uint32_t i = 0; i < count; i++) {
2934 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2937 packmsg_add_int64(&out, 0);
2938 packmsg_add_int64(&out, 0);
2940 pthread_mutex_unlock(&mesh->mutex);
2942 if(!packmsg_output_ok(&out)) {
2943 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2944 meshlink_errno = MESHLINK_EINTERNAL;
2948 // Prepare a base64-encoded packmsg array containing our config file
2950 uint32_t len = packmsg_output_size(&out, buf);
2951 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2952 uint8_t *buf2 = xmalloc(len2);
2953 packmsg_output_t out2 = {buf2, len2};
2954 packmsg_add_array(&out2, 1);
2955 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2957 if(!packmsg_output_ok(&out2)) {
2958 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2959 meshlink_errno = MESHLINK_EINTERNAL;
2964 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2966 return (char *)buf2;
2969 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2970 if(!mesh || !data) {
2971 meshlink_errno = MESHLINK_EINVAL;
2975 size_t datalen = strlen(data);
2976 uint8_t *buf = xmalloc(datalen);
2977 int buflen = b64decode(data, buf, datalen);
2980 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2981 meshlink_errno = MESHLINK_EPEER;
2985 packmsg_input_t in = {buf, buflen};
2986 uint32_t count = packmsg_get_array(&in);
2989 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2990 meshlink_errno = MESHLINK_EPEER;
2994 pthread_mutex_lock(&mesh->mutex);
2998 uint32_t len = packmsg_get_bin_raw(&in, &data);
3004 packmsg_input_t in2 = {data, len};
3005 uint32_t version = packmsg_get_uint32(&in2);
3006 char *name = packmsg_get_str_dup(&in2);
3008 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3010 packmsg_input_invalidate(&in);
3014 if(!check_id(name)) {
3019 node_t *n = lookup_node(mesh, name);
3022 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3030 config_t config = {data, len};
3032 if(!node_read_from_config(mesh, n, &config)) {
3034 packmsg_input_invalidate(&in);
3038 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3039 n->last_reachable = 0;
3040 n->last_unreachable = 0;
3042 if(!node_write_config(mesh, n)) {
3050 pthread_mutex_unlock(&mesh->mutex);
3054 if(!packmsg_done(&in)) {
3055 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3056 meshlink_errno = MESHLINK_EPEER;
3060 if(!config_sync(mesh, "current")) {
3067 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3068 if(n == mesh->self) {
3069 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3070 meshlink_errno = MESHLINK_EINVAL;
3074 if(n->status.blacklisted) {
3075 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3079 n->status.blacklisted = true;
3081 /* Immediately shut down any connections we have with the blacklisted node.
3082 * We can't call terminate_connection(), because we might be called from a callback function.
3084 for list_each(connection_t, c, mesh->connections) {
3086 shutdown(c->socket, SHUT_RDWR);
3090 utcp_abort_all_connections(n->utcp);
3096 n->status.udp_confirmed = false;
3098 if(n->status.reachable) {
3099 n->last_unreachable = mesh->loop.now.tv_sec;
3102 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3103 * manually call the status callback if necessary.
3105 if(n->status.reachable && mesh->node_status_cb) {
3106 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3109 return node_write_config(mesh, n) && config_sync(mesh, "current");
3112 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3113 if(!mesh || !node) {
3114 meshlink_errno = MESHLINK_EINVAL;
3118 pthread_mutex_lock(&mesh->mutex);
3120 if(!blacklist(mesh, (node_t *)node)) {
3121 pthread_mutex_unlock(&mesh->mutex);
3125 pthread_mutex_unlock(&mesh->mutex);
3127 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3131 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3132 if(!mesh || !name) {
3133 meshlink_errno = MESHLINK_EINVAL;
3137 pthread_mutex_lock(&mesh->mutex);
3139 node_t *n = lookup_node(mesh, (char *)name);
3143 n->name = xstrdup(name);
3147 if(!blacklist(mesh, (node_t *)n)) {
3148 pthread_mutex_unlock(&mesh->mutex);
3152 pthread_mutex_unlock(&mesh->mutex);
3154 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3158 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3159 if(n == mesh->self) {
3160 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3161 meshlink_errno = MESHLINK_EINVAL;
3165 if(!n->status.blacklisted) {
3166 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3170 n->status.blacklisted = false;
3172 if(n->status.reachable) {
3173 n->last_reachable = mesh->loop.now.tv_sec;
3174 update_node_status(mesh, n);
3177 return node_write_config(mesh, n) && config_sync(mesh, "current");
3180 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3181 if(!mesh || !node) {
3182 meshlink_errno = MESHLINK_EINVAL;
3186 pthread_mutex_lock(&mesh->mutex);
3188 if(!whitelist(mesh, (node_t *)node)) {
3189 pthread_mutex_unlock(&mesh->mutex);
3193 pthread_mutex_unlock(&mesh->mutex);
3195 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3199 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3200 if(!mesh || !name) {
3201 meshlink_errno = MESHLINK_EINVAL;
3205 pthread_mutex_lock(&mesh->mutex);
3207 node_t *n = lookup_node(mesh, (char *)name);
3211 n->name = xstrdup(name);
3215 if(!whitelist(mesh, (node_t *)n)) {
3216 pthread_mutex_unlock(&mesh->mutex);
3220 pthread_mutex_unlock(&mesh->mutex);
3222 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3226 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3227 mesh->default_blacklist = blacklist;
3230 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3231 if(!mesh || !node) {
3232 meshlink_errno = MESHLINK_EINVAL;
3236 node_t *n = (node_t *)node;
3238 pthread_mutex_lock(&mesh->mutex);
3240 /* Check that the node is not reachable */
3241 if(n->status.reachable || n->connection) {
3242 pthread_mutex_unlock(&mesh->mutex);
3243 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3247 /* Check that we don't have any active UTCP connections */
3248 if(n->utcp && utcp_is_active(n->utcp)) {
3249 pthread_mutex_unlock(&mesh->mutex);
3250 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3254 /* Check that we have no active connections to this node */
3255 for list_each(connection_t, c, mesh->connections) {
3257 pthread_mutex_unlock(&mesh->mutex);
3258 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3263 /* Remove any pending outgoings to this node */
3264 if(mesh->outgoings) {
3265 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3266 if(outgoing->node == n) {
3267 list_delete_node(mesh->outgoings, node);
3272 /* Delete the config file for this node */
3273 if(!config_delete(mesh, "current", n->name)) {
3274 pthread_mutex_unlock(&mesh->mutex);
3278 /* Delete the node struct and any remaining edges referencing this node */
3281 pthread_mutex_unlock(&mesh->mutex);
3283 return config_sync(mesh, "current");
3286 /* Hint that a hostname may be found at an address
3287 * See header file for detailed comment.
3289 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3290 if(!mesh || !node || !addr) {
3291 meshlink_errno = EINVAL;
3295 pthread_mutex_lock(&mesh->mutex);
3297 node_t *n = (node_t *)node;
3299 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3300 if(!node_write_config(mesh, n)) {
3301 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3305 pthread_mutex_unlock(&mesh->mutex);
3306 // @TODO do we want to fire off a connection attempt right away?
3309 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3311 node_t *n = utcp->priv;
3312 meshlink_handle_t *mesh = n->mesh;
3313 return mesh->channel_accept_cb;
3316 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3318 if(aio->cb.buffer) {
3319 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3323 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3328 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3329 meshlink_channel_t *channel = connection->priv;
3335 node_t *n = channel->node;
3336 meshlink_handle_t *mesh = n->mesh;
3338 if(n->status.destroyed) {
3339 meshlink_channel_close(mesh, channel);
3343 const char *p = data;
3346 while(channel->aio_receive) {
3347 meshlink_aio_buffer_t *aio = channel->aio_receive;
3348 size_t todo = aio->len - aio->done;
3355 memcpy((char *)aio->data + aio->done, p, todo);
3357 ssize_t result = write(aio->fd, p, todo);
3366 if(aio->done == aio->len) {
3367 channel->aio_receive = aio->next;
3368 aio_signal(mesh, channel, aio);
3380 if(channel->receive_cb) {
3381 channel->receive_cb(mesh, channel, p, left);
3387 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3388 node_t *n = utcp_connection->utcp->priv;
3394 meshlink_handle_t *mesh = n->mesh;
3396 if(!mesh->channel_accept_cb) {
3400 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3402 channel->c = utcp_connection;
3404 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3405 utcp_accept(utcp_connection, channel_recv, channel);
3411 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3412 node_t *n = utcp->priv;
3414 if(n->status.destroyed) {
3418 meshlink_handle_t *mesh = n->mesh;
3419 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3422 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3423 if(!mesh || !channel) {
3424 meshlink_errno = MESHLINK_EINVAL;
3428 channel->receive_cb = cb;
3431 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3433 node_t *n = (node_t *)source;
3439 utcp_recv(n->utcp, data, len);
3442 static void channel_poll(struct utcp_connection *connection, size_t len) {
3443 meshlink_channel_t *channel = connection->priv;
3449 node_t *n = channel->node;
3450 meshlink_handle_t *mesh = n->mesh;
3451 meshlink_aio_buffer_t *aio = channel->aio_send;
3454 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3455 size_t left = aio->len - aio->done;
3463 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3466 size_t todo = utcp_get_sndbuf_free(connection);
3472 if(todo > sizeof(buf)) {
3476 ssize_t result = read(aio->fd, buf, todo);
3479 sent = utcp_send(connection, buf, result);
3489 /* If the buffer is now completely sent, call the callback and dispose of it. */
3490 if(aio->done >= aio->len) {
3491 channel->aio_send = aio->next;
3492 aio_signal(mesh, channel, aio);
3496 if(channel->poll_cb) {
3497 channel->poll_cb(mesh, channel, len);
3499 utcp_set_poll_cb(connection, NULL);
3504 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3505 if(!mesh || !channel) {
3506 meshlink_errno = MESHLINK_EINVAL;
3510 pthread_mutex_lock(&mesh->mutex);
3511 channel->poll_cb = cb;
3512 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3513 pthread_mutex_unlock(&mesh->mutex);
3516 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3518 meshlink_errno = MESHLINK_EINVAL;
3522 pthread_mutex_lock(&mesh->mutex);
3523 mesh->channel_accept_cb = cb;
3524 mesh->receive_cb = channel_receive;
3526 for splay_each(node_t, n, mesh->nodes) {
3527 if(!n->utcp && n != mesh->self) {
3528 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3532 pthread_mutex_unlock(&mesh->mutex);
3535 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3539 meshlink_errno = MESHLINK_EINVAL;
3543 pthread_mutex_lock(&mesh->mutex);
3544 utcp_set_sndbuf(channel->c, size);
3545 pthread_mutex_unlock(&mesh->mutex);
3548 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3552 meshlink_errno = MESHLINK_EINVAL;
3556 pthread_mutex_lock(&mesh->mutex);
3557 utcp_set_rcvbuf(channel->c, size);
3558 pthread_mutex_unlock(&mesh->mutex);
3561 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) {
3563 abort(); // TODO: handle non-NULL data
3566 if(!mesh || !node) {
3567 meshlink_errno = MESHLINK_EINVAL;
3571 pthread_mutex_lock(&mesh->mutex);
3573 node_t *n = (node_t *)node;
3576 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3577 mesh->receive_cb = channel_receive;
3580 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3581 pthread_mutex_unlock(&mesh->mutex);
3586 if(n->status.blacklisted) {
3587 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3588 meshlink_errno = MESHLINK_EBLACKLISTED;
3589 pthread_mutex_unlock(&mesh->mutex);
3593 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3595 channel->receive_cb = cb;
3598 channel->priv = (void *)data;
3601 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3603 pthread_mutex_unlock(&mesh->mutex);
3606 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3614 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) {
3615 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3618 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3619 if(!mesh || !channel) {
3620 meshlink_errno = MESHLINK_EINVAL;
3624 pthread_mutex_lock(&mesh->mutex);
3625 utcp_shutdown(channel->c, direction);
3626 pthread_mutex_unlock(&mesh->mutex);
3629 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3630 if(!mesh || !channel) {
3631 meshlink_errno = MESHLINK_EINVAL;
3635 pthread_mutex_lock(&mesh->mutex);
3637 utcp_close(channel->c);
3639 /* Clean up any outstanding AIO buffers. */
3640 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3642 aio_signal(mesh, channel, aio);
3646 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3648 aio_signal(mesh, channel, aio);
3652 pthread_mutex_unlock(&mesh->mutex);
3657 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3658 if(!mesh || !channel) {
3659 meshlink_errno = MESHLINK_EINVAL;
3668 meshlink_errno = MESHLINK_EINVAL;
3672 // TODO: more finegrained locking.
3673 // Ideally we want to put the data into the UTCP connection's send buffer.
3674 // Then, preferably only if there is room in the receiver window,
3675 // kick the meshlink thread to go send packets.
3679 pthread_mutex_lock(&mesh->mutex);
3681 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3682 if(channel->aio_send) {
3685 retval = utcp_send(channel->c, data, len);
3688 pthread_mutex_unlock(&mesh->mutex);
3691 meshlink_errno = MESHLINK_ENETWORK;
3697 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) {
3698 if(!mesh || !channel) {
3699 meshlink_errno = MESHLINK_EINVAL;
3704 meshlink_errno = MESHLINK_EINVAL;
3708 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3711 aio->cb.buffer = cb;
3714 pthread_mutex_lock(&mesh->mutex);
3716 /* Append the AIO buffer descriptor to the end of the chain */
3717 meshlink_aio_buffer_t **p = &channel->aio_send;
3725 /* Ensure the poll callback is set, and call it right now to push data if possible */
3726 utcp_set_poll_cb(channel->c, channel_poll);
3727 channel_poll(channel->c, len);
3729 pthread_mutex_unlock(&mesh->mutex);
3734 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) {
3735 if(!mesh || !channel) {
3736 meshlink_errno = MESHLINK_EINVAL;
3740 if(!len || fd == -1) {
3741 meshlink_errno = MESHLINK_EINVAL;
3745 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3751 pthread_mutex_lock(&mesh->mutex);
3753 /* Append the AIO buffer descriptor to the end of the chain */
3754 meshlink_aio_buffer_t **p = &channel->aio_send;
3762 /* Ensure the poll callback is set, and call it right now to push data if possible */
3763 utcp_set_poll_cb(channel->c, channel_poll);
3764 channel_poll(channel->c, len);
3766 pthread_mutex_unlock(&mesh->mutex);
3771 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) {
3772 if(!mesh || !channel) {
3773 meshlink_errno = MESHLINK_EINVAL;
3778 meshlink_errno = MESHLINK_EINVAL;
3782 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3785 aio->cb.buffer = cb;
3788 pthread_mutex_lock(&mesh->mutex);
3790 /* Append the AIO buffer descriptor to the end of the chain */
3791 meshlink_aio_buffer_t **p = &channel->aio_receive;
3799 pthread_mutex_unlock(&mesh->mutex);
3804 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) {
3805 if(!mesh || !channel) {
3806 meshlink_errno = MESHLINK_EINVAL;
3810 if(!len || fd == -1) {
3811 meshlink_errno = MESHLINK_EINVAL;
3815 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3821 pthread_mutex_lock(&mesh->mutex);
3823 /* Append the AIO buffer descriptor to the end of the chain */
3824 meshlink_aio_buffer_t **p = &channel->aio_receive;
3832 pthread_mutex_unlock(&mesh->mutex);
3837 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3838 if(!mesh || !channel) {
3839 meshlink_errno = MESHLINK_EINVAL;
3843 return channel->c->flags;
3846 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3847 if(!mesh || !channel) {
3848 meshlink_errno = MESHLINK_EINVAL;
3852 return utcp_get_sendq(channel->c);
3855 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3856 if(!mesh || !channel) {
3857 meshlink_errno = MESHLINK_EINVAL;
3861 return utcp_get_recvq(channel->c);
3864 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3865 if(!mesh || !node) {
3866 meshlink_errno = MESHLINK_EINVAL;
3870 node_t *n = (node_t *)node;
3872 pthread_mutex_lock(&mesh->mutex);
3875 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3878 utcp_set_user_timeout(n->utcp, timeout);
3880 pthread_mutex_unlock(&mesh->mutex);
3883 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3884 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3885 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3888 if(mesh->node_status_cb) {
3889 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3892 if(mesh->node_pmtu_cb) {
3893 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3897 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3898 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3899 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3903 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3904 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3908 n->status.duplicate = true;
3909 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3912 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3916 meshlink_errno = MESHLINK_EINVAL;
3920 pthread_mutex_lock(&mesh->mutex);
3922 if(mesh->discovery == enable) {
3926 if(mesh->threadstarted) {
3928 discovery_start(mesh);
3930 discovery_stop(mesh);
3934 mesh->discovery = enable;
3937 pthread_mutex_unlock(&mesh->mutex);
3941 meshlink_errno = MESHLINK_ENOTSUP;
3945 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3946 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3947 meshlink_errno = EINVAL;
3951 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3952 meshlink_errno = EINVAL;
3956 pthread_mutex_lock(&mesh->mutex);
3957 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3958 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3959 pthread_mutex_unlock(&mesh->mutex);
3962 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3963 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3964 meshlink_errno = EINVAL;
3968 if(fast_retry_period < 0) {
3969 meshlink_errno = EINVAL;
3973 pthread_mutex_lock(&mesh->mutex);
3974 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3975 pthread_mutex_unlock(&mesh->mutex);
3978 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
3980 meshlink_errno = EINVAL;
3984 pthread_mutex_lock(&mesh->mutex);
3985 mesh->inviter_commits_first = inviter_commits_first;
3986 pthread_mutex_unlock(&mesh->mutex);
3989 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3992 if(!mesh->connections || !mesh->loop.running) {
3999 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
4000 // We should only call the callback function if we are in the background thread.
4001 if(!mesh->error_cb) {
4005 if(!mesh->threadstarted) {
4009 if(mesh->thread == pthread_self()) {
4010 mesh->error_cb(mesh, meshlink_errno);
4014 static void __attribute__((constructor)) meshlink_init(void) {
4018 static void __attribute__((destructor)) meshlink_exit(void) {