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)) {
612 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
613 packmsg_input_t in = {buf, len};
614 uint32_t version = packmsg_get_uint32(&in);
616 if(version != MESHLINK_INVITATION_VERSION) {
617 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
621 char *name = packmsg_get_str_dup(&in);
622 packmsg_skip_element(&in); /* submesh */
623 dev_class_t devclass = packmsg_get_int32(&in);
624 uint32_t count = packmsg_get_array(&in);
627 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
631 if(!check_id(name)) {
632 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
638 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
644 free(mesh->self->name);
646 mesh->self->name = xstrdup(name);
647 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
649 // Initialize configuration directory
650 if(!config_init(mesh, "current")) {
654 if(!write_main_config_files(mesh)) {
658 // Write host config files
659 for(uint32_t i = 0; i < count; i++) {
661 uint32_t len = packmsg_get_bin_raw(&in, &data);
664 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
668 packmsg_input_t in2 = {data, len};
669 uint32_t version = packmsg_get_uint32(&in2);
670 char *name = packmsg_get_str_dup(&in2);
672 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
674 packmsg_input_invalidate(&in);
678 if(!check_id(name)) {
683 if(!strcmp(name, mesh->name)) {
684 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
686 meshlink_errno = MESHLINK_EPEER;
690 node_t *n = new_node();
693 config_t config = {data, len};
695 if(!node_read_from_config(mesh, n, &config)) {
697 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
698 meshlink_errno = MESHLINK_EPEER;
703 /* The first host config file is of the inviter itself;
704 * remember the address we are currently using for the invitation connection.
707 socklen_t salen = sizeof(sa);
709 if(getpeername(mesh->sock, &sa.sa, &salen) == 0) {
710 node_add_recent_address(mesh, n, &sa);
714 /* Clear the reachability times, since we ourself have never seen these nodes yet */
715 n->last_reachable = 0;
716 n->last_unreachable = 0;
718 if(!node_write_config(mesh, n)) {
726 /* Ensure the configuration directory metadata is on disk */
727 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
731 sptps_send_record(&mesh->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
733 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
738 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
740 meshlink_handle_t *mesh = handle;
741 const char *ptr = data;
744 int result = send(mesh->sock, ptr, len, 0);
746 if(result == -1 && errno == EINTR) {
748 } else if(result <= 0) {
759 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
760 meshlink_handle_t *mesh = handle;
763 case SPTPS_HANDSHAKE:
764 return sptps_send_record(&mesh->sptps, 0, mesh->cookie, sizeof(mesh)->cookie);
767 return finalize_join(mesh, msg, len);
770 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
771 shutdown(mesh->sock, SHUT_RDWR);
772 mesh->success = true;
782 static bool recvline(meshlink_handle_t *mesh, size_t len) {
783 char *newline = NULL;
789 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
790 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
792 if(result == -1 && errno == EINTR) {
794 } else if(result <= 0) {
798 mesh->blen += result;
801 if((size_t)(newline - mesh->buffer) >= len) {
805 len = newline - mesh->buffer;
807 memcpy(mesh->line, mesh->buffer, len);
809 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
810 mesh->blen -= len + 1;
815 static bool sendline(int fd, char *format, ...) {
821 va_start(ap, format);
822 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
825 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
833 int result = send(fd, p, blen, MSG_NOSIGNAL);
835 if(result == -1 && errno == EINTR) {
837 } else if(result <= 0) {
848 static const char *errstr[] = {
849 [MESHLINK_OK] = "No error",
850 [MESHLINK_EINVAL] = "Invalid argument",
851 [MESHLINK_ENOMEM] = "Out of memory",
852 [MESHLINK_ENOENT] = "No such node",
853 [MESHLINK_EEXIST] = "Node already exists",
854 [MESHLINK_EINTERNAL] = "Internal error",
855 [MESHLINK_ERESOLV] = "Could not resolve hostname",
856 [MESHLINK_ESTORAGE] = "Storage error",
857 [MESHLINK_ENETWORK] = "Network error",
858 [MESHLINK_EPEER] = "Error communicating with peer",
859 [MESHLINK_ENOTSUP] = "Operation not supported",
860 [MESHLINK_EBUSY] = "MeshLink instance already in use",
861 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
864 const char *meshlink_strerror(meshlink_errno_t err) {
865 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
866 return "Invalid error code";
872 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
873 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
875 mesh->private_key = ecdsa_generate();
876 mesh->invitation_key = ecdsa_generate();
878 if(!mesh->private_key || !mesh->invitation_key) {
879 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
880 meshlink_errno = MESHLINK_EINTERNAL;
884 logger(mesh, MESHLINK_DEBUG, "Done.\n");
889 static struct timeval idle(event_loop_t *loop, void *data) {
891 meshlink_handle_t *mesh = data;
892 struct timeval t, tmin = {3600, 0};
894 for splay_each(node_t, n, mesh->nodes) {
899 t = utcp_timeout(n->utcp);
901 if(timercmp(&t, &tmin, <)) {
909 // Get our local address(es) by simulating connecting to an Internet host.
910 static void add_local_addresses(meshlink_handle_t *mesh) {
912 sa.storage.ss_family = AF_UNKNOWN;
913 socklen_t salen = sizeof(sa);
917 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
918 sa.in.sin_port = ntohs(atoi(mesh->myport));
919 node_add_recent_address(mesh, mesh->self, &sa);
926 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
927 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
928 node_add_recent_address(mesh, mesh->self, &sa);
932 static bool meshlink_setup(meshlink_handle_t *mesh) {
933 if(!config_destroy(mesh->confbase, "new")) {
934 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
935 meshlink_errno = MESHLINK_ESTORAGE;
939 if(!config_destroy(mesh->confbase, "old")) {
940 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
941 meshlink_errno = MESHLINK_ESTORAGE;
945 if(!config_init(mesh, "current")) {
946 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
947 meshlink_errno = MESHLINK_ESTORAGE;
951 if(!ecdsa_keygen(mesh)) {
952 meshlink_errno = MESHLINK_EINTERNAL;
956 if(check_port(mesh) == 0) {
957 meshlink_errno = MESHLINK_ENETWORK;
961 /* Create a node for ourself */
963 mesh->self = new_node();
964 mesh->self->name = xstrdup(mesh->name);
965 mesh->self->devclass = mesh->devclass;
966 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
967 mesh->self->session_id = mesh->session_id;
969 if(!write_main_config_files(mesh)) {
970 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
971 meshlink_errno = MESHLINK_ESTORAGE;
975 /* Ensure the configuration directory metadata is on disk */
976 if(!config_sync(mesh, "current")) {
983 static bool meshlink_read_config(meshlink_handle_t *mesh) {
986 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
987 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
991 packmsg_input_t in = {config.buf, config.len};
992 const void *private_key;
993 const void *invitation_key;
995 uint32_t version = packmsg_get_uint32(&in);
996 char *name = packmsg_get_str_dup(&in);
997 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
998 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
999 uint16_t myport = packmsg_get_uint16(&in);
1001 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1002 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1004 config_free(&config);
1010 // TODO: check this?
1011 if(mesh->name && strcmp(mesh->name, name)) {
1012 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1013 meshlink_errno = MESHLINK_ESTORAGE;
1015 config_free(&config);
1023 xasprintf(&mesh->myport, "%u", myport);
1024 mesh->private_key = ecdsa_set_private_key(private_key);
1025 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1026 config_free(&config);
1028 /* Create a node for ourself and read our host configuration file */
1030 mesh->self = new_node();
1031 mesh->self->name = xstrdup(name);
1032 mesh->self->devclass = mesh->devclass;
1033 mesh->self->session_id = mesh->session_id;
1035 if(!node_read_public_key(mesh, mesh->self)) {
1036 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1037 meshlink_errno = MESHLINK_ESTORAGE;
1038 free_node(mesh->self);
1047 static void *setup_network_in_netns_thread(void *arg) {
1048 meshlink_handle_t *mesh = arg;
1050 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1054 bool success = setup_network(mesh);
1055 add_local_addresses(mesh);
1056 return success ? arg : NULL;
1058 #endif // HAVE_SETNS
1060 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1061 if(!confbase || !*confbase) {
1062 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1063 meshlink_errno = MESHLINK_EINVAL;
1067 if(!appname || !*appname) {
1068 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1069 meshlink_errno = MESHLINK_EINVAL;
1073 if(strchr(appname, ' ')) {
1074 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1075 meshlink_errno = MESHLINK_EINVAL;
1079 if(!name || !*name) {
1080 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1081 meshlink_errno = MESHLINK_EINVAL;
1085 if(!check_id(name)) {
1086 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1087 meshlink_errno = MESHLINK_EINVAL;
1091 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1092 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1093 meshlink_errno = MESHLINK_EINVAL;
1097 meshlink_open_params_t *params = xzalloc(sizeof * params);
1099 params->confbase = xstrdup(confbase);
1100 params->name = xstrdup(name);
1101 params->appname = xstrdup(appname);
1102 params->devclass = devclass;
1108 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1110 meshlink_errno = MESHLINK_EINVAL;
1114 params->netns = netns;
1119 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1121 meshlink_errno = MESHLINK_EINVAL;
1125 if((!key && keylen) || (key && !keylen)) {
1126 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1127 meshlink_errno = MESHLINK_EINVAL;
1132 params->keylen = keylen;
1137 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1138 if(!mesh || !new_key || !new_keylen) {
1139 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1140 meshlink_errno = MESHLINK_EINVAL;
1144 pthread_mutex_lock(&mesh->mutex);
1146 // Create hash for the new key
1147 void *new_config_key;
1148 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1150 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1151 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1152 meshlink_errno = MESHLINK_EINTERNAL;
1153 pthread_mutex_unlock(&mesh->mutex);
1157 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1159 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1160 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1161 meshlink_errno = MESHLINK_ESTORAGE;
1162 pthread_mutex_unlock(&mesh->mutex);
1166 devtool_keyrotate_probe(1);
1168 // Rename confbase/current/ to confbase/old
1170 if(!config_rename(mesh, "current", "old")) {
1171 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1172 meshlink_errno = MESHLINK_ESTORAGE;
1173 pthread_mutex_unlock(&mesh->mutex);
1177 devtool_keyrotate_probe(2);
1179 // Rename confbase/new/ to confbase/current
1181 if(!config_rename(mesh, "new", "current")) {
1182 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1183 meshlink_errno = MESHLINK_ESTORAGE;
1184 pthread_mutex_unlock(&mesh->mutex);
1188 devtool_keyrotate_probe(3);
1190 // Cleanup the "old" confbase sub-directory
1192 if(!config_destroy(mesh->confbase, "old")) {
1193 pthread_mutex_unlock(&mesh->mutex);
1197 // Change the mesh handle key with new key
1199 free(mesh->config_key);
1200 mesh->config_key = new_config_key;
1202 pthread_mutex_unlock(&mesh->mutex);
1207 void meshlink_open_params_free(meshlink_open_params_t *params) {
1209 meshlink_errno = MESHLINK_EINVAL;
1213 free(params->confbase);
1215 free(params->appname);
1220 /// Device class traits
1221 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1222 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1223 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1224 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1225 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1228 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1229 if(!confbase || !*confbase) {
1230 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1231 meshlink_errno = MESHLINK_EINVAL;
1235 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1236 meshlink_open_params_t params;
1237 memset(¶ms, 0, sizeof(params));
1239 params.confbase = (char *)confbase;
1240 params.name = (char *)name;
1241 params.appname = (char *)appname;
1242 params.devclass = devclass;
1245 return meshlink_open_ex(¶ms);
1248 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) {
1249 if(!confbase || !*confbase) {
1250 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1251 meshlink_errno = MESHLINK_EINVAL;
1255 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1256 meshlink_open_params_t params;
1257 memset(¶ms, 0, sizeof(params));
1259 params.confbase = (char *)confbase;
1260 params.name = (char *)name;
1261 params.appname = (char *)appname;
1262 params.devclass = devclass;
1265 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1269 return meshlink_open_ex(¶ms);
1272 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1273 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1274 meshlink_open_params_t params;
1275 memset(¶ms, 0, sizeof(params));
1277 params.name = (char *)name;
1278 params.appname = (char *)appname;
1279 params.devclass = devclass;
1282 return meshlink_open_ex(¶ms);
1285 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1286 // Validate arguments provided by the application
1287 bool usingname = false;
1289 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1291 if(!params->appname || !*params->appname) {
1292 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1293 meshlink_errno = MESHLINK_EINVAL;
1297 if(strchr(params->appname, ' ')) {
1298 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1299 meshlink_errno = MESHLINK_EINVAL;
1303 if(!params->name || !*params->name) {
1304 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1306 } else { //check name only if there is a name != NULL
1308 if(!check_id(params->name)) {
1309 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1310 meshlink_errno = MESHLINK_EINVAL;
1317 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1318 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1319 meshlink_errno = MESHLINK_EINVAL;
1323 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1324 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1325 meshlink_errno = MESHLINK_EINVAL;
1329 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1331 if(params->confbase) {
1332 mesh->confbase = xstrdup(params->confbase);
1335 mesh->appname = xstrdup(params->appname);
1336 mesh->devclass = params->devclass;
1337 mesh->discovery = true;
1338 mesh->invitation_timeout = 604800; // 1 week
1339 mesh->netns = params->netns;
1340 mesh->submeshes = NULL;
1341 mesh->log_cb = global_log_cb;
1342 mesh->log_level = global_log_level;
1344 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1347 randomize(&mesh->session_id, sizeof(mesh->session_id));
1348 } while(mesh->session_id == 0);
1350 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1353 mesh->name = xstrdup(params->name);
1358 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1360 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1361 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1362 meshlink_close(mesh);
1363 meshlink_errno = MESHLINK_EINTERNAL;
1369 pthread_mutexattr_t attr;
1370 pthread_mutexattr_init(&attr);
1371 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1372 pthread_mutex_init(&mesh->mutex, &attr);
1374 mesh->threadstarted = false;
1375 event_loop_init(&mesh->loop);
1376 mesh->loop.data = mesh;
1378 meshlink_queue_init(&mesh->outpacketqueue);
1380 // Atomically lock the configuration directory.
1381 if(!main_config_lock(mesh)) {
1382 meshlink_close(mesh);
1386 // If no configuration exists yet, create it.
1388 if(!meshlink_confbase_exists(mesh)) {
1389 if(!meshlink_setup(mesh)) {
1390 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1391 meshlink_close(mesh);
1395 if(!meshlink_read_config(mesh)) {
1396 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1397 meshlink_close(mesh);
1403 struct WSAData wsa_state;
1404 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1407 // Setup up everything
1408 // TODO: we should not open listening sockets yet
1410 bool success = false;
1412 if(mesh->netns != -1) {
1416 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1417 void *retval = NULL;
1418 success = pthread_join(thr, &retval) == 0 && retval;
1422 meshlink_errno = MESHLINK_EINTERNAL;
1425 #endif // HAVE_SETNS
1427 success = setup_network(mesh);
1428 add_local_addresses(mesh);
1432 meshlink_close(mesh);
1433 meshlink_errno = MESHLINK_ENETWORK;
1437 add_local_addresses(mesh);
1439 if(!node_write_config(mesh, mesh->self)) {
1440 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1444 idle_set(&mesh->loop, idle, mesh);
1446 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1450 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1451 meshlink_submesh_t *s = NULL;
1454 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1455 meshlink_errno = MESHLINK_EINVAL;
1459 if(!submesh || !*submesh) {
1460 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1461 meshlink_errno = MESHLINK_EINVAL;
1466 pthread_mutex_lock(&mesh->mutex);
1468 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1470 pthread_mutex_unlock(&mesh->mutex);
1475 static void *meshlink_main_loop(void *arg) {
1476 meshlink_handle_t *mesh = arg;
1478 if(mesh->netns != -1) {
1481 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1482 pthread_cond_signal(&mesh->cond);
1487 pthread_cond_signal(&mesh->cond);
1489 #endif // HAVE_SETNS
1494 if(mesh->discovery) {
1495 discovery_start(mesh);
1500 pthread_mutex_lock(&mesh->mutex);
1502 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1503 pthread_cond_broadcast(&mesh->cond);
1505 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1507 pthread_mutex_unlock(&mesh->mutex);
1512 if(mesh->discovery) {
1513 discovery_stop(mesh);
1521 bool meshlink_start(meshlink_handle_t *mesh) {
1523 assert(mesh->private_key);
1526 meshlink_errno = MESHLINK_EINVAL;
1530 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1532 pthread_mutex_lock(&mesh->mutex);
1534 assert(mesh->self->ecdsa);
1535 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1537 if(mesh->threadstarted) {
1538 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1539 pthread_mutex_unlock(&mesh->mutex);
1543 if(mesh->listen_socket[0].tcp.fd < 0) {
1544 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1545 meshlink_errno = MESHLINK_ENETWORK;
1549 mesh->thedatalen = 0;
1551 // TODO: open listening sockets first
1553 //Check that a valid name is set
1555 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1556 meshlink_errno = MESHLINK_EINVAL;
1557 pthread_mutex_unlock(&mesh->mutex);
1561 init_outgoings(mesh);
1563 // Start the main thread
1565 event_loop_start(&mesh->loop);
1567 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1568 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1569 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1570 meshlink_errno = MESHLINK_EINTERNAL;
1571 event_loop_stop(&mesh->loop);
1572 pthread_mutex_unlock(&mesh->mutex);
1576 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1577 mesh->threadstarted = true;
1579 // Ensure we are considered reachable
1582 pthread_mutex_unlock(&mesh->mutex);
1586 void meshlink_stop(meshlink_handle_t *mesh) {
1588 meshlink_errno = MESHLINK_EINVAL;
1592 pthread_mutex_lock(&mesh->mutex);
1593 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1595 // Shut down the main thread
1596 event_loop_stop(&mesh->loop);
1598 // Send ourselves a UDP packet to kick the event loop
1599 for(int i = 0; i < mesh->listen_sockets; i++) {
1601 socklen_t salen = sizeof(sa);
1603 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1604 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1608 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1609 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1613 if(mesh->threadstarted) {
1614 // Wait for the main thread to finish
1615 pthread_mutex_unlock(&mesh->mutex);
1616 pthread_join(mesh->thread, NULL);
1617 pthread_mutex_lock(&mesh->mutex);
1619 mesh->threadstarted = false;
1622 // Close all metaconnections
1623 if(mesh->connections) {
1624 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1626 connection_t *c = node->data;
1628 terminate_connection(mesh, c, false);
1632 exit_outgoings(mesh);
1634 // Ensure we are considered unreachable
1639 // Try to write out any changed node config files, ignore errors at this point.
1641 for splay_each(node_t, n, mesh->nodes) {
1642 if(n->status.dirty) {
1643 n->status.dirty = !node_write_config(mesh, n);
1648 pthread_mutex_unlock(&mesh->mutex);
1651 void meshlink_close(meshlink_handle_t *mesh) {
1653 meshlink_errno = MESHLINK_EINVAL;
1657 // stop can be called even if mesh has not been started
1658 meshlink_stop(mesh);
1660 // lock is not released after this
1661 pthread_mutex_lock(&mesh->mutex);
1663 // Close and free all resources used.
1665 close_network_connections(mesh);
1667 logger(mesh, MESHLINK_INFO, "Terminating");
1669 event_loop_exit(&mesh->loop);
1673 if(mesh->confbase) {
1679 ecdsa_free(mesh->invitation_key);
1681 if(mesh->netns != -1) {
1685 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1689 meshlink_queue_exit(&mesh->outpacketqueue);
1692 free(mesh->appname);
1693 free(mesh->confbase);
1694 free(mesh->config_key);
1695 ecdsa_free(mesh->private_key);
1697 main_config_unlock(mesh);
1699 pthread_mutex_unlock(&mesh->mutex);
1700 pthread_mutex_destroy(&mesh->mutex);
1702 memset(mesh, 0, sizeof(*mesh));
1707 bool meshlink_destroy(const char *confbase) {
1709 meshlink_errno = MESHLINK_EINVAL;
1713 /* Exit early if the confbase directory itself doesn't exist */
1714 if(access(confbase, F_OK) && errno == ENOENT) {
1718 /* Take the lock the same way meshlink_open() would. */
1719 char lockfilename[PATH_MAX];
1720 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1722 FILE *lockfile = fopen(lockfilename, "w+");
1725 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1726 meshlink_errno = MESHLINK_ESTORAGE;
1731 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1735 // TODO: use _locking()?
1738 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1739 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1741 meshlink_errno = MESHLINK_EBUSY;
1747 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1748 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1752 if(unlink(lockfilename)) {
1753 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1755 meshlink_errno = MESHLINK_ESTORAGE;
1761 if(!sync_path(confbase)) {
1762 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1763 meshlink_errno = MESHLINK_ESTORAGE;
1770 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1772 meshlink_errno = MESHLINK_EINVAL;
1776 pthread_mutex_lock(&mesh->mutex);
1777 mesh->receive_cb = cb;
1778 pthread_mutex_unlock(&mesh->mutex);
1781 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1783 meshlink_errno = MESHLINK_EINVAL;
1787 pthread_mutex_lock(&mesh->mutex);
1788 mesh->connection_try_cb = cb;
1789 pthread_mutex_unlock(&mesh->mutex);
1792 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1794 meshlink_errno = MESHLINK_EINVAL;
1798 pthread_mutex_lock(&mesh->mutex);
1799 mesh->node_status_cb = cb;
1800 pthread_mutex_unlock(&mesh->mutex);
1803 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1805 meshlink_errno = MESHLINK_EINVAL;
1809 pthread_mutex_lock(&mesh->mutex);
1810 mesh->node_pmtu_cb = cb;
1811 pthread_mutex_unlock(&mesh->mutex);
1814 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1816 meshlink_errno = MESHLINK_EINVAL;
1820 pthread_mutex_lock(&mesh->mutex);
1821 mesh->node_duplicate_cb = cb;
1822 pthread_mutex_unlock(&mesh->mutex);
1825 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1827 pthread_mutex_lock(&mesh->mutex);
1829 mesh->log_level = cb ? level : 0;
1830 pthread_mutex_unlock(&mesh->mutex);
1833 global_log_level = cb ? level : 0;
1837 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1839 meshlink_errno = MESHLINK_EINVAL;
1843 pthread_mutex_lock(&mesh->mutex);
1844 mesh->error_cb = cb;
1845 pthread_mutex_unlock(&mesh->mutex);
1848 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1849 meshlink_packethdr_t *hdr;
1851 // Validate arguments
1852 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1853 meshlink_errno = MESHLINK_EINVAL;
1862 meshlink_errno = MESHLINK_EINVAL;
1866 node_t *n = (node_t *)destination;
1868 if(n->status.blacklisted) {
1869 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1870 meshlink_errno = MESHLINK_EBLACKLISTED;
1874 // Prepare the packet
1875 vpn_packet_t *packet = malloc(sizeof(*packet));
1878 meshlink_errno = MESHLINK_ENOMEM;
1882 packet->probe = false;
1883 packet->tcp = false;
1884 packet->len = len + sizeof(*hdr);
1886 hdr = (meshlink_packethdr_t *)packet->data;
1887 memset(hdr, 0, sizeof(*hdr));
1888 // leave the last byte as 0 to make sure strings are always
1889 // null-terminated if they are longer than the buffer
1890 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1891 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1893 memcpy(packet->data + sizeof(*hdr), data, len);
1896 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1898 meshlink_errno = MESHLINK_ENOMEM;
1902 // Notify event loop
1903 signal_trigger(&mesh->loop, &mesh->datafromapp);
1908 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1910 meshlink_handle_t *mesh = data;
1911 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1917 mesh->self->in_packets++;
1918 mesh->self->in_bytes += packet->len;
1919 route(mesh, mesh->self, packet);
1924 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1925 if(!mesh || !destination) {
1926 meshlink_errno = MESHLINK_EINVAL;
1930 pthread_mutex_lock(&mesh->mutex);
1932 node_t *n = (node_t *)destination;
1934 if(!n->status.reachable) {
1935 pthread_mutex_unlock(&mesh->mutex);
1938 } else if(n->mtuprobes > 30 && n->minmtu) {
1939 pthread_mutex_unlock(&mesh->mutex);
1942 pthread_mutex_unlock(&mesh->mutex);
1947 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1948 if(!mesh || !node) {
1949 meshlink_errno = MESHLINK_EINVAL;
1953 pthread_mutex_lock(&mesh->mutex);
1955 node_t *n = (node_t *)node;
1957 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1958 meshlink_errno = MESHLINK_EINTERNAL;
1959 pthread_mutex_unlock(&mesh->mutex);
1963 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1966 meshlink_errno = MESHLINK_EINTERNAL;
1969 pthread_mutex_unlock(&mesh->mutex);
1973 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1975 meshlink_errno = MESHLINK_EINVAL;
1979 return (meshlink_node_t *)mesh->self;
1982 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1983 if(!mesh || !name) {
1984 meshlink_errno = MESHLINK_EINVAL;
1990 pthread_mutex_lock(&mesh->mutex);
1991 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1992 pthread_mutex_unlock(&mesh->mutex);
1995 meshlink_errno = MESHLINK_ENOENT;
1998 return (meshlink_node_t *)n;
2001 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2002 if(!mesh || !name) {
2003 meshlink_errno = MESHLINK_EINVAL;
2007 meshlink_submesh_t *submesh = NULL;
2009 pthread_mutex_lock(&mesh->mutex);
2010 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2011 pthread_mutex_unlock(&mesh->mutex);
2014 meshlink_errno = MESHLINK_ENOENT;
2020 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2021 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2022 meshlink_errno = MESHLINK_EINVAL;
2026 meshlink_node_t **result;
2029 pthread_mutex_lock(&mesh->mutex);
2031 *nmemb = mesh->nodes->count;
2032 result = realloc(nodes, *nmemb * sizeof(*nodes));
2035 meshlink_node_t **p = result;
2037 for splay_each(node_t, n, mesh->nodes) {
2038 *p++ = (meshlink_node_t *)n;
2043 meshlink_errno = MESHLINK_ENOMEM;
2046 pthread_mutex_unlock(&mesh->mutex);
2051 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) {
2052 meshlink_node_t **result;
2054 pthread_mutex_lock(&mesh->mutex);
2058 for splay_each(node_t, n, mesh->nodes) {
2059 if(search_node(n, condition)) {
2066 pthread_mutex_unlock(&mesh->mutex);
2070 result = realloc(nodes, *nmemb * sizeof(*nodes));
2073 meshlink_node_t **p = result;
2075 for splay_each(node_t, n, mesh->nodes) {
2076 if(search_node(n, condition)) {
2077 *p++ = (meshlink_node_t *)n;
2083 meshlink_errno = MESHLINK_ENOMEM;
2086 pthread_mutex_unlock(&mesh->mutex);
2091 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2092 dev_class_t *devclass = (dev_class_t *)condition;
2094 if(*devclass == (dev_class_t)node->devclass) {
2101 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2102 if(condition == node->submesh) {
2114 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2115 const struct time_range *range = condition;
2116 time_t start = node->last_reachable;
2117 time_t end = node->last_unreachable;
2127 if(range->end >= range->start) {
2128 return start <= range->end && end >= range->start;
2130 return start > range->start || end < range->end;
2134 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) {
2135 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2136 meshlink_errno = MESHLINK_EINVAL;
2140 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2143 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2144 if(!mesh || !submesh || !nmemb) {
2145 meshlink_errno = MESHLINK_EINVAL;
2149 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2152 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) {
2153 if(!mesh || !nmemb) {
2154 meshlink_errno = MESHLINK_EINVAL;
2158 struct time_range range = {start, end};
2160 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2163 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2164 if(!mesh || !node) {
2165 meshlink_errno = MESHLINK_EINVAL;
2169 dev_class_t devclass;
2171 pthread_mutex_lock(&mesh->mutex);
2173 devclass = ((node_t *)node)->devclass;
2175 pthread_mutex_unlock(&mesh->mutex);
2180 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2181 if(!mesh || !node) {
2182 meshlink_errno = MESHLINK_EINVAL;
2186 node_t *n = (node_t *)node;
2188 meshlink_submesh_t *s;
2190 s = (meshlink_submesh_t *)n->submesh;
2195 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2196 if(!mesh || !node) {
2197 meshlink_errno = MESHLINK_EINVAL;
2201 node_t *n = (node_t *)node;
2204 pthread_mutex_lock(&mesh->mutex);
2205 reachable = n->status.reachable && !n->status.blacklisted;
2207 if(last_reachable) {
2208 *last_reachable = n->last_reachable;
2211 if(last_unreachable) {
2212 *last_unreachable = n->last_unreachable;
2215 pthread_mutex_unlock(&mesh->mutex);
2220 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2221 if(!mesh || !data || !len || !signature || !siglen) {
2222 meshlink_errno = MESHLINK_EINVAL;
2226 if(*siglen < MESHLINK_SIGLEN) {
2227 meshlink_errno = MESHLINK_EINVAL;
2231 pthread_mutex_lock(&mesh->mutex);
2233 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2234 meshlink_errno = MESHLINK_EINTERNAL;
2235 pthread_mutex_unlock(&mesh->mutex);
2239 *siglen = MESHLINK_SIGLEN;
2240 pthread_mutex_unlock(&mesh->mutex);
2244 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2245 if(!mesh || !data || !len || !signature) {
2246 meshlink_errno = MESHLINK_EINVAL;
2250 if(siglen != MESHLINK_SIGLEN) {
2251 meshlink_errno = MESHLINK_EINVAL;
2255 pthread_mutex_lock(&mesh->mutex);
2259 struct node_t *n = (struct node_t *)source;
2261 if(!node_read_public_key(mesh, n)) {
2262 meshlink_errno = MESHLINK_EINTERNAL;
2265 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2268 pthread_mutex_unlock(&mesh->mutex);
2272 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2273 pthread_mutex_lock(&mesh->mutex);
2275 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2278 // TODO: Update invitation key if necessary?
2281 pthread_mutex_unlock(&mesh->mutex);
2283 return mesh->invitation_key;
2286 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2287 if(!mesh || !node || !address) {
2288 meshlink_errno = MESHLINK_EINVAL;
2292 if(!is_valid_hostname(address)) {
2293 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2294 meshlink_errno = MESHLINK_EINVAL;
2298 if(port && !is_valid_port(port)) {
2299 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2300 meshlink_errno = MESHLINK_EINVAL;
2304 char *canonical_address;
2307 xasprintf(&canonical_address, "%s %s", address, port);
2309 canonical_address = xstrdup(address);
2312 pthread_mutex_lock(&mesh->mutex);
2314 node_t *n = (node_t *)node;
2315 free(n->canonical_address);
2316 n->canonical_address = canonical_address;
2318 if(!node_write_config(mesh, n)) {
2319 pthread_mutex_unlock(&mesh->mutex);
2323 pthread_mutex_unlock(&mesh->mutex);
2325 return config_sync(mesh, "current");
2328 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2329 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2332 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2334 meshlink_errno = MESHLINK_EINVAL;
2338 char *address = meshlink_get_external_address(mesh);
2344 bool rval = meshlink_add_address(mesh, address);
2350 int meshlink_get_port(meshlink_handle_t *mesh) {
2352 meshlink_errno = MESHLINK_EINVAL;
2357 meshlink_errno = MESHLINK_EINTERNAL;
2363 pthread_mutex_lock(&mesh->mutex);
2364 port = atoi(mesh->myport);
2365 pthread_mutex_unlock(&mesh->mutex);
2370 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2371 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2372 meshlink_errno = MESHLINK_EINVAL;
2376 if(mesh->myport && port == atoi(mesh->myport)) {
2380 if(!try_bind(port)) {
2381 meshlink_errno = MESHLINK_ENETWORK;
2385 devtool_trybind_probe();
2389 pthread_mutex_lock(&mesh->mutex);
2391 if(mesh->threadstarted) {
2392 meshlink_errno = MESHLINK_EINVAL;
2397 xasprintf(&mesh->myport, "%d", port);
2399 /* Close down the network. This also deletes mesh->self. */
2400 close_network_connections(mesh);
2402 /* Recreate mesh->self. */
2403 mesh->self = new_node();
2404 mesh->self->name = xstrdup(mesh->name);
2405 mesh->self->devclass = mesh->devclass;
2406 mesh->self->session_id = mesh->session_id;
2407 xasprintf(&mesh->myport, "%d", port);
2409 if(!node_read_public_key(mesh, mesh->self)) {
2410 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2411 meshlink_errno = MESHLINK_ESTORAGE;
2412 free_node(mesh->self);
2415 } else if(!setup_network(mesh)) {
2416 meshlink_errno = MESHLINK_ENETWORK;
2420 /* Rebuild our own list of recent addresses */
2421 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2422 add_local_addresses(mesh);
2424 /* Write meshlink.conf with the updated port number */
2425 write_main_config_files(mesh);
2427 rval = config_sync(mesh, "current");
2430 pthread_mutex_unlock(&mesh->mutex);
2432 return rval && meshlink_get_port(mesh) == port;
2435 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2436 mesh->invitation_timeout = timeout;
2439 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2440 meshlink_submesh_t *s = NULL;
2443 meshlink_errno = MESHLINK_EINVAL;
2448 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2451 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2452 meshlink_errno = MESHLINK_EINVAL;
2456 s = (meshlink_submesh_t *)mesh->self->submesh;
2459 pthread_mutex_lock(&mesh->mutex);
2461 // Check validity of the new node's name
2462 if(!check_id(name)) {
2463 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2464 meshlink_errno = MESHLINK_EINVAL;
2465 pthread_mutex_unlock(&mesh->mutex);
2469 // Ensure no host configuration file with that name exists
2470 if(config_exists(mesh, "current", name)) {
2471 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2472 meshlink_errno = MESHLINK_EEXIST;
2473 pthread_mutex_unlock(&mesh->mutex);
2477 // Ensure no other nodes know about this name
2478 if(lookup_node(mesh, name)) {
2479 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2480 meshlink_errno = MESHLINK_EEXIST;
2481 pthread_mutex_unlock(&mesh->mutex);
2485 // Get the local address
2486 char *address = get_my_hostname(mesh, flags);
2489 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2490 meshlink_errno = MESHLINK_ERESOLV;
2491 pthread_mutex_unlock(&mesh->mutex);
2495 if(!refresh_invitation_key(mesh)) {
2496 meshlink_errno = MESHLINK_EINTERNAL;
2497 pthread_mutex_unlock(&mesh->mutex);
2501 // If we changed our own host config file, write it out now
2502 if(mesh->self->status.dirty) {
2503 if(!node_write_config(mesh, mesh->self)) {
2504 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2505 pthread_mutex_unlock(&mesh->mutex);
2512 // Create a hash of the key.
2513 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2514 sha512(fingerprint, strlen(fingerprint), hash);
2515 b64encode_urlsafe(hash, hash, 18);
2517 // Create a random cookie for this invitation.
2519 randomize(cookie, 18);
2521 // Create a filename that doesn't reveal the cookie itself
2522 char buf[18 + strlen(fingerprint)];
2523 char cookiehash[64];
2524 memcpy(buf, cookie, 18);
2525 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2526 sha512(buf, sizeof(buf), cookiehash);
2527 b64encode_urlsafe(cookiehash, cookiehash, 18);
2529 b64encode_urlsafe(cookie, cookie, 18);
2533 /* Construct the invitation file */
2534 uint8_t outbuf[4096];
2535 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2537 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2538 packmsg_add_str(&inv, name);
2539 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2540 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2542 /* TODO: Add several host config files to bootstrap connections.
2543 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2544 * and are not blacklisted.
2546 config_t configs[5];
2547 memset(configs, 0, sizeof(configs));
2550 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2554 /* Append host config files to the invitation file */
2555 packmsg_add_array(&inv, count);
2557 for(int i = 0; i < count; i++) {
2558 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2559 config_free(&configs[i]);
2562 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2564 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2565 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2566 meshlink_errno = MESHLINK_ESTORAGE;
2567 pthread_mutex_unlock(&mesh->mutex);
2571 // Create an URL from the local address, key hash and cookie
2573 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2576 pthread_mutex_unlock(&mesh->mutex);
2580 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2581 return meshlink_invite_ex(mesh, submesh, name, 0);
2584 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2585 if(!mesh || !invitation) {
2586 meshlink_errno = MESHLINK_EINVAL;
2590 pthread_mutex_lock(&mesh->mutex);
2592 //Before doing meshlink_join make sure we are not connected to another mesh
2593 if(mesh->threadstarted) {
2594 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2595 meshlink_errno = MESHLINK_EINVAL;
2596 pthread_mutex_unlock(&mesh->mutex);
2600 // 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.
2601 if(mesh->nodes->count > 1) {
2602 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2603 meshlink_errno = MESHLINK_EINVAL;
2604 pthread_mutex_unlock(&mesh->mutex);
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];
2610 strcpy(copy, invitation);
2612 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2614 char *slash = strchr(copy, '/');
2622 if(strlen(slash) != 48) {
2626 char *address = copy;
2629 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2633 // Generate a throw-away key for the invitation.
2634 ecdsa_t *key = ecdsa_generate();
2637 meshlink_errno = MESHLINK_EINTERNAL;
2638 pthread_mutex_unlock(&mesh->mutex);
2642 char *b64key = ecdsa_get_base64_public_key(key);
2646 while(address && *address) {
2647 // We allow commas in the address part to support multiple addresses in one invitation URL.
2648 comma = strchr(address, ',');
2654 // Split of the port
2655 port = strrchr(address, ':');
2663 // IPv6 address are enclosed in brackets, per RFC 3986
2664 if(*address == '[') {
2666 char *bracket = strchr(address, ']');
2679 // Connect to the meshlink daemon mentioned in the URL.
2680 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2683 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2684 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2686 if(mesh->sock == -1) {
2687 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2688 meshlink_errno = MESHLINK_ENETWORK;
2692 set_timeout(mesh->sock, 5000);
2694 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2695 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2696 meshlink_errno = MESHLINK_ENETWORK;
2697 closesocket(mesh->sock);
2705 meshlink_errno = MESHLINK_ERESOLV;
2708 if(mesh->sock != -1 || !comma) {
2715 if(mesh->sock == -1) {
2716 pthread_mutex_unlock(&mesh->mutex);
2720 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2722 // Tell him we have an invitation, and give him our throw-away key.
2726 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2727 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2728 closesocket(mesh->sock);
2729 meshlink_errno = MESHLINK_ENETWORK;
2730 pthread_mutex_unlock(&mesh->mutex);
2736 char hisname[4096] = "";
2737 int code, hismajor, hisminor = 0;
2739 if(!recvline(mesh, sizeof(mesh)->line) || sscanf(mesh->line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(mesh, sizeof(mesh)->line) || !rstrip(mesh->line) || sscanf(mesh->line, "%d ", &code) != 1 || code != ACK || strlen(mesh->line) < 3) {
2740 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2741 closesocket(mesh->sock);
2742 meshlink_errno = MESHLINK_ENETWORK;
2743 pthread_mutex_unlock(&mesh->mutex);
2747 // Check if the hash of the key he gave us matches the hash in the URL.
2748 char *fingerprint = mesh->line + 2;
2751 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2752 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2753 meshlink_errno = MESHLINK_EINTERNAL;
2754 pthread_mutex_unlock(&mesh->mutex);
2758 if(memcmp(hishash, mesh->hash, 18)) {
2759 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2760 meshlink_errno = MESHLINK_EPEER;
2761 pthread_mutex_unlock(&mesh->mutex);
2766 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2769 meshlink_errno = MESHLINK_EINTERNAL;
2770 pthread_mutex_unlock(&mesh->mutex);
2774 // Start an SPTPS session
2775 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2776 meshlink_errno = MESHLINK_EINTERNAL;
2777 pthread_mutex_unlock(&mesh->mutex);
2781 // Feed rest of input buffer to SPTPS
2782 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2783 meshlink_errno = MESHLINK_EPEER;
2784 pthread_mutex_unlock(&mesh->mutex);
2790 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2792 if(errno == EINTR) {
2796 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2797 meshlink_errno = MESHLINK_ENETWORK;
2798 pthread_mutex_unlock(&mesh->mutex);
2802 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2803 meshlink_errno = MESHLINK_EPEER;
2804 pthread_mutex_unlock(&mesh->mutex);
2809 sptps_stop(&mesh->sptps);
2812 closesocket(mesh->sock);
2814 if(!mesh->success) {
2815 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2816 meshlink_errno = MESHLINK_EPEER;
2817 pthread_mutex_unlock(&mesh->mutex);
2821 pthread_mutex_unlock(&mesh->mutex);
2825 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2826 meshlink_errno = MESHLINK_EINVAL;
2827 pthread_mutex_unlock(&mesh->mutex);
2831 char *meshlink_export(meshlink_handle_t *mesh) {
2833 meshlink_errno = MESHLINK_EINVAL;
2837 // Create a config file on the fly.
2840 packmsg_output_t out = {buf, sizeof(buf)};
2841 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2842 packmsg_add_str(&out, mesh->name);
2843 packmsg_add_str(&out, CORE_MESH);
2845 pthread_mutex_lock(&mesh->mutex);
2847 packmsg_add_int32(&out, mesh->self->devclass);
2848 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2849 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2850 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2854 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2855 if(mesh->self->recent[i].sa.sa_family) {
2862 packmsg_add_array(&out, count);
2864 for(uint32_t i = 0; i < count; i++) {
2865 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2868 packmsg_add_int64(&out, 0);
2869 packmsg_add_int64(&out, 0);
2871 pthread_mutex_unlock(&mesh->mutex);
2873 if(!packmsg_output_ok(&out)) {
2874 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2875 meshlink_errno = MESHLINK_EINTERNAL;
2879 // Prepare a base64-encoded packmsg array containing our config file
2881 uint32_t len = packmsg_output_size(&out, buf);
2882 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2883 uint8_t *buf2 = xmalloc(len2);
2884 packmsg_output_t out2 = {buf2, len2};
2885 packmsg_add_array(&out2, 1);
2886 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2888 if(!packmsg_output_ok(&out2)) {
2889 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2890 meshlink_errno = MESHLINK_EINTERNAL;
2895 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2897 return (char *)buf2;
2900 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2901 if(!mesh || !data) {
2902 meshlink_errno = MESHLINK_EINVAL;
2906 size_t datalen = strlen(data);
2907 uint8_t *buf = xmalloc(datalen);
2908 int buflen = b64decode(data, buf, datalen);
2911 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2912 meshlink_errno = MESHLINK_EPEER;
2916 packmsg_input_t in = {buf, buflen};
2917 uint32_t count = packmsg_get_array(&in);
2920 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2921 meshlink_errno = MESHLINK_EPEER;
2925 pthread_mutex_lock(&mesh->mutex);
2929 uint32_t len = packmsg_get_bin_raw(&in, &data);
2935 packmsg_input_t in2 = {data, len};
2936 uint32_t version = packmsg_get_uint32(&in2);
2937 char *name = packmsg_get_str_dup(&in2);
2939 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2941 packmsg_input_invalidate(&in);
2945 if(!check_id(name)) {
2950 node_t *n = lookup_node(mesh, name);
2953 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2961 config_t config = {data, len};
2963 if(!node_read_from_config(mesh, n, &config)) {
2965 packmsg_input_invalidate(&in);
2969 /* Clear the reachability times, since we ourself have never seen these nodes yet */
2970 n->last_reachable = 0;
2971 n->last_unreachable = 0;
2973 if(!node_write_config(mesh, n)) {
2981 pthread_mutex_unlock(&mesh->mutex);
2985 if(!packmsg_done(&in)) {
2986 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2987 meshlink_errno = MESHLINK_EPEER;
2991 if(!config_sync(mesh, "current")) {
2998 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
2999 if(n == mesh->self) {
3000 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3001 meshlink_errno = MESHLINK_EINVAL;
3005 if(n->status.blacklisted) {
3006 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3010 n->status.blacklisted = true;
3012 /* Immediately shut down any connections we have with the blacklisted node.
3013 * We can't call terminate_connection(), because we might be called from a callback function.
3015 for list_each(connection_t, c, mesh->connections) {
3017 shutdown(c->socket, SHUT_RDWR);
3021 utcp_abort_all_connections(n->utcp);
3027 n->status.udp_confirmed = false;
3029 if(n->status.reachable) {
3030 n->last_unreachable = mesh->loop.now.tv_sec;
3033 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3034 * manually call the status callback if necessary.
3036 if(n->status.reachable && mesh->node_status_cb) {
3037 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3040 return node_write_config(mesh, n) && config_sync(mesh, "current");
3043 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3044 if(!mesh || !node) {
3045 meshlink_errno = MESHLINK_EINVAL;
3049 pthread_mutex_lock(&mesh->mutex);
3051 if(!blacklist(mesh, (node_t *)node)) {
3052 pthread_mutex_unlock(&mesh->mutex);
3056 pthread_mutex_unlock(&mesh->mutex);
3058 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3062 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3063 if(!mesh || !name) {
3064 meshlink_errno = MESHLINK_EINVAL;
3068 pthread_mutex_lock(&mesh->mutex);
3070 node_t *n = lookup_node(mesh, (char *)name);
3074 n->name = xstrdup(name);
3078 if(!blacklist(mesh, (node_t *)n)) {
3079 pthread_mutex_unlock(&mesh->mutex);
3083 pthread_mutex_unlock(&mesh->mutex);
3085 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3089 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3090 if(n == mesh->self) {
3091 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3092 meshlink_errno = MESHLINK_EINVAL;
3096 if(!n->status.blacklisted) {
3097 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3101 n->status.blacklisted = false;
3103 if(n->status.reachable) {
3104 n->last_reachable = mesh->loop.now.tv_sec;
3105 update_node_status(mesh, n);
3108 return node_write_config(mesh, n) && config_sync(mesh, "current");
3111 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3112 if(!mesh || !node) {
3113 meshlink_errno = MESHLINK_EINVAL;
3117 pthread_mutex_lock(&mesh->mutex);
3119 if(!whitelist(mesh, (node_t *)node)) {
3120 pthread_mutex_unlock(&mesh->mutex);
3124 pthread_mutex_unlock(&mesh->mutex);
3126 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3130 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3131 if(!mesh || !name) {
3132 meshlink_errno = MESHLINK_EINVAL;
3136 pthread_mutex_lock(&mesh->mutex);
3138 node_t *n = lookup_node(mesh, (char *)name);
3142 n->name = xstrdup(name);
3146 if(!whitelist(mesh, (node_t *)n)) {
3147 pthread_mutex_unlock(&mesh->mutex);
3151 pthread_mutex_unlock(&mesh->mutex);
3153 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3157 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3158 mesh->default_blacklist = blacklist;
3161 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3162 if(!mesh || !node) {
3163 meshlink_errno = MESHLINK_EINVAL;
3167 node_t *n = (node_t *)node;
3169 pthread_mutex_lock(&mesh->mutex);
3171 /* Check that the node is not reachable */
3172 if(n->status.reachable || n->connection) {
3173 pthread_mutex_unlock(&mesh->mutex);
3174 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3178 /* Check that we don't have any active UTCP connections */
3179 if(n->utcp && utcp_is_active(n->utcp)) {
3180 pthread_mutex_unlock(&mesh->mutex);
3181 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3185 /* Check that we have no active connections to this node */
3186 for list_each(connection_t, c, mesh->connections) {
3188 pthread_mutex_unlock(&mesh->mutex);
3189 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3194 /* Remove any pending outgoings to this node */
3195 if(mesh->outgoings) {
3196 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3197 if(outgoing->node == n) {
3198 list_delete_node(mesh->outgoings, node);
3203 /* Delete the config file for this node */
3204 if(!config_delete(mesh, "current", n->name)) {
3205 pthread_mutex_unlock(&mesh->mutex);
3209 /* Delete the node struct and any remaining edges referencing this node */
3212 pthread_mutex_unlock(&mesh->mutex);
3214 return config_sync(mesh, "current");
3217 /* Hint that a hostname may be found at an address
3218 * See header file for detailed comment.
3220 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3221 if(!mesh || !node || !addr) {
3222 meshlink_errno = EINVAL;
3226 pthread_mutex_lock(&mesh->mutex);
3228 node_t *n = (node_t *)node;
3230 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3231 if(!node_write_config(mesh, n)) {
3232 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3236 pthread_mutex_unlock(&mesh->mutex);
3237 // @TODO do we want to fire off a connection attempt right away?
3240 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3242 node_t *n = utcp->priv;
3243 meshlink_handle_t *mesh = n->mesh;
3244 return mesh->channel_accept_cb;
3247 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3249 if(aio->cb.buffer) {
3250 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3254 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3259 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3260 meshlink_channel_t *channel = connection->priv;
3266 node_t *n = channel->node;
3267 meshlink_handle_t *mesh = n->mesh;
3269 if(n->status.destroyed) {
3270 meshlink_channel_close(mesh, channel);
3274 const char *p = data;
3277 while(channel->aio_receive) {
3278 meshlink_aio_buffer_t *aio = channel->aio_receive;
3279 size_t todo = aio->len - aio->done;
3286 memcpy((char *)aio->data + aio->done, p, todo);
3288 ssize_t result = write(aio->fd, p, todo);
3297 if(aio->done == aio->len) {
3298 channel->aio_receive = aio->next;
3299 aio_signal(mesh, channel, aio);
3311 if(channel->receive_cb) {
3312 channel->receive_cb(mesh, channel, p, left);
3318 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3319 node_t *n = utcp_connection->utcp->priv;
3325 meshlink_handle_t *mesh = n->mesh;
3327 if(!mesh->channel_accept_cb) {
3331 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3333 channel->c = utcp_connection;
3335 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3336 utcp_accept(utcp_connection, channel_recv, channel);
3342 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3343 node_t *n = utcp->priv;
3345 if(n->status.destroyed) {
3349 meshlink_handle_t *mesh = n->mesh;
3350 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3353 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3354 if(!mesh || !channel) {
3355 meshlink_errno = MESHLINK_EINVAL;
3359 channel->receive_cb = cb;
3362 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3364 node_t *n = (node_t *)source;
3370 utcp_recv(n->utcp, data, len);
3373 static void channel_poll(struct utcp_connection *connection, size_t len) {
3374 meshlink_channel_t *channel = connection->priv;
3380 node_t *n = channel->node;
3381 meshlink_handle_t *mesh = n->mesh;
3382 meshlink_aio_buffer_t *aio = channel->aio_send;
3385 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3386 size_t left = aio->len - aio->done;
3394 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3397 size_t todo = utcp_get_sndbuf_free(connection);
3403 if(todo > sizeof(buf)) {
3407 ssize_t result = read(aio->fd, buf, todo);
3410 sent = utcp_send(connection, buf, result);
3420 /* If the buffer is now completely sent, call the callback and dispose of it. */
3421 if(aio->done >= aio->len) {
3422 channel->aio_send = aio->next;
3423 aio_signal(mesh, channel, aio);
3427 if(channel->poll_cb) {
3428 channel->poll_cb(mesh, channel, len);
3430 utcp_set_poll_cb(connection, NULL);
3435 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3436 if(!mesh || !channel) {
3437 meshlink_errno = MESHLINK_EINVAL;
3441 pthread_mutex_lock(&mesh->mutex);
3442 channel->poll_cb = cb;
3443 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3444 pthread_mutex_unlock(&mesh->mutex);
3447 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3449 meshlink_errno = MESHLINK_EINVAL;
3453 pthread_mutex_lock(&mesh->mutex);
3454 mesh->channel_accept_cb = cb;
3455 mesh->receive_cb = channel_receive;
3457 for splay_each(node_t, n, mesh->nodes) {
3458 if(!n->utcp && n != mesh->self) {
3459 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3463 pthread_mutex_unlock(&mesh->mutex);
3466 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3470 meshlink_errno = MESHLINK_EINVAL;
3474 pthread_mutex_lock(&mesh->mutex);
3475 utcp_set_sndbuf(channel->c, size);
3476 pthread_mutex_unlock(&mesh->mutex);
3479 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3483 meshlink_errno = MESHLINK_EINVAL;
3487 pthread_mutex_lock(&mesh->mutex);
3488 utcp_set_rcvbuf(channel->c, size);
3489 pthread_mutex_unlock(&mesh->mutex);
3492 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) {
3494 abort(); // TODO: handle non-NULL data
3497 if(!mesh || !node) {
3498 meshlink_errno = MESHLINK_EINVAL;
3502 pthread_mutex_lock(&mesh->mutex);
3504 node_t *n = (node_t *)node;
3507 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3508 mesh->receive_cb = channel_receive;
3511 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3512 pthread_mutex_unlock(&mesh->mutex);
3517 if(n->status.blacklisted) {
3518 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3519 meshlink_errno = MESHLINK_EBLACKLISTED;
3520 pthread_mutex_unlock(&mesh->mutex);
3524 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3526 channel->receive_cb = cb;
3529 channel->priv = (void *)data;
3532 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3534 pthread_mutex_unlock(&mesh->mutex);
3537 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3545 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) {
3546 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3549 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3550 if(!mesh || !channel) {
3551 meshlink_errno = MESHLINK_EINVAL;
3555 pthread_mutex_lock(&mesh->mutex);
3556 utcp_shutdown(channel->c, direction);
3557 pthread_mutex_unlock(&mesh->mutex);
3560 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3561 if(!mesh || !channel) {
3562 meshlink_errno = MESHLINK_EINVAL;
3566 pthread_mutex_lock(&mesh->mutex);
3568 utcp_close(channel->c);
3570 /* Clean up any outstanding AIO buffers. */
3571 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3573 aio_signal(mesh, channel, aio);
3577 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3579 aio_signal(mesh, channel, aio);
3583 pthread_mutex_unlock(&mesh->mutex);
3588 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3589 if(!mesh || !channel) {
3590 meshlink_errno = MESHLINK_EINVAL;
3599 meshlink_errno = MESHLINK_EINVAL;
3603 // TODO: more finegrained locking.
3604 // Ideally we want to put the data into the UTCP connection's send buffer.
3605 // Then, preferably only if there is room in the receiver window,
3606 // kick the meshlink thread to go send packets.
3610 pthread_mutex_lock(&mesh->mutex);
3612 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3613 if(channel->aio_send) {
3616 retval = utcp_send(channel->c, data, len);
3619 pthread_mutex_unlock(&mesh->mutex);
3622 meshlink_errno = MESHLINK_ENETWORK;
3628 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) {
3629 if(!mesh || !channel) {
3630 meshlink_errno = MESHLINK_EINVAL;
3635 meshlink_errno = MESHLINK_EINVAL;
3639 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3642 aio->cb.buffer = cb;
3645 pthread_mutex_lock(&mesh->mutex);
3647 /* Append the AIO buffer descriptor to the end of the chain */
3648 meshlink_aio_buffer_t **p = &channel->aio_send;
3656 /* Ensure the poll callback is set, and call it right now to push data if possible */
3657 utcp_set_poll_cb(channel->c, channel_poll);
3658 channel_poll(channel->c, len);
3660 pthread_mutex_unlock(&mesh->mutex);
3665 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) {
3666 if(!mesh || !channel) {
3667 meshlink_errno = MESHLINK_EINVAL;
3671 if(!len || fd == -1) {
3672 meshlink_errno = MESHLINK_EINVAL;
3676 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3682 pthread_mutex_lock(&mesh->mutex);
3684 /* Append the AIO buffer descriptor to the end of the chain */
3685 meshlink_aio_buffer_t **p = &channel->aio_send;
3693 /* Ensure the poll callback is set, and call it right now to push data if possible */
3694 utcp_set_poll_cb(channel->c, channel_poll);
3695 channel_poll(channel->c, len);
3697 pthread_mutex_unlock(&mesh->mutex);
3702 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) {
3703 if(!mesh || !channel) {
3704 meshlink_errno = MESHLINK_EINVAL;
3709 meshlink_errno = MESHLINK_EINVAL;
3713 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3716 aio->cb.buffer = cb;
3719 pthread_mutex_lock(&mesh->mutex);
3721 /* Append the AIO buffer descriptor to the end of the chain */
3722 meshlink_aio_buffer_t **p = &channel->aio_receive;
3730 pthread_mutex_unlock(&mesh->mutex);
3735 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) {
3736 if(!mesh || !channel) {
3737 meshlink_errno = MESHLINK_EINVAL;
3741 if(!len || fd == -1) {
3742 meshlink_errno = MESHLINK_EINVAL;
3746 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3752 pthread_mutex_lock(&mesh->mutex);
3754 /* Append the AIO buffer descriptor to the end of the chain */
3755 meshlink_aio_buffer_t **p = &channel->aio_receive;
3763 pthread_mutex_unlock(&mesh->mutex);
3768 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3769 if(!mesh || !channel) {
3770 meshlink_errno = MESHLINK_EINVAL;
3774 return channel->c->flags;
3777 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3778 if(!mesh || !channel) {
3779 meshlink_errno = MESHLINK_EINVAL;
3783 return utcp_get_sendq(channel->c);
3786 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3787 if(!mesh || !channel) {
3788 meshlink_errno = MESHLINK_EINVAL;
3792 return utcp_get_recvq(channel->c);
3795 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3796 if(!mesh || !node) {
3797 meshlink_errno = MESHLINK_EINVAL;
3801 node_t *n = (node_t *)node;
3803 pthread_mutex_lock(&mesh->mutex);
3806 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3809 utcp_set_user_timeout(n->utcp, timeout);
3811 pthread_mutex_unlock(&mesh->mutex);
3814 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3815 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3816 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3819 if(mesh->node_status_cb) {
3820 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3823 if(mesh->node_pmtu_cb) {
3824 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3828 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3829 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3830 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3834 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3835 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3839 n->status.duplicate = true;
3840 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3843 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3847 meshlink_errno = MESHLINK_EINVAL;
3851 pthread_mutex_lock(&mesh->mutex);
3853 if(mesh->discovery == enable) {
3857 if(mesh->threadstarted) {
3859 discovery_start(mesh);
3861 discovery_stop(mesh);
3865 mesh->discovery = enable;
3868 pthread_mutex_unlock(&mesh->mutex);
3872 meshlink_errno = MESHLINK_ENOTSUP;
3876 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3877 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3878 meshlink_errno = EINVAL;
3882 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3883 meshlink_errno = EINVAL;
3887 pthread_mutex_lock(&mesh->mutex);
3888 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3889 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3890 pthread_mutex_unlock(&mesh->mutex);
3893 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3894 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3895 meshlink_errno = EINVAL;
3899 if(fast_retry_period < 0) {
3900 meshlink_errno = EINVAL;
3904 pthread_mutex_lock(&mesh->mutex);
3905 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3906 pthread_mutex_unlock(&mesh->mutex);
3909 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3912 if(!mesh->connections || !mesh->loop.running) {
3919 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3920 // We should only call the callback function if we are in the background thread.
3921 if(!mesh->error_cb) {
3925 if(!mesh->threadstarted) {
3929 if(mesh->thread == pthread_self()) {
3930 mesh->error_cb(mesh, meshlink_errno);
3935 static void __attribute__((constructor)) meshlink_init(void) {
3939 static void __attribute__((destructor)) meshlink_exit(void) {