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 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
293 // Determine address of the local interface used for outgoing connections.
294 char localaddr[NI_MAXHOST];
295 bool success = false;
297 if(family == AF_INET) {
298 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
299 } else if(family == AF_INET6) {
300 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
304 meshlink_errno = MESHLINK_ENETWORK;
308 return xstrdup(localaddr);
311 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
312 for(int i = 0; i < n; i++) {
317 // Ignore duplicate hostnames
320 for(int j = 0; j < i; j++) {
325 if(strcmp(host[i], host[j])) {
329 if(strcmp(port[i], port[j])) {
337 if(found || !is_valid_hostname(host[i])) {
347 // This gets the hostname part for use in invitation URLs
348 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
349 char *hostname[4] = {NULL};
350 char *port[4] = {NULL};
351 char *hostport = NULL;
353 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
354 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
357 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
358 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
361 // Add local addresses if requested
362 if(flags & MESHLINK_INVITE_LOCAL) {
363 if(flags & MESHLINK_INVITE_IPV4) {
364 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
367 if(flags & MESHLINK_INVITE_IPV6) {
368 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
372 // Add public/canonical addresses if requested
373 if(flags & MESHLINK_INVITE_PUBLIC) {
374 // Try the CanonicalAddress first
375 get_canonical_address(mesh->self, &hostname[2], &port[2]);
378 if(flags & MESHLINK_INVITE_IPV4) {
379 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
382 if(flags & MESHLINK_INVITE_IPV6) {
383 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
388 for(int i = 0; i < 4; i++) {
389 // Ensure we always have a port number
390 if(hostname[i] && !port[i]) {
391 port[i] = xstrdup(mesh->myport);
395 remove_duplicate_hostnames(hostname, port, 4);
397 // Resolve the hostnames
398 for(int i = 0; i < 4; i++) {
403 // Convert what we have to a sockaddr
404 struct addrinfo *ai_in, *ai_out;
405 struct addrinfo hint = {
406 .ai_family = AF_UNSPEC,
407 .ai_flags = AI_NUMERICSERV,
408 .ai_socktype = SOCK_STREAM,
410 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
416 // Remember the address
417 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)ai_in->ai_addr);
419 if(flags & MESHLINK_INVITE_NUMERIC) {
420 // We don't need to do any further conversion
425 // Convert it to a hostname
426 char resolved_host[NI_MAXHOST];
427 char resolved_port[NI_MAXSERV];
428 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
430 if(err || !is_valid_hostname(resolved_host)) {
435 // Convert the hostname back to a sockaddr
436 hint.ai_family = ai_in->ai_family;
437 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
444 // Check if it's still the same sockaddr
445 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
447 freeaddrinfo(ai_out);
451 // Yes: replace the hostname with the resolved one
453 hostname[i] = xstrdup(resolved_host);
456 freeaddrinfo(ai_out);
459 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
460 remove_duplicate_hostnames(hostname, port, 4);
462 // Concatenate all unique address to the hostport string
463 for(int i = 0; i < 4; i++) {
468 // Append the address to the hostport string
470 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
472 hostport = newhostport;
481 static bool try_bind(int port) {
482 struct addrinfo *ai = NULL;
483 struct addrinfo hint = {
484 .ai_flags = AI_PASSIVE,
485 .ai_family = AF_UNSPEC,
486 .ai_socktype = SOCK_STREAM,
487 .ai_protocol = IPPROTO_TCP,
491 snprintf(portstr, sizeof(portstr), "%d", port);
493 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
498 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
499 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
506 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
519 static int check_port(meshlink_handle_t *mesh) {
520 for(int i = 0; i < 1000; i++) {
521 int port = 0x1000 + prng(mesh, 0x8000);
525 xasprintf(&mesh->myport, "%d", port);
530 meshlink_errno = MESHLINK_ENETWORK;
531 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
535 static bool write_main_config_files(meshlink_handle_t *mesh) {
536 if(!mesh->confbase) {
542 /* Write the main config file */
543 packmsg_output_t out = {buf, sizeof buf};
545 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
546 packmsg_add_str(&out, mesh->name);
547 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
548 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
549 packmsg_add_uint16(&out, atoi(mesh->myport));
551 if(!packmsg_output_ok(&out)) {
555 config_t config = {buf, packmsg_output_size(&out, buf)};
557 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
561 /* Write our own host config file */
562 if(!node_write_config(mesh, mesh->self)) {
569 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
570 packmsg_input_t in = {buf, len};
571 uint32_t version = packmsg_get_uint32(&in);
573 if(version != MESHLINK_INVITATION_VERSION) {
574 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
578 char *name = packmsg_get_str_dup(&in);
579 packmsg_skip_element(&in); /* submesh */
580 dev_class_t devclass = packmsg_get_int32(&in);
581 uint32_t count = packmsg_get_array(&in);
584 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
588 if(!check_id(name)) {
589 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
595 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
601 free(mesh->self->name);
603 mesh->self->name = xstrdup(name);
604 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
606 // Initialize configuration directory
607 if(!config_init(mesh, "current")) {
611 if(!write_main_config_files(mesh)) {
615 // Write host config files
616 for(uint32_t i = 0; i < count; i++) {
618 uint32_t len = packmsg_get_bin_raw(&in, &data);
621 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
625 packmsg_input_t in2 = {data, len};
626 uint32_t version = packmsg_get_uint32(&in2);
627 char *name = packmsg_get_str_dup(&in2);
629 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
631 packmsg_input_invalidate(&in);
635 if(!check_id(name)) {
640 if(!strcmp(name, mesh->name)) {
641 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
643 meshlink_errno = MESHLINK_EPEER;
647 node_t *n = new_node();
650 config_t config = {data, len};
652 if(!node_read_from_config(mesh, n, &config)) {
654 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
655 meshlink_errno = MESHLINK_EPEER;
660 /* The first host config file is of the inviter itself;
661 * remember the address we are currently using for the invitation connection.
664 socklen_t salen = sizeof(sa);
666 if(getpeername(mesh->sock, &sa.sa, &salen) == 0) {
667 node_add_recent_address(mesh, n, &sa);
671 /* Clear the reachability times, since we ourself have never seen these nodes yet */
672 n->last_reachable = 0;
673 n->last_unreachable = 0;
675 if(!node_write_config(mesh, n)) {
683 /* Ensure the configuration directory metadata is on disk */
684 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
688 sptps_send_record(&mesh->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
690 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
695 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
697 meshlink_handle_t *mesh = handle;
698 const char *ptr = data;
701 int result = send(mesh->sock, ptr, len, 0);
703 if(result == -1 && errno == EINTR) {
705 } else if(result <= 0) {
716 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
717 meshlink_handle_t *mesh = handle;
720 case SPTPS_HANDSHAKE:
721 return sptps_send_record(&mesh->sptps, 0, mesh->cookie, sizeof(mesh)->cookie);
724 return finalize_join(mesh, msg, len);
727 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
728 shutdown(mesh->sock, SHUT_RDWR);
729 mesh->success = true;
739 static bool recvline(meshlink_handle_t *mesh, size_t len) {
740 char *newline = NULL;
746 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
747 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
749 if(result == -1 && errno == EINTR) {
751 } else if(result <= 0) {
755 mesh->blen += result;
758 if((size_t)(newline - mesh->buffer) >= len) {
762 len = newline - mesh->buffer;
764 memcpy(mesh->line, mesh->buffer, len);
766 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
767 mesh->blen -= len + 1;
772 static bool sendline(int fd, char *format, ...) {
778 va_start(ap, format);
779 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
782 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
790 int result = send(fd, p, blen, MSG_NOSIGNAL);
792 if(result == -1 && errno == EINTR) {
794 } else if(result <= 0) {
805 static const char *errstr[] = {
806 [MESHLINK_OK] = "No error",
807 [MESHLINK_EINVAL] = "Invalid argument",
808 [MESHLINK_ENOMEM] = "Out of memory",
809 [MESHLINK_ENOENT] = "No such node",
810 [MESHLINK_EEXIST] = "Node already exists",
811 [MESHLINK_EINTERNAL] = "Internal error",
812 [MESHLINK_ERESOLV] = "Could not resolve hostname",
813 [MESHLINK_ESTORAGE] = "Storage error",
814 [MESHLINK_ENETWORK] = "Network error",
815 [MESHLINK_EPEER] = "Error communicating with peer",
816 [MESHLINK_ENOTSUP] = "Operation not supported",
817 [MESHLINK_EBUSY] = "MeshLink instance already in use",
818 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
821 const char *meshlink_strerror(meshlink_errno_t err) {
822 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
823 return "Invalid error code";
829 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
830 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
832 mesh->private_key = ecdsa_generate();
833 mesh->invitation_key = ecdsa_generate();
835 if(!mesh->private_key || !mesh->invitation_key) {
836 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
837 meshlink_errno = MESHLINK_EINTERNAL;
841 logger(mesh, MESHLINK_DEBUG, "Done.\n");
846 static struct timeval idle(event_loop_t *loop, void *data) {
848 meshlink_handle_t *mesh = data;
849 struct timeval t, tmin = {3600, 0};
851 for splay_each(node_t, n, mesh->nodes) {
856 t = utcp_timeout(n->utcp);
858 if(timercmp(&t, &tmin, <)) {
866 // Get our local address(es) by simulating connecting to an Internet host.
867 static void add_local_addresses(meshlink_handle_t *mesh) {
869 sa.storage.ss_family = AF_UNKNOWN;
870 socklen_t salen = sizeof(sa);
874 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
875 sa.in.sin_port = ntohs(atoi(mesh->myport));
876 node_add_recent_address(mesh, mesh->self, &sa);
883 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
884 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
885 node_add_recent_address(mesh, mesh->self, &sa);
889 static bool meshlink_setup(meshlink_handle_t *mesh) {
890 if(!config_destroy(mesh->confbase, "new")) {
891 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
892 meshlink_errno = MESHLINK_ESTORAGE;
896 if(!config_destroy(mesh->confbase, "old")) {
897 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
898 meshlink_errno = MESHLINK_ESTORAGE;
902 if(!config_init(mesh, "current")) {
903 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
904 meshlink_errno = MESHLINK_ESTORAGE;
908 if(!ecdsa_keygen(mesh)) {
909 meshlink_errno = MESHLINK_EINTERNAL;
913 if(check_port(mesh) == 0) {
914 meshlink_errno = MESHLINK_ENETWORK;
918 /* Create a node for ourself */
920 mesh->self = new_node();
921 mesh->self->name = xstrdup(mesh->name);
922 mesh->self->devclass = mesh->devclass;
923 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
924 mesh->self->session_id = mesh->session_id;
926 if(!write_main_config_files(mesh)) {
927 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
928 meshlink_errno = MESHLINK_ESTORAGE;
932 /* Ensure the configuration directory metadata is on disk */
933 if(!config_sync(mesh, "current")) {
940 static bool meshlink_read_config(meshlink_handle_t *mesh) {
943 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
944 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
948 packmsg_input_t in = {config.buf, config.len};
949 const void *private_key;
950 const void *invitation_key;
952 uint32_t version = packmsg_get_uint32(&in);
953 char *name = packmsg_get_str_dup(&in);
954 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
955 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
956 uint16_t myport = packmsg_get_uint16(&in);
958 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
959 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
961 config_free(&config);
968 if(mesh->name && strcmp(mesh->name, name)) {
969 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
970 meshlink_errno = MESHLINK_ESTORAGE;
972 config_free(&config);
980 xasprintf(&mesh->myport, "%u", myport);
981 mesh->private_key = ecdsa_set_private_key(private_key);
982 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
983 config_free(&config);
985 /* Create a node for ourself and read our host configuration file */
987 mesh->self = new_node();
988 mesh->self->name = xstrdup(name);
989 mesh->self->devclass = mesh->devclass;
990 mesh->self->session_id = mesh->session_id;
992 if(!node_read_public_key(mesh, mesh->self)) {
993 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
994 meshlink_errno = MESHLINK_ESTORAGE;
995 free_node(mesh->self);
1004 static void *setup_network_in_netns_thread(void *arg) {
1005 meshlink_handle_t *mesh = arg;
1007 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1011 bool success = setup_network(mesh);
1012 add_local_addresses(mesh);
1013 return success ? arg : NULL;
1015 #endif // HAVE_SETNS
1017 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1018 if(!confbase || !*confbase) {
1019 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1020 meshlink_errno = MESHLINK_EINVAL;
1024 if(!appname || !*appname) {
1025 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1026 meshlink_errno = MESHLINK_EINVAL;
1030 if(strchr(appname, ' ')) {
1031 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1032 meshlink_errno = MESHLINK_EINVAL;
1036 if(!name || !*name) {
1037 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1038 meshlink_errno = MESHLINK_EINVAL;
1042 if(!check_id(name)) {
1043 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1044 meshlink_errno = MESHLINK_EINVAL;
1048 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1049 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1050 meshlink_errno = MESHLINK_EINVAL;
1054 meshlink_open_params_t *params = xzalloc(sizeof * params);
1056 params->confbase = xstrdup(confbase);
1057 params->name = xstrdup(name);
1058 params->appname = xstrdup(appname);
1059 params->devclass = devclass;
1065 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1067 meshlink_errno = MESHLINK_EINVAL;
1071 params->netns = netns;
1076 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1078 meshlink_errno = MESHLINK_EINVAL;
1082 if((!key && keylen) || (key && !keylen)) {
1083 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1084 meshlink_errno = MESHLINK_EINVAL;
1089 params->keylen = keylen;
1094 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1095 if(!mesh || !new_key || !new_keylen) {
1096 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1097 meshlink_errno = MESHLINK_EINVAL;
1101 pthread_mutex_lock(&mesh->mutex);
1103 // Create hash for the new key
1104 void *new_config_key;
1105 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1107 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1108 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1109 meshlink_errno = MESHLINK_EINTERNAL;
1110 pthread_mutex_unlock(&mesh->mutex);
1114 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1116 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1117 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1118 meshlink_errno = MESHLINK_ESTORAGE;
1119 pthread_mutex_unlock(&mesh->mutex);
1123 devtool_keyrotate_probe(1);
1125 // Rename confbase/current/ to confbase/old
1127 if(!config_rename(mesh, "current", "old")) {
1128 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1129 meshlink_errno = MESHLINK_ESTORAGE;
1130 pthread_mutex_unlock(&mesh->mutex);
1134 devtool_keyrotate_probe(2);
1136 // Rename confbase/new/ to confbase/current
1138 if(!config_rename(mesh, "new", "current")) {
1139 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1140 meshlink_errno = MESHLINK_ESTORAGE;
1141 pthread_mutex_unlock(&mesh->mutex);
1145 devtool_keyrotate_probe(3);
1147 // Cleanup the "old" confbase sub-directory
1149 if(!config_destroy(mesh->confbase, "old")) {
1150 pthread_mutex_unlock(&mesh->mutex);
1154 // Change the mesh handle key with new key
1156 free(mesh->config_key);
1157 mesh->config_key = new_config_key;
1159 pthread_mutex_unlock(&mesh->mutex);
1164 void meshlink_open_params_free(meshlink_open_params_t *params) {
1166 meshlink_errno = MESHLINK_EINVAL;
1170 free(params->confbase);
1172 free(params->appname);
1177 /// Device class traits
1178 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1179 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1180 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1181 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1182 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1185 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1186 if(!confbase || !*confbase) {
1187 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1188 meshlink_errno = MESHLINK_EINVAL;
1192 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1193 meshlink_open_params_t params;
1194 memset(¶ms, 0, sizeof(params));
1196 params.confbase = (char *)confbase;
1197 params.name = (char *)name;
1198 params.appname = (char *)appname;
1199 params.devclass = devclass;
1202 return meshlink_open_ex(¶ms);
1205 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) {
1206 if(!confbase || !*confbase) {
1207 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1208 meshlink_errno = MESHLINK_EINVAL;
1212 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1213 meshlink_open_params_t params;
1214 memset(¶ms, 0, sizeof(params));
1216 params.confbase = (char *)confbase;
1217 params.name = (char *)name;
1218 params.appname = (char *)appname;
1219 params.devclass = devclass;
1222 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1226 return meshlink_open_ex(¶ms);
1229 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1230 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1231 meshlink_open_params_t params;
1232 memset(¶ms, 0, sizeof(params));
1234 params.name = (char *)name;
1235 params.appname = (char *)appname;
1236 params.devclass = devclass;
1239 return meshlink_open_ex(¶ms);
1242 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1243 // Validate arguments provided by the application
1244 bool usingname = false;
1246 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1248 if(!params->appname || !*params->appname) {
1249 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1250 meshlink_errno = MESHLINK_EINVAL;
1254 if(strchr(params->appname, ' ')) {
1255 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1256 meshlink_errno = MESHLINK_EINVAL;
1260 if(!params->name || !*params->name) {
1261 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1263 } else { //check name only if there is a name != NULL
1265 if(!check_id(params->name)) {
1266 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1267 meshlink_errno = MESHLINK_EINVAL;
1274 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1275 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1276 meshlink_errno = MESHLINK_EINVAL;
1280 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1281 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1282 meshlink_errno = MESHLINK_EINVAL;
1286 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1288 if(params->confbase) {
1289 mesh->confbase = xstrdup(params->confbase);
1292 mesh->appname = xstrdup(params->appname);
1293 mesh->devclass = params->devclass;
1294 mesh->discovery = true;
1295 mesh->invitation_timeout = 604800; // 1 week
1296 mesh->netns = params->netns;
1297 mesh->submeshes = NULL;
1298 mesh->log_cb = global_log_cb;
1299 mesh->log_level = global_log_level;
1301 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1304 randomize(&mesh->session_id, sizeof(mesh->session_id));
1305 } while(mesh->session_id == 0);
1307 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1310 mesh->name = xstrdup(params->name);
1315 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1317 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1318 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1319 meshlink_close(mesh);
1320 meshlink_errno = MESHLINK_EINTERNAL;
1326 pthread_mutexattr_t attr;
1327 pthread_mutexattr_init(&attr);
1328 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1329 pthread_mutex_init(&mesh->mutex, &attr);
1331 mesh->threadstarted = false;
1332 event_loop_init(&mesh->loop);
1333 mesh->loop.data = mesh;
1335 meshlink_queue_init(&mesh->outpacketqueue);
1337 // Atomically lock the configuration directory.
1338 if(!main_config_lock(mesh)) {
1339 meshlink_close(mesh);
1343 // If no configuration exists yet, create it.
1345 if(!meshlink_confbase_exists(mesh)) {
1346 if(!meshlink_setup(mesh)) {
1347 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1348 meshlink_close(mesh);
1352 if(!meshlink_read_config(mesh)) {
1353 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1354 meshlink_close(mesh);
1360 struct WSAData wsa_state;
1361 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1364 // Setup up everything
1365 // TODO: we should not open listening sockets yet
1367 bool success = false;
1369 if(mesh->netns != -1) {
1373 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1374 void *retval = NULL;
1375 success = pthread_join(thr, &retval) == 0 && retval;
1379 meshlink_errno = MESHLINK_EINTERNAL;
1382 #endif // HAVE_SETNS
1384 success = setup_network(mesh);
1385 add_local_addresses(mesh);
1389 meshlink_close(mesh);
1390 meshlink_errno = MESHLINK_ENETWORK;
1394 add_local_addresses(mesh);
1396 if(!node_write_config(mesh, mesh->self)) {
1397 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1401 idle_set(&mesh->loop, idle, mesh);
1403 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1407 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1408 meshlink_submesh_t *s = NULL;
1411 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1412 meshlink_errno = MESHLINK_EINVAL;
1416 if(!submesh || !*submesh) {
1417 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1418 meshlink_errno = MESHLINK_EINVAL;
1423 pthread_mutex_lock(&mesh->mutex);
1425 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1427 pthread_mutex_unlock(&mesh->mutex);
1432 static void *meshlink_main_loop(void *arg) {
1433 meshlink_handle_t *mesh = arg;
1435 if(mesh->netns != -1) {
1438 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1439 pthread_cond_signal(&mesh->cond);
1444 pthread_cond_signal(&mesh->cond);
1446 #endif // HAVE_SETNS
1451 if(mesh->discovery) {
1452 discovery_start(mesh);
1457 pthread_mutex_lock(&mesh->mutex);
1459 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1460 pthread_cond_broadcast(&mesh->cond);
1462 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1464 pthread_mutex_unlock(&mesh->mutex);
1469 if(mesh->discovery) {
1470 discovery_stop(mesh);
1478 bool meshlink_start(meshlink_handle_t *mesh) {
1480 assert(mesh->private_key);
1483 meshlink_errno = MESHLINK_EINVAL;
1487 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1489 pthread_mutex_lock(&mesh->mutex);
1491 assert(mesh->self->ecdsa);
1492 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1494 if(mesh->threadstarted) {
1495 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1496 pthread_mutex_unlock(&mesh->mutex);
1500 if(mesh->listen_socket[0].tcp.fd < 0) {
1501 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1502 meshlink_errno = MESHLINK_ENETWORK;
1506 mesh->thedatalen = 0;
1508 // TODO: open listening sockets first
1510 //Check that a valid name is set
1512 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1513 meshlink_errno = MESHLINK_EINVAL;
1514 pthread_mutex_unlock(&mesh->mutex);
1518 init_outgoings(mesh);
1520 // Start the main thread
1522 event_loop_start(&mesh->loop);
1524 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1525 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1526 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1527 meshlink_errno = MESHLINK_EINTERNAL;
1528 event_loop_stop(&mesh->loop);
1529 pthread_mutex_unlock(&mesh->mutex);
1533 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1534 mesh->threadstarted = true;
1536 // Ensure we are considered reachable
1539 pthread_mutex_unlock(&mesh->mutex);
1543 void meshlink_stop(meshlink_handle_t *mesh) {
1545 meshlink_errno = MESHLINK_EINVAL;
1549 pthread_mutex_lock(&mesh->mutex);
1550 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1552 // Shut down the main thread
1553 event_loop_stop(&mesh->loop);
1555 // Send ourselves a UDP packet to kick the event loop
1556 for(int i = 0; i < mesh->listen_sockets; i++) {
1558 socklen_t salen = sizeof(sa);
1560 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1561 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1565 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1566 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1570 if(mesh->threadstarted) {
1571 // Wait for the main thread to finish
1572 pthread_mutex_unlock(&mesh->mutex);
1573 pthread_join(mesh->thread, NULL);
1574 pthread_mutex_lock(&mesh->mutex);
1576 mesh->threadstarted = false;
1579 // Close all metaconnections
1580 if(mesh->connections) {
1581 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1583 connection_t *c = node->data;
1585 terminate_connection(mesh, c, false);
1589 exit_outgoings(mesh);
1591 // Ensure we are considered unreachable
1596 // Try to write out any changed node config files, ignore errors at this point.
1598 for splay_each(node_t, n, mesh->nodes) {
1599 if(n->status.dirty) {
1600 n->status.dirty = !node_write_config(mesh, n);
1605 pthread_mutex_unlock(&mesh->mutex);
1608 void meshlink_close(meshlink_handle_t *mesh) {
1610 meshlink_errno = MESHLINK_EINVAL;
1614 // stop can be called even if mesh has not been started
1615 meshlink_stop(mesh);
1617 // lock is not released after this
1618 pthread_mutex_lock(&mesh->mutex);
1620 // Close and free all resources used.
1622 close_network_connections(mesh);
1624 logger(mesh, MESHLINK_INFO, "Terminating");
1626 event_loop_exit(&mesh->loop);
1630 if(mesh->confbase) {
1636 ecdsa_free(mesh->invitation_key);
1638 if(mesh->netns != -1) {
1642 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1646 meshlink_queue_exit(&mesh->outpacketqueue);
1649 free(mesh->appname);
1650 free(mesh->confbase);
1651 free(mesh->config_key);
1652 ecdsa_free(mesh->private_key);
1654 main_config_unlock(mesh);
1656 pthread_mutex_unlock(&mesh->mutex);
1657 pthread_mutex_destroy(&mesh->mutex);
1659 memset(mesh, 0, sizeof(*mesh));
1664 bool meshlink_destroy(const char *confbase) {
1666 meshlink_errno = MESHLINK_EINVAL;
1670 /* Exit early if the confbase directory itself doesn't exist */
1671 if(access(confbase, F_OK) && errno == ENOENT) {
1675 /* Take the lock the same way meshlink_open() would. */
1676 char lockfilename[PATH_MAX];
1677 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1679 FILE *lockfile = fopen(lockfilename, "w+");
1682 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1683 meshlink_errno = MESHLINK_ESTORAGE;
1688 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1692 // TODO: use _locking()?
1695 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1696 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1698 meshlink_errno = MESHLINK_EBUSY;
1704 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1705 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1709 if(unlink(lockfilename)) {
1710 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1712 meshlink_errno = MESHLINK_ESTORAGE;
1718 if(!sync_path(confbase)) {
1719 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1720 meshlink_errno = MESHLINK_ESTORAGE;
1727 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1729 meshlink_errno = MESHLINK_EINVAL;
1733 pthread_mutex_lock(&mesh->mutex);
1734 mesh->receive_cb = cb;
1735 pthread_mutex_unlock(&mesh->mutex);
1738 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1740 meshlink_errno = MESHLINK_EINVAL;
1744 pthread_mutex_lock(&mesh->mutex);
1745 mesh->connection_try_cb = cb;
1746 pthread_mutex_unlock(&mesh->mutex);
1749 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1751 meshlink_errno = MESHLINK_EINVAL;
1755 pthread_mutex_lock(&mesh->mutex);
1756 mesh->node_status_cb = cb;
1757 pthread_mutex_unlock(&mesh->mutex);
1760 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1762 meshlink_errno = MESHLINK_EINVAL;
1766 pthread_mutex_lock(&mesh->mutex);
1767 mesh->node_pmtu_cb = cb;
1768 pthread_mutex_unlock(&mesh->mutex);
1771 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1773 meshlink_errno = MESHLINK_EINVAL;
1777 pthread_mutex_lock(&mesh->mutex);
1778 mesh->node_duplicate_cb = cb;
1779 pthread_mutex_unlock(&mesh->mutex);
1782 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1784 pthread_mutex_lock(&mesh->mutex);
1786 mesh->log_level = cb ? level : 0;
1787 pthread_mutex_unlock(&mesh->mutex);
1790 global_log_level = cb ? level : 0;
1794 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1796 meshlink_errno = MESHLINK_EINVAL;
1800 pthread_mutex_lock(&mesh->mutex);
1801 mesh->error_cb = cb;
1802 pthread_mutex_unlock(&mesh->mutex);
1805 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1806 meshlink_packethdr_t *hdr;
1808 // Validate arguments
1809 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1810 meshlink_errno = MESHLINK_EINVAL;
1819 meshlink_errno = MESHLINK_EINVAL;
1823 node_t *n = (node_t *)destination;
1825 if(n->status.blacklisted) {
1826 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1827 meshlink_errno = MESHLINK_EBLACKLISTED;
1831 // Prepare the packet
1832 vpn_packet_t *packet = malloc(sizeof(*packet));
1835 meshlink_errno = MESHLINK_ENOMEM;
1839 packet->probe = false;
1840 packet->tcp = false;
1841 packet->len = len + sizeof(*hdr);
1843 hdr = (meshlink_packethdr_t *)packet->data;
1844 memset(hdr, 0, sizeof(*hdr));
1845 // leave the last byte as 0 to make sure strings are always
1846 // null-terminated if they are longer than the buffer
1847 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1848 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1850 memcpy(packet->data + sizeof(*hdr), data, len);
1853 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1855 meshlink_errno = MESHLINK_ENOMEM;
1859 // Notify event loop
1860 signal_trigger(&mesh->loop, &mesh->datafromapp);
1865 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1867 meshlink_handle_t *mesh = data;
1868 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1874 mesh->self->in_packets++;
1875 mesh->self->in_bytes += packet->len;
1876 route(mesh, mesh->self, packet);
1881 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1882 if(!mesh || !destination) {
1883 meshlink_errno = MESHLINK_EINVAL;
1887 pthread_mutex_lock(&mesh->mutex);
1889 node_t *n = (node_t *)destination;
1891 if(!n->status.reachable) {
1892 pthread_mutex_unlock(&mesh->mutex);
1895 } else if(n->mtuprobes > 30 && n->minmtu) {
1896 pthread_mutex_unlock(&mesh->mutex);
1899 pthread_mutex_unlock(&mesh->mutex);
1904 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1905 if(!mesh || !node) {
1906 meshlink_errno = MESHLINK_EINVAL;
1910 pthread_mutex_lock(&mesh->mutex);
1912 node_t *n = (node_t *)node;
1914 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1915 meshlink_errno = MESHLINK_EINTERNAL;
1916 pthread_mutex_unlock(&mesh->mutex);
1920 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1923 meshlink_errno = MESHLINK_EINTERNAL;
1926 pthread_mutex_unlock(&mesh->mutex);
1930 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1932 meshlink_errno = MESHLINK_EINVAL;
1936 return (meshlink_node_t *)mesh->self;
1939 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1940 if(!mesh || !name) {
1941 meshlink_errno = MESHLINK_EINVAL;
1947 pthread_mutex_lock(&mesh->mutex);
1948 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1949 pthread_mutex_unlock(&mesh->mutex);
1952 meshlink_errno = MESHLINK_ENOENT;
1955 return (meshlink_node_t *)n;
1958 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1959 if(!mesh || !name) {
1960 meshlink_errno = MESHLINK_EINVAL;
1964 meshlink_submesh_t *submesh = NULL;
1966 pthread_mutex_lock(&mesh->mutex);
1967 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1968 pthread_mutex_unlock(&mesh->mutex);
1971 meshlink_errno = MESHLINK_ENOENT;
1977 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1978 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1979 meshlink_errno = MESHLINK_EINVAL;
1983 meshlink_node_t **result;
1986 pthread_mutex_lock(&mesh->mutex);
1988 *nmemb = mesh->nodes->count;
1989 result = realloc(nodes, *nmemb * sizeof(*nodes));
1992 meshlink_node_t **p = result;
1994 for splay_each(node_t, n, mesh->nodes) {
1995 *p++ = (meshlink_node_t *)n;
2000 meshlink_errno = MESHLINK_ENOMEM;
2003 pthread_mutex_unlock(&mesh->mutex);
2008 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) {
2009 meshlink_node_t **result;
2011 pthread_mutex_lock(&mesh->mutex);
2015 for splay_each(node_t, n, mesh->nodes) {
2016 if(search_node(n, condition)) {
2023 pthread_mutex_unlock(&mesh->mutex);
2027 result = realloc(nodes, *nmemb * sizeof(*nodes));
2030 meshlink_node_t **p = result;
2032 for splay_each(node_t, n, mesh->nodes) {
2033 if(search_node(n, condition)) {
2034 *p++ = (meshlink_node_t *)n;
2040 meshlink_errno = MESHLINK_ENOMEM;
2043 pthread_mutex_unlock(&mesh->mutex);
2048 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2049 dev_class_t *devclass = (dev_class_t *)condition;
2051 if(*devclass == (dev_class_t)node->devclass) {
2058 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2059 if(condition == node->submesh) {
2071 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2072 const struct time_range *range = condition;
2073 time_t start = node->last_reachable;
2074 time_t end = node->last_unreachable;
2084 if(range->end >= range->start) {
2085 return start <= range->end && end >= range->start;
2087 return start > range->start || end < range->end;
2091 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) {
2092 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2093 meshlink_errno = MESHLINK_EINVAL;
2097 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2100 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2101 if(!mesh || !submesh || !nmemb) {
2102 meshlink_errno = MESHLINK_EINVAL;
2106 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2109 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) {
2110 if(!mesh || !nmemb) {
2111 meshlink_errno = MESHLINK_EINVAL;
2115 struct time_range range = {start, end};
2117 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2120 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2121 if(!mesh || !node) {
2122 meshlink_errno = MESHLINK_EINVAL;
2126 dev_class_t devclass;
2128 pthread_mutex_lock(&mesh->mutex);
2130 devclass = ((node_t *)node)->devclass;
2132 pthread_mutex_unlock(&mesh->mutex);
2137 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2138 if(!mesh || !node) {
2139 meshlink_errno = MESHLINK_EINVAL;
2143 node_t *n = (node_t *)node;
2145 meshlink_submesh_t *s;
2147 s = (meshlink_submesh_t *)n->submesh;
2152 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2153 if(!mesh || !node) {
2154 meshlink_errno = MESHLINK_EINVAL;
2158 node_t *n = (node_t *)node;
2161 pthread_mutex_lock(&mesh->mutex);
2162 reachable = n->status.reachable && !n->status.blacklisted;
2164 if(last_reachable) {
2165 *last_reachable = n->last_reachable;
2168 if(last_unreachable) {
2169 *last_unreachable = n->last_unreachable;
2172 pthread_mutex_unlock(&mesh->mutex);
2177 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2178 if(!mesh || !data || !len || !signature || !siglen) {
2179 meshlink_errno = MESHLINK_EINVAL;
2183 if(*siglen < MESHLINK_SIGLEN) {
2184 meshlink_errno = MESHLINK_EINVAL;
2188 pthread_mutex_lock(&mesh->mutex);
2190 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2191 meshlink_errno = MESHLINK_EINTERNAL;
2192 pthread_mutex_unlock(&mesh->mutex);
2196 *siglen = MESHLINK_SIGLEN;
2197 pthread_mutex_unlock(&mesh->mutex);
2201 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2202 if(!mesh || !data || !len || !signature) {
2203 meshlink_errno = MESHLINK_EINVAL;
2207 if(siglen != MESHLINK_SIGLEN) {
2208 meshlink_errno = MESHLINK_EINVAL;
2212 pthread_mutex_lock(&mesh->mutex);
2216 struct node_t *n = (struct node_t *)source;
2218 if(!node_read_public_key(mesh, n)) {
2219 meshlink_errno = MESHLINK_EINTERNAL;
2222 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2225 pthread_mutex_unlock(&mesh->mutex);
2229 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2230 pthread_mutex_lock(&mesh->mutex);
2232 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2235 // TODO: Update invitation key if necessary?
2238 pthread_mutex_unlock(&mesh->mutex);
2240 return mesh->invitation_key;
2243 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2244 if(!mesh || !node || !address) {
2245 meshlink_errno = MESHLINK_EINVAL;
2249 if(!is_valid_hostname(address)) {
2250 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2251 meshlink_errno = MESHLINK_EINVAL;
2255 if(port && !is_valid_port(port)) {
2256 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2257 meshlink_errno = MESHLINK_EINVAL;
2261 char *canonical_address;
2264 xasprintf(&canonical_address, "%s %s", address, port);
2266 canonical_address = xstrdup(address);
2269 pthread_mutex_lock(&mesh->mutex);
2271 node_t *n = (node_t *)node;
2272 free(n->canonical_address);
2273 n->canonical_address = canonical_address;
2275 if(!node_write_config(mesh, n)) {
2276 pthread_mutex_unlock(&mesh->mutex);
2280 pthread_mutex_unlock(&mesh->mutex);
2282 return config_sync(mesh, "current");
2285 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2286 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2289 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2291 meshlink_errno = MESHLINK_EINVAL;
2295 char *address = meshlink_get_external_address(mesh);
2301 bool rval = meshlink_add_address(mesh, address);
2307 int meshlink_get_port(meshlink_handle_t *mesh) {
2309 meshlink_errno = MESHLINK_EINVAL;
2314 meshlink_errno = MESHLINK_EINTERNAL;
2320 pthread_mutex_lock(&mesh->mutex);
2321 port = atoi(mesh->myport);
2322 pthread_mutex_unlock(&mesh->mutex);
2327 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2328 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2329 meshlink_errno = MESHLINK_EINVAL;
2333 if(mesh->myport && port == atoi(mesh->myport)) {
2337 if(!try_bind(port)) {
2338 meshlink_errno = MESHLINK_ENETWORK;
2342 devtool_trybind_probe();
2346 pthread_mutex_lock(&mesh->mutex);
2348 if(mesh->threadstarted) {
2349 meshlink_errno = MESHLINK_EINVAL;
2354 xasprintf(&mesh->myport, "%d", port);
2356 /* Close down the network. This also deletes mesh->self. */
2357 close_network_connections(mesh);
2359 /* Recreate mesh->self. */
2360 mesh->self = new_node();
2361 mesh->self->name = xstrdup(mesh->name);
2362 mesh->self->devclass = mesh->devclass;
2363 mesh->self->session_id = mesh->session_id;
2364 xasprintf(&mesh->myport, "%d", port);
2366 if(!node_read_public_key(mesh, mesh->self)) {
2367 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2368 meshlink_errno = MESHLINK_ESTORAGE;
2369 free_node(mesh->self);
2372 } else if(!setup_network(mesh)) {
2373 meshlink_errno = MESHLINK_ENETWORK;
2377 /* Rebuild our own list of recent addresses */
2378 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2379 add_local_addresses(mesh);
2381 /* Write meshlink.conf with the updated port number */
2382 write_main_config_files(mesh);
2384 rval = config_sync(mesh, "current");
2387 pthread_mutex_unlock(&mesh->mutex);
2389 return rval && meshlink_get_port(mesh) == port;
2392 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2393 mesh->invitation_timeout = timeout;
2396 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2397 meshlink_submesh_t *s = NULL;
2400 meshlink_errno = MESHLINK_EINVAL;
2405 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2408 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2409 meshlink_errno = MESHLINK_EINVAL;
2413 s = (meshlink_submesh_t *)mesh->self->submesh;
2416 pthread_mutex_lock(&mesh->mutex);
2418 // Check validity of the new node's name
2419 if(!check_id(name)) {
2420 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2421 meshlink_errno = MESHLINK_EINVAL;
2422 pthread_mutex_unlock(&mesh->mutex);
2426 // Ensure no host configuration file with that name exists
2427 if(config_exists(mesh, "current", name)) {
2428 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2429 meshlink_errno = MESHLINK_EEXIST;
2430 pthread_mutex_unlock(&mesh->mutex);
2434 // Ensure no other nodes know about this name
2435 if(lookup_node(mesh, name)) {
2436 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2437 meshlink_errno = MESHLINK_EEXIST;
2438 pthread_mutex_unlock(&mesh->mutex);
2442 // Get the local address
2443 char *address = get_my_hostname(mesh, flags);
2446 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2447 meshlink_errno = MESHLINK_ERESOLV;
2448 pthread_mutex_unlock(&mesh->mutex);
2452 if(!refresh_invitation_key(mesh)) {
2453 meshlink_errno = MESHLINK_EINTERNAL;
2454 pthread_mutex_unlock(&mesh->mutex);
2458 // If we changed our own host config file, write it out now
2459 if(mesh->self->status.dirty) {
2460 if(!node_write_config(mesh, mesh->self)) {
2461 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2462 pthread_mutex_unlock(&mesh->mutex);
2469 // Create a hash of the key.
2470 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2471 sha512(fingerprint, strlen(fingerprint), hash);
2472 b64encode_urlsafe(hash, hash, 18);
2474 // Create a random cookie for this invitation.
2476 randomize(cookie, 18);
2478 // Create a filename that doesn't reveal the cookie itself
2479 char buf[18 + strlen(fingerprint)];
2480 char cookiehash[64];
2481 memcpy(buf, cookie, 18);
2482 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2483 sha512(buf, sizeof(buf), cookiehash);
2484 b64encode_urlsafe(cookiehash, cookiehash, 18);
2486 b64encode_urlsafe(cookie, cookie, 18);
2490 /* Construct the invitation file */
2491 uint8_t outbuf[4096];
2492 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2494 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2495 packmsg_add_str(&inv, name);
2496 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2497 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2499 /* TODO: Add several host config files to bootstrap connections.
2500 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2501 * and are not blacklisted.
2503 config_t configs[5];
2504 memset(configs, 0, sizeof(configs));
2507 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2511 /* Append host config files to the invitation file */
2512 packmsg_add_array(&inv, count);
2514 for(int i = 0; i < count; i++) {
2515 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2516 config_free(&configs[i]);
2519 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2521 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2522 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2523 meshlink_errno = MESHLINK_ESTORAGE;
2524 pthread_mutex_unlock(&mesh->mutex);
2528 // Create an URL from the local address, key hash and cookie
2530 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2533 pthread_mutex_unlock(&mesh->mutex);
2537 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2538 return meshlink_invite_ex(mesh, submesh, name, 0);
2541 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2542 if(!mesh || !invitation) {
2543 meshlink_errno = MESHLINK_EINVAL;
2547 pthread_mutex_lock(&mesh->mutex);
2549 //Before doing meshlink_join make sure we are not connected to another mesh
2550 if(mesh->threadstarted) {
2551 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2552 meshlink_errno = MESHLINK_EINVAL;
2553 pthread_mutex_unlock(&mesh->mutex);
2557 // 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.
2558 if(mesh->nodes->count > 1) {
2559 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2560 meshlink_errno = MESHLINK_EINVAL;
2561 pthread_mutex_unlock(&mesh->mutex);
2565 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2566 char copy[strlen(invitation) + 1];
2567 strcpy(copy, invitation);
2569 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2571 char *slash = strchr(copy, '/');
2579 if(strlen(slash) != 48) {
2583 char *address = copy;
2586 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2590 // Generate a throw-away key for the invitation.
2591 ecdsa_t *key = ecdsa_generate();
2594 meshlink_errno = MESHLINK_EINTERNAL;
2595 pthread_mutex_unlock(&mesh->mutex);
2599 char *b64key = ecdsa_get_base64_public_key(key);
2603 while(address && *address) {
2604 // We allow commas in the address part to support multiple addresses in one invitation URL.
2605 comma = strchr(address, ',');
2611 // Split of the port
2612 port = strrchr(address, ':');
2620 // IPv6 address are enclosed in brackets, per RFC 3986
2621 if(*address == '[') {
2623 char *bracket = strchr(address, ']');
2636 // Connect to the meshlink daemon mentioned in the URL.
2637 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2640 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2641 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2643 if(mesh->sock == -1) {
2644 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2645 meshlink_errno = MESHLINK_ENETWORK;
2649 set_timeout(mesh->sock, 5000);
2651 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2652 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2653 meshlink_errno = MESHLINK_ENETWORK;
2654 closesocket(mesh->sock);
2662 meshlink_errno = MESHLINK_ERESOLV;
2665 if(mesh->sock != -1 || !comma) {
2672 if(mesh->sock == -1) {
2673 pthread_mutex_unlock(&mesh->mutex);
2677 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2679 // Tell him we have an invitation, and give him our throw-away key.
2683 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2684 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2685 closesocket(mesh->sock);
2686 meshlink_errno = MESHLINK_ENETWORK;
2687 pthread_mutex_unlock(&mesh->mutex);
2693 char hisname[4096] = "";
2694 int code, hismajor, hisminor = 0;
2696 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) {
2697 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2698 closesocket(mesh->sock);
2699 meshlink_errno = MESHLINK_ENETWORK;
2700 pthread_mutex_unlock(&mesh->mutex);
2704 // Check if the hash of the key he gave us matches the hash in the URL.
2705 char *fingerprint = mesh->line + 2;
2708 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2709 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2710 meshlink_errno = MESHLINK_EINTERNAL;
2711 pthread_mutex_unlock(&mesh->mutex);
2715 if(memcmp(hishash, mesh->hash, 18)) {
2716 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2717 meshlink_errno = MESHLINK_EPEER;
2718 pthread_mutex_unlock(&mesh->mutex);
2723 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2726 meshlink_errno = MESHLINK_EINTERNAL;
2727 pthread_mutex_unlock(&mesh->mutex);
2731 // Start an SPTPS session
2732 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2733 meshlink_errno = MESHLINK_EINTERNAL;
2734 pthread_mutex_unlock(&mesh->mutex);
2738 // Feed rest of input buffer to SPTPS
2739 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2740 meshlink_errno = MESHLINK_EPEER;
2741 pthread_mutex_unlock(&mesh->mutex);
2747 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2749 if(errno == EINTR) {
2753 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2754 meshlink_errno = MESHLINK_ENETWORK;
2755 pthread_mutex_unlock(&mesh->mutex);
2759 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2760 meshlink_errno = MESHLINK_EPEER;
2761 pthread_mutex_unlock(&mesh->mutex);
2766 sptps_stop(&mesh->sptps);
2769 closesocket(mesh->sock);
2771 if(!mesh->success) {
2772 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2773 meshlink_errno = MESHLINK_EPEER;
2774 pthread_mutex_unlock(&mesh->mutex);
2778 pthread_mutex_unlock(&mesh->mutex);
2782 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2783 meshlink_errno = MESHLINK_EINVAL;
2784 pthread_mutex_unlock(&mesh->mutex);
2788 char *meshlink_export(meshlink_handle_t *mesh) {
2790 meshlink_errno = MESHLINK_EINVAL;
2794 // Create a config file on the fly.
2797 packmsg_output_t out = {buf, sizeof(buf)};
2798 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2799 packmsg_add_str(&out, mesh->name);
2800 packmsg_add_str(&out, CORE_MESH);
2802 pthread_mutex_lock(&mesh->mutex);
2804 packmsg_add_int32(&out, mesh->self->devclass);
2805 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2806 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2807 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2811 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2812 if(mesh->self->recent[i].sa.sa_family) {
2819 packmsg_add_array(&out, count);
2821 for(uint32_t i = 0; i < count; i++) {
2822 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2825 packmsg_add_int64(&out, 0);
2826 packmsg_add_int64(&out, 0);
2828 pthread_mutex_unlock(&mesh->mutex);
2830 if(!packmsg_output_ok(&out)) {
2831 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2832 meshlink_errno = MESHLINK_EINTERNAL;
2836 // Prepare a base64-encoded packmsg array containing our config file
2838 uint32_t len = packmsg_output_size(&out, buf);
2839 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2840 uint8_t *buf2 = xmalloc(len2);
2841 packmsg_output_t out2 = {buf2, len2};
2842 packmsg_add_array(&out2, 1);
2843 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2845 if(!packmsg_output_ok(&out2)) {
2846 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2847 meshlink_errno = MESHLINK_EINTERNAL;
2852 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2854 return (char *)buf2;
2857 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2858 if(!mesh || !data) {
2859 meshlink_errno = MESHLINK_EINVAL;
2863 size_t datalen = strlen(data);
2864 uint8_t *buf = xmalloc(datalen);
2865 int buflen = b64decode(data, buf, datalen);
2868 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2869 meshlink_errno = MESHLINK_EPEER;
2873 packmsg_input_t in = {buf, buflen};
2874 uint32_t count = packmsg_get_array(&in);
2877 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2878 meshlink_errno = MESHLINK_EPEER;
2882 pthread_mutex_lock(&mesh->mutex);
2886 uint32_t len = packmsg_get_bin_raw(&in, &data);
2892 packmsg_input_t in2 = {data, len};
2893 uint32_t version = packmsg_get_uint32(&in2);
2894 char *name = packmsg_get_str_dup(&in2);
2896 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2898 packmsg_input_invalidate(&in);
2902 if(!check_id(name)) {
2907 node_t *n = lookup_node(mesh, name);
2910 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2918 config_t config = {data, len};
2920 if(!node_read_from_config(mesh, n, &config)) {
2922 packmsg_input_invalidate(&in);
2926 /* Clear the reachability times, since we ourself have never seen these nodes yet */
2927 n->last_reachable = 0;
2928 n->last_unreachable = 0;
2930 if(!node_write_config(mesh, n)) {
2938 pthread_mutex_unlock(&mesh->mutex);
2942 if(!packmsg_done(&in)) {
2943 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2944 meshlink_errno = MESHLINK_EPEER;
2948 if(!config_sync(mesh, "current")) {
2955 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
2956 if(n == mesh->self) {
2957 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
2958 meshlink_errno = MESHLINK_EINVAL;
2962 if(n->status.blacklisted) {
2963 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
2967 n->status.blacklisted = true;
2969 /* Immediately shut down any connections we have with the blacklisted node.
2970 * We can't call terminate_connection(), because we might be called from a callback function.
2972 for list_each(connection_t, c, mesh->connections) {
2974 shutdown(c->socket, SHUT_RDWR);
2978 utcp_abort_all_connections(n->utcp);
2984 n->status.udp_confirmed = false;
2986 if(n->status.reachable) {
2987 n->last_unreachable = mesh->loop.now.tv_sec;
2990 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
2991 * manually call the status callback if necessary.
2993 if(n->status.reachable && mesh->node_status_cb) {
2994 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
2997 return node_write_config(mesh, n) && config_sync(mesh, "current");
3000 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3001 if(!mesh || !node) {
3002 meshlink_errno = MESHLINK_EINVAL;
3006 pthread_mutex_lock(&mesh->mutex);
3008 if(!blacklist(mesh, (node_t *)node)) {
3009 pthread_mutex_unlock(&mesh->mutex);
3013 pthread_mutex_unlock(&mesh->mutex);
3015 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3019 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3020 if(!mesh || !name) {
3021 meshlink_errno = MESHLINK_EINVAL;
3025 pthread_mutex_lock(&mesh->mutex);
3027 node_t *n = lookup_node(mesh, (char *)name);
3031 n->name = xstrdup(name);
3035 if(!blacklist(mesh, (node_t *)n)) {
3036 pthread_mutex_unlock(&mesh->mutex);
3040 pthread_mutex_unlock(&mesh->mutex);
3042 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3046 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3047 if(n == mesh->self) {
3048 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3049 meshlink_errno = MESHLINK_EINVAL;
3053 if(!n->status.blacklisted) {
3054 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3058 n->status.blacklisted = false;
3060 if(n->status.reachable) {
3061 n->last_reachable = mesh->loop.now.tv_sec;
3062 update_node_status(mesh, n);
3065 return node_write_config(mesh, n) && config_sync(mesh, "current");
3068 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3069 if(!mesh || !node) {
3070 meshlink_errno = MESHLINK_EINVAL;
3074 pthread_mutex_lock(&mesh->mutex);
3076 if(!whitelist(mesh, (node_t *)node)) {
3077 pthread_mutex_unlock(&mesh->mutex);
3081 pthread_mutex_unlock(&mesh->mutex);
3083 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3087 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3088 if(!mesh || !name) {
3089 meshlink_errno = MESHLINK_EINVAL;
3093 pthread_mutex_lock(&mesh->mutex);
3095 node_t *n = lookup_node(mesh, (char *)name);
3099 n->name = xstrdup(name);
3103 if(!whitelist(mesh, (node_t *)n)) {
3104 pthread_mutex_unlock(&mesh->mutex);
3108 pthread_mutex_unlock(&mesh->mutex);
3110 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3114 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3115 mesh->default_blacklist = blacklist;
3118 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3119 if(!mesh || !node) {
3120 meshlink_errno = MESHLINK_EINVAL;
3124 node_t *n = (node_t *)node;
3126 pthread_mutex_lock(&mesh->mutex);
3128 /* Check that the node is not reachable */
3129 if(n->status.reachable || n->connection) {
3130 pthread_mutex_unlock(&mesh->mutex);
3131 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3135 /* Check that we don't have any active UTCP connections */
3136 if(n->utcp && utcp_is_active(n->utcp)) {
3137 pthread_mutex_unlock(&mesh->mutex);
3138 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3142 /* Check that we have no active connections to this node */
3143 for list_each(connection_t, c, mesh->connections) {
3145 pthread_mutex_unlock(&mesh->mutex);
3146 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3151 /* Remove any pending outgoings to this node */
3152 if(mesh->outgoings) {
3153 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3154 if(outgoing->node == n) {
3155 list_delete_node(mesh->outgoings, node);
3160 /* Delete the config file for this node */
3161 if(!config_delete(mesh, "current", n->name)) {
3162 pthread_mutex_unlock(&mesh->mutex);
3166 /* Delete the node struct and any remaining edges referencing this node */
3169 pthread_mutex_unlock(&mesh->mutex);
3171 return config_sync(mesh, "current");
3174 /* Hint that a hostname may be found at an address
3175 * See header file for detailed comment.
3177 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3178 if(!mesh || !node || !addr) {
3179 meshlink_errno = EINVAL;
3183 pthread_mutex_lock(&mesh->mutex);
3185 node_t *n = (node_t *)node;
3187 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3188 if(!node_write_config(mesh, n)) {
3189 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3193 pthread_mutex_unlock(&mesh->mutex);
3194 // @TODO do we want to fire off a connection attempt right away?
3197 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3199 node_t *n = utcp->priv;
3200 meshlink_handle_t *mesh = n->mesh;
3201 return mesh->channel_accept_cb;
3204 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3206 if(aio->cb.buffer) {
3207 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3211 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3216 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3217 meshlink_channel_t *channel = connection->priv;
3223 node_t *n = channel->node;
3224 meshlink_handle_t *mesh = n->mesh;
3226 if(n->status.destroyed) {
3227 meshlink_channel_close(mesh, channel);
3231 const char *p = data;
3234 while(channel->aio_receive) {
3235 meshlink_aio_buffer_t *aio = channel->aio_receive;
3236 size_t todo = aio->len - aio->done;
3243 memcpy((char *)aio->data + aio->done, p, todo);
3245 ssize_t result = write(aio->fd, p, todo);
3254 if(aio->done == aio->len) {
3255 channel->aio_receive = aio->next;
3256 aio_signal(mesh, channel, aio);
3268 if(channel->receive_cb) {
3269 channel->receive_cb(mesh, channel, p, left);
3275 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3276 node_t *n = utcp_connection->utcp->priv;
3282 meshlink_handle_t *mesh = n->mesh;
3284 if(!mesh->channel_accept_cb) {
3288 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3290 channel->c = utcp_connection;
3292 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3293 utcp_accept(utcp_connection, channel_recv, channel);
3299 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3300 node_t *n = utcp->priv;
3302 if(n->status.destroyed) {
3306 meshlink_handle_t *mesh = n->mesh;
3307 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3310 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3311 if(!mesh || !channel) {
3312 meshlink_errno = MESHLINK_EINVAL;
3316 channel->receive_cb = cb;
3319 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3321 node_t *n = (node_t *)source;
3327 utcp_recv(n->utcp, data, len);
3330 static void channel_poll(struct utcp_connection *connection, size_t len) {
3331 meshlink_channel_t *channel = connection->priv;
3337 node_t *n = channel->node;
3338 meshlink_handle_t *mesh = n->mesh;
3339 meshlink_aio_buffer_t *aio = channel->aio_send;
3342 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3343 size_t left = aio->len - aio->done;
3351 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3354 size_t todo = utcp_get_sndbuf_free(connection);
3360 if(todo > sizeof(buf)) {
3364 ssize_t result = read(aio->fd, buf, todo);
3367 sent = utcp_send(connection, buf, result);
3377 /* If the buffer is now completely sent, call the callback and dispose of it. */
3378 if(aio->done >= aio->len) {
3379 channel->aio_send = aio->next;
3380 aio_signal(mesh, channel, aio);
3384 if(channel->poll_cb) {
3385 channel->poll_cb(mesh, channel, len);
3387 utcp_set_poll_cb(connection, NULL);
3392 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3393 if(!mesh || !channel) {
3394 meshlink_errno = MESHLINK_EINVAL;
3398 pthread_mutex_lock(&mesh->mutex);
3399 channel->poll_cb = cb;
3400 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3401 pthread_mutex_unlock(&mesh->mutex);
3404 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3406 meshlink_errno = MESHLINK_EINVAL;
3410 pthread_mutex_lock(&mesh->mutex);
3411 mesh->channel_accept_cb = cb;
3412 mesh->receive_cb = channel_receive;
3414 for splay_each(node_t, n, mesh->nodes) {
3415 if(!n->utcp && n != mesh->self) {
3416 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3420 pthread_mutex_unlock(&mesh->mutex);
3423 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3427 meshlink_errno = MESHLINK_EINVAL;
3431 pthread_mutex_lock(&mesh->mutex);
3432 utcp_set_sndbuf(channel->c, size);
3433 pthread_mutex_unlock(&mesh->mutex);
3436 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3440 meshlink_errno = MESHLINK_EINVAL;
3444 pthread_mutex_lock(&mesh->mutex);
3445 utcp_set_rcvbuf(channel->c, size);
3446 pthread_mutex_unlock(&mesh->mutex);
3449 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) {
3451 abort(); // TODO: handle non-NULL data
3454 if(!mesh || !node) {
3455 meshlink_errno = MESHLINK_EINVAL;
3459 pthread_mutex_lock(&mesh->mutex);
3461 node_t *n = (node_t *)node;
3464 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3465 mesh->receive_cb = channel_receive;
3468 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3469 pthread_mutex_unlock(&mesh->mutex);
3474 if(n->status.blacklisted) {
3475 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3476 meshlink_errno = MESHLINK_EBLACKLISTED;
3477 pthread_mutex_unlock(&mesh->mutex);
3481 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3483 channel->receive_cb = cb;
3486 channel->priv = (void *)data;
3489 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3491 pthread_mutex_unlock(&mesh->mutex);
3494 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3502 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) {
3503 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3506 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3507 if(!mesh || !channel) {
3508 meshlink_errno = MESHLINK_EINVAL;
3512 pthread_mutex_lock(&mesh->mutex);
3513 utcp_shutdown(channel->c, direction);
3514 pthread_mutex_unlock(&mesh->mutex);
3517 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3518 if(!mesh || !channel) {
3519 meshlink_errno = MESHLINK_EINVAL;
3523 pthread_mutex_lock(&mesh->mutex);
3525 utcp_close(channel->c);
3527 /* Clean up any outstanding AIO buffers. */
3528 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3530 aio_signal(mesh, channel, aio);
3534 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3536 aio_signal(mesh, channel, aio);
3540 pthread_mutex_unlock(&mesh->mutex);
3545 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3546 if(!mesh || !channel) {
3547 meshlink_errno = MESHLINK_EINVAL;
3556 meshlink_errno = MESHLINK_EINVAL;
3560 // TODO: more finegrained locking.
3561 // Ideally we want to put the data into the UTCP connection's send buffer.
3562 // Then, preferably only if there is room in the receiver window,
3563 // kick the meshlink thread to go send packets.
3567 pthread_mutex_lock(&mesh->mutex);
3569 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3570 if(channel->aio_send) {
3573 retval = utcp_send(channel->c, data, len);
3576 pthread_mutex_unlock(&mesh->mutex);
3579 meshlink_errno = MESHLINK_ENETWORK;
3585 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) {
3586 if(!mesh || !channel) {
3587 meshlink_errno = MESHLINK_EINVAL;
3592 meshlink_errno = MESHLINK_EINVAL;
3596 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3599 aio->cb.buffer = cb;
3602 pthread_mutex_lock(&mesh->mutex);
3604 /* Append the AIO buffer descriptor to the end of the chain */
3605 meshlink_aio_buffer_t **p = &channel->aio_send;
3613 /* Ensure the poll callback is set, and call it right now to push data if possible */
3614 utcp_set_poll_cb(channel->c, channel_poll);
3615 channel_poll(channel->c, len);
3617 pthread_mutex_unlock(&mesh->mutex);
3622 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) {
3623 if(!mesh || !channel) {
3624 meshlink_errno = MESHLINK_EINVAL;
3628 if(!len || fd == -1) {
3629 meshlink_errno = MESHLINK_EINVAL;
3633 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3639 pthread_mutex_lock(&mesh->mutex);
3641 /* Append the AIO buffer descriptor to the end of the chain */
3642 meshlink_aio_buffer_t **p = &channel->aio_send;
3650 /* Ensure the poll callback is set, and call it right now to push data if possible */
3651 utcp_set_poll_cb(channel->c, channel_poll);
3652 channel_poll(channel->c, len);
3654 pthread_mutex_unlock(&mesh->mutex);
3659 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) {
3660 if(!mesh || !channel) {
3661 meshlink_errno = MESHLINK_EINVAL;
3666 meshlink_errno = MESHLINK_EINVAL;
3670 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3673 aio->cb.buffer = cb;
3676 pthread_mutex_lock(&mesh->mutex);
3678 /* Append the AIO buffer descriptor to the end of the chain */
3679 meshlink_aio_buffer_t **p = &channel->aio_receive;
3687 pthread_mutex_unlock(&mesh->mutex);
3692 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) {
3693 if(!mesh || !channel) {
3694 meshlink_errno = MESHLINK_EINVAL;
3698 if(!len || fd == -1) {
3699 meshlink_errno = MESHLINK_EINVAL;
3703 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3709 pthread_mutex_lock(&mesh->mutex);
3711 /* Append the AIO buffer descriptor to the end of the chain */
3712 meshlink_aio_buffer_t **p = &channel->aio_receive;
3720 pthread_mutex_unlock(&mesh->mutex);
3725 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3726 if(!mesh || !channel) {
3727 meshlink_errno = MESHLINK_EINVAL;
3731 return channel->c->flags;
3734 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3735 if(!mesh || !channel) {
3736 meshlink_errno = MESHLINK_EINVAL;
3740 return utcp_get_sendq(channel->c);
3743 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3744 if(!mesh || !channel) {
3745 meshlink_errno = MESHLINK_EINVAL;
3749 return utcp_get_recvq(channel->c);
3752 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3753 if(!mesh || !node) {
3754 meshlink_errno = MESHLINK_EINVAL;
3758 node_t *n = (node_t *)node;
3760 pthread_mutex_lock(&mesh->mutex);
3763 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3766 utcp_set_user_timeout(n->utcp, timeout);
3768 pthread_mutex_unlock(&mesh->mutex);
3771 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3772 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3773 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3776 if(mesh->node_status_cb) {
3777 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3780 if(mesh->node_pmtu_cb) {
3781 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3785 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3786 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3787 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3791 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3792 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3796 n->status.duplicate = true;
3797 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3800 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3804 meshlink_errno = MESHLINK_EINVAL;
3808 pthread_mutex_lock(&mesh->mutex);
3810 if(mesh->discovery == enable) {
3814 if(mesh->threadstarted) {
3816 discovery_start(mesh);
3818 discovery_stop(mesh);
3822 mesh->discovery = enable;
3825 pthread_mutex_unlock(&mesh->mutex);
3829 meshlink_errno = MESHLINK_ENOTSUP;
3833 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3834 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3835 meshlink_errno = EINVAL;
3839 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3840 meshlink_errno = EINVAL;
3844 pthread_mutex_lock(&mesh->mutex);
3845 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3846 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3847 pthread_mutex_unlock(&mesh->mutex);
3850 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3851 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3852 meshlink_errno = EINVAL;
3856 if(fast_retry_period < 0) {
3857 meshlink_errno = EINVAL;
3861 pthread_mutex_lock(&mesh->mutex);
3862 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3863 pthread_mutex_unlock(&mesh->mutex);
3866 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3869 if(!mesh->connections || !mesh->loop.running) {
3876 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3877 // We should only call the callback function if we are in the background thread.
3878 if(!mesh->error_cb) {
3882 if(!mesh->threadstarted) {
3886 if(mesh->thread == pthread_self()) {
3887 mesh->error_cb(mesh, meshlink_errno);
3892 static void __attribute__((constructor)) meshlink_init(void) {
3896 static void __attribute__((destructor)) meshlink_exit(void) {