2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2021 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.
27 #include "meshlink_internal.h"
39 #include "ed25519/sha512.h"
40 #include "discovery.h"
45 #define MSG_NOSIGNAL 0
47 __thread meshlink_errno_t meshlink_errno;
48 meshlink_log_cb_t global_log_cb;
49 meshlink_log_level_t global_log_level;
51 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
53 static int rstrip(char *value) {
54 int len = strlen(value);
56 while(len && strchr("\t\r\n ", value[len - 1])) {
63 static bool is_valid_hostname(const char *hostname) {
68 for(const char *p = hostname; *p; p++) {
69 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
77 static bool is_valid_port(const char *port) {
84 unsigned long int result = strtoul(port, &end, 10);
85 return result && result < 65536 && !*end;
88 for(const char *p = port; *p; p++) {
89 if(!(isalnum(*p) || *p == '-')) {
97 static void set_timeout(int sock, int timeout) {
102 tv.tv_sec = timeout / 1000;
103 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
105 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
106 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
109 struct socket_in_netns_params {
118 static void *socket_in_netns_thread(void *arg) {
119 struct socket_in_netns_params *params = arg;
121 if(setns(params->netns, CLONE_NEWNET) == -1) {
122 meshlink_errno = MESHLINK_EINVAL;
126 params->fd = socket(params->domain, params->type, params->protocol);
132 static int socket_in_netns(int domain, int type, int protocol, int netns) {
134 return socket(domain, type, protocol);
138 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
142 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
143 if(pthread_join(thr, NULL) != 0) {
155 // Find out what local address a socket would use if we connect to the given address.
156 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
157 // of both endpoints, but this will actually not send any UDP packet.
158 static bool getlocaladdr(const char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
159 struct addrinfo *rai = NULL;
160 const struct addrinfo hint = {
161 .ai_family = AF_UNSPEC,
162 .ai_socktype = SOCK_DGRAM,
163 .ai_protocol = IPPROTO_UDP,
164 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
167 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
171 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
178 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
186 if(getsockname(sock, &sa->sa, salen)) {
195 static bool getlocaladdrname(const char *destaddr, char *host, socklen_t hostlen, int netns) {
197 socklen_t salen = sizeof(sa);
199 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
203 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
210 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
211 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
214 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
215 logger(mesh, MESHLINK_DEBUG, "meshlink_get_external_address_for_family(%d)", family);
216 const char *url = mesh->external_address_url;
219 url = "http://meshlink.io/host.cgi";
222 /* Find the hostname part between the slashes */
223 if(strncmp(url, "http://", 7)) {
225 meshlink_errno = MESHLINK_EINTERNAL;
229 const char *begin = url + 7;
231 const char *end = strchr(begin, '/');
234 end = begin + strlen(begin);
238 char host[end - begin + 1];
239 strncpy(host, begin, end - begin);
240 host[end - begin] = 0;
242 char *port = strchr(host, ':');
248 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
249 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(host), xstrdup(port ? port : "80"), SOCK_STREAM, 5);
251 char *hostname = NULL;
253 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
254 if(family != AF_UNSPEC && aip->ai_family != family) {
258 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
262 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
266 set_timeout(s, 5000);
268 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
275 send(s, "GET ", 4, 0);
276 send(s, url, strlen(url), 0);
277 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
278 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
283 if(line[len - 1] == '\n') {
287 char *p = strrchr(line, '\n');
290 hostname = xstrdup(p + 1);
306 // Check that the hostname is reasonable
307 if(hostname && !is_valid_hostname(hostname)) {
313 meshlink_errno = MESHLINK_ERESOLV;
319 static bool is_localaddr(sockaddr_t *sa) {
320 switch(sa->sa.sa_family) {
322 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
325 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
326 return first == 0 || (first & 0xffc0) == 0xfe80;
334 #ifdef HAVE_GETIFADDRS
335 struct getifaddrs_in_netns_params {
336 struct ifaddrs **ifa;
341 static void *getifaddrs_in_netns_thread(void *arg) {
342 struct getifaddrs_in_netns_params *params = arg;
344 if(setns(params->netns, CLONE_NEWNET) == -1) {
345 meshlink_errno = MESHLINK_EINVAL;
349 if(getifaddrs(params->ifa) != 0) {
357 static int getifaddrs_in_netns(struct ifaddrs **ifa, int netns) {
359 return getifaddrs(ifa);
363 struct getifaddrs_in_netns_params params = {ifa, netns};
366 if(pthread_create(&thr, NULL, getifaddrs_in_netns_thread, ¶ms) == 0) {
367 if(pthread_join(thr, NULL) != 0) {
372 return *params.ifa ? 0 : -1;
380 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
381 logger(mesh, MESHLINK_DEBUG, "meshlink_get_local_address_for_family(%d)", family);
384 meshlink_errno = MESHLINK_EINVAL;
388 // Determine address of the local interface used for outgoing connections.
389 char localaddr[NI_MAXHOST];
390 bool success = false;
392 if(family == AF_INET) {
393 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
394 } else if(family == AF_INET6) {
395 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
398 #ifdef HAVE_GETIFADDRS
401 struct ifaddrs *ifa = NULL;
402 getifaddrs_in_netns(&ifa, mesh->netns);
404 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
405 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
407 if(!sa || sa->sa.sa_family != family) {
411 if(is_localaddr(sa)) {
415 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
427 meshlink_errno = MESHLINK_ENETWORK;
431 return xstrdup(localaddr);
434 static bool try_bind(meshlink_handle_t *mesh, int port) {
435 struct addrinfo *ai = NULL;
436 struct addrinfo hint = {
437 .ai_flags = AI_PASSIVE,
438 .ai_family = AF_UNSPEC,
439 .ai_socktype = SOCK_STREAM,
440 .ai_protocol = IPPROTO_TCP,
444 snprintf(portstr, sizeof(portstr), "%d", port);
446 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
450 bool success = false;
452 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
453 /* Try to bind to TCP. */
455 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
458 if(errno == EADDRINUSE) {
459 /* If this port is in use for any address family, avoid it. */
467 /* If TCP worked, then we require that UDP works as well. */
469 int udp_fd = setup_udp_listen_socket(mesh, aip);
486 int check_port(meshlink_handle_t *mesh) {
487 for(int i = 0; i < 1000; i++) {
488 int port = 0x1000 + prng(mesh, 0x8000);
490 if(try_bind(mesh, port)) {
492 xasprintf(&mesh->myport, "%d", port);
497 meshlink_errno = MESHLINK_ENETWORK;
498 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
502 static bool write_main_config_files(meshlink_handle_t *mesh) {
503 if(!mesh->confbase) {
509 /* Write the main config file */
510 packmsg_output_t out = {buf, sizeof buf};
512 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
513 packmsg_add_str(&out, mesh->name);
514 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
515 packmsg_add_nil(&out); // Invitation keys are not supported
516 packmsg_add_uint16(&out, atoi(mesh->myport));
518 if(!packmsg_output_ok(&out)) {
522 config_t config = {buf, packmsg_output_size(&out, buf)};
524 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
528 /* Write our own host config file */
529 if(!node_write_config(mesh, mesh->self, true)) {
537 meshlink_handle_t *mesh;
539 char cookie[18 + 32];
550 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
551 meshlink_handle_t *mesh = state->mesh;
552 packmsg_input_t in = {buf, len};
553 uint32_t version = packmsg_get_uint32(&in);
555 if(version != MESHLINK_INVITATION_VERSION) {
556 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
560 char *name = packmsg_get_str_dup(&in);
561 char *submesh_name = packmsg_get_str_dup(&in);
562 dev_class_t devclass = packmsg_get_int32(&in);
563 uint32_t count = packmsg_get_array(&in);
565 if(!name || !check_id(name)) {
566 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
572 if(!submesh_name || (strcmp(submesh_name, CORE_MESH) && !check_id(submesh_name))) {
573 logger(mesh, MESHLINK_DEBUG, "No valid Submesh found in invitation!\n");
580 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
587 free(mesh->self->name);
589 mesh->self->name = xstrdup(name);
590 mesh->self->submesh = strcmp(submesh_name, CORE_MESH) ? lookup_or_create_submesh(mesh, submesh_name) : NULL;
592 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
594 // Initialize configuration directory
595 if(!config_init(mesh, "current")) {
599 if(!write_main_config_files(mesh)) {
603 // Write host config files
604 for(uint32_t i = 0; i < count; i++) {
606 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
609 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
613 packmsg_input_t in2 = {data, data_len};
614 uint32_t version2 = packmsg_get_uint32(&in2);
615 char *name2 = packmsg_get_str_dup(&in2);
617 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
619 packmsg_input_invalidate(&in);
623 if(!check_id(name2)) {
628 if(!strcmp(name2, mesh->name)) {
629 logger(mesh, MESHLINK_ERROR, "Secondary chunk would overwrite our own host config file.\n");
631 meshlink_errno = MESHLINK_EPEER;
635 node_t *n = new_node();
638 config_t config = {data, data_len};
640 if(!node_read_from_config(mesh, n, &config)) {
642 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
643 meshlink_errno = MESHLINK_EPEER;
648 /* The first host config file is of the inviter itself;
649 * remember the address we are currently using for the invitation connection.
652 socklen_t salen = sizeof(sa);
654 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
655 node_add_recent_address(mesh, n, &sa);
659 /* Clear the reachability times, since we ourself have never seen these nodes yet */
660 n->last_reachable = 0;
661 n->last_unreachable = 0;
663 if(!node_write_config(mesh, n, true)) {
671 /* Ensure the configuration directory metadata is on disk */
672 if(!config_sync(mesh, "current") || (mesh->confbase && !sync_path(mesh->confbase))) {
676 if(!mesh->inviter_commits_first) {
677 devtool_set_inviter_commits_first(false);
680 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
682 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
687 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
689 join_state_t *state = handle;
690 const char *ptr = data;
693 int result = send(state->sock, ptr, len, 0);
695 if(result == -1 && errno == EINTR) {
697 } else if(result <= 0) {
708 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
709 join_state_t *state = handle;
710 meshlink_handle_t *mesh = state->mesh;
712 if(mesh->inviter_commits_first) {
714 case SPTPS_HANDSHAKE:
715 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
721 if(!finalize_join(state, msg, len)) {
725 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
726 shutdown(state->sock, SHUT_RDWR);
727 state->success = true;
735 case SPTPS_HANDSHAKE:
736 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
739 return finalize_join(state, msg, len);
742 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
743 shutdown(state->sock, SHUT_RDWR);
744 state->success = true;
755 static bool recvline(join_state_t *state) {
756 char *newline = NULL;
758 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
759 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
761 if(result == -1 && errno == EINTR) {
763 } else if(result <= 0) {
767 state->blen += result;
770 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
774 size_t len = newline - state->buffer;
776 memcpy(state->line, state->buffer, len);
777 state->line[len] = 0;
778 memmove(state->buffer, newline + 1, state->blen - len - 1);
779 state->blen -= len + 1;
784 static bool sendline(int fd, const char *format, ...) {
790 va_start(ap, format);
791 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
794 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
802 int result = send(fd, p, blen, MSG_NOSIGNAL);
804 if(result == -1 && errno == EINTR) {
806 } else if(result <= 0) {
817 static const char *errstr[] = {
818 [MESHLINK_OK] = "No error",
819 [MESHLINK_EINVAL] = "Invalid argument",
820 [MESHLINK_ENOMEM] = "Out of memory",
821 [MESHLINK_ENOENT] = "No such node",
822 [MESHLINK_EEXIST] = "Node already exists",
823 [MESHLINK_EINTERNAL] = "Internal error",
824 [MESHLINK_ERESOLV] = "Could not resolve hostname",
825 [MESHLINK_ESTORAGE] = "Storage error",
826 [MESHLINK_ENETWORK] = "Network error",
827 [MESHLINK_EPEER] = "Error communicating with peer",
828 [MESHLINK_ENOTSUP] = "Operation not supported",
829 [MESHLINK_EBUSY] = "MeshLink instance already in use",
830 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
833 const char *meshlink_strerror(meshlink_errno_t err) {
834 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
835 return "Invalid error code";
841 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
842 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypair:\n");
844 mesh->private_key = ecdsa_generate();
846 if(!mesh->private_key) {
847 logger(mesh, MESHLINK_ERROR, "Error during key generation!\n");
848 meshlink_errno = MESHLINK_EINTERNAL;
852 logger(mesh, MESHLINK_DEBUG, "Done.\n");
857 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
858 if(a->tv_sec == b->tv_sec) {
859 return a->tv_nsec < b->tv_nsec;
861 return a->tv_sec < b->tv_sec;
865 static struct timespec idle(event_loop_t *loop, void *data) {
867 meshlink_handle_t *mesh = data;
868 struct timespec t, tmin = {3600, 0};
870 for splay_each(node_t, n, mesh->nodes) {
875 t = utcp_timeout(n->utcp);
877 if(timespec_lt(&t, &tmin)) {
885 // Get our local address(es) by simulating connecting to an Internet host.
886 static void add_local_addresses(meshlink_handle_t *mesh) {
888 sa.storage.ss_family = AF_UNKNOWN;
889 socklen_t salen = sizeof(sa);
893 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
894 sa.in.sin_port = ntohs(atoi(mesh->myport));
895 node_add_recent_address(mesh, mesh->self, &sa);
902 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
903 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
904 node_add_recent_address(mesh, mesh->self, &sa);
908 static bool meshlink_setup(meshlink_handle_t *mesh) {
909 if(!config_destroy(mesh->confbase, "new")) {
910 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
911 meshlink_errno = MESHLINK_ESTORAGE;
915 if(!config_destroy(mesh->confbase, "old")) {
916 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
917 meshlink_errno = MESHLINK_ESTORAGE;
921 if(!config_init(mesh, "current")) {
922 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
923 meshlink_errno = MESHLINK_ESTORAGE;
927 if(!ecdsa_keygen(mesh)) {
928 meshlink_errno = MESHLINK_EINTERNAL;
932 if(check_port(mesh) == 0) {
933 meshlink_errno = MESHLINK_ENETWORK;
937 /* Create a node for ourself */
939 mesh->self = new_node();
940 mesh->self->name = xstrdup(mesh->name);
941 mesh->self->devclass = mesh->devclass;
942 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
943 mesh->self->session_id = mesh->session_id;
945 if(!write_main_config_files(mesh)) {
946 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
947 meshlink_errno = MESHLINK_ESTORAGE;
951 /* Ensure the configuration directory metadata is on disk */
952 if(!config_sync(mesh, "current")) {
959 static bool meshlink_read_config(meshlink_handle_t *mesh) {
962 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
963 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
967 packmsg_input_t in = {config.buf, config.len};
968 const void *private_key;
970 uint32_t version = packmsg_get_uint32(&in);
971 char *name = packmsg_get_str_dup(&in);
972 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
973 packmsg_skip_element(&in); // Invitation key is not supported
974 uint16_t myport = packmsg_get_uint16(&in);
976 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96) {
977 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
979 config_free(&config);
983 if(mesh->name && strcmp(mesh->name, name)) {
984 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
985 meshlink_errno = MESHLINK_ESTORAGE;
987 config_free(&config);
993 xasprintf(&mesh->myport, "%u", myport);
994 mesh->private_key = ecdsa_set_private_key(private_key);
995 config_free(&config);
997 /* Create a node for ourself and read our host configuration file */
999 mesh->self = new_node();
1000 mesh->self->name = xstrdup(name);
1001 mesh->self->devclass = mesh->devclass;
1002 mesh->self->session_id = mesh->session_id;
1004 if(!node_read_public_key(mesh, mesh->self)) {
1005 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1006 meshlink_errno = MESHLINK_ESTORAGE;
1007 free_node(mesh->self);
1016 static void *setup_network_in_netns_thread(void *arg) {
1017 meshlink_handle_t *mesh = arg;
1019 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1023 bool success = setup_network(mesh);
1024 return success ? arg : NULL;
1026 #endif // HAVE_SETNS
1028 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1029 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_init(%s, %s, %s, %d)", confbase, name, appname, devclass);
1031 if(!confbase || !*confbase) {
1032 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1033 meshlink_errno = MESHLINK_EINVAL;
1037 if(!appname || !*appname) {
1038 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1039 meshlink_errno = MESHLINK_EINVAL;
1043 if(strchr(appname, ' ')) {
1044 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1045 meshlink_errno = MESHLINK_EINVAL;
1049 if(name && !check_id(name)) {
1050 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1051 meshlink_errno = MESHLINK_EINVAL;
1055 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1056 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1057 meshlink_errno = MESHLINK_EINVAL;
1061 meshlink_open_params_t *params = xzalloc(sizeof * params);
1063 params->confbase = xstrdup(confbase);
1064 params->name = name ? xstrdup(name) : NULL;
1065 params->appname = xstrdup(appname);
1066 params->devclass = devclass;
1069 xasprintf(¶ms->lock_filename, "%s" SLASH "meshlink.lock", confbase);
1074 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1075 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_netnst(%d)", netns);
1078 meshlink_errno = MESHLINK_EINVAL;
1082 params->netns = netns;
1087 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1088 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_key(%p, %zu)", key, keylen);
1091 meshlink_errno = MESHLINK_EINVAL;
1095 if((!key && keylen) || (key && !keylen)) {
1096 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1097 meshlink_errno = MESHLINK_EINVAL;
1102 params->keylen = keylen;
1107 bool meshlink_open_params_set_storage_policy(meshlink_open_params_t *params, meshlink_storage_policy_t policy) {
1108 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_storage_policy(%d)", policy);
1111 meshlink_errno = MESHLINK_EINVAL;
1115 params->storage_policy = policy;
1120 bool meshlink_open_params_set_lock_filename(meshlink_open_params_t *params, const char *filename) {
1121 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_set_lock_filename(%s)", filename);
1123 if(!params || !filename) {
1124 meshlink_errno = MESHLINK_EINVAL;
1128 free(params->lock_filename);
1129 params->lock_filename = xstrdup(filename);
1134 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1135 logger(NULL, MESHLINK_DEBUG, "meshlink_encrypted_key_rotate(%p, %zu)", new_key, new_keylen);
1137 if(!mesh || !new_key || !new_keylen) {
1138 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1139 meshlink_errno = MESHLINK_EINVAL;
1143 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1147 // Create hash for the new key
1148 void *new_config_key;
1149 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1151 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1152 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1153 meshlink_errno = MESHLINK_EINTERNAL;
1154 pthread_mutex_unlock(&mesh->mutex);
1158 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1160 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1161 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1162 meshlink_errno = MESHLINK_ESTORAGE;
1163 pthread_mutex_unlock(&mesh->mutex);
1167 devtool_keyrotate_probe(1);
1169 // Rename confbase/current/ to confbase/old
1171 if(!config_rename(mesh, "current", "old")) {
1172 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1173 meshlink_errno = MESHLINK_ESTORAGE;
1174 pthread_mutex_unlock(&mesh->mutex);
1178 devtool_keyrotate_probe(2);
1180 // Rename confbase/new/ to confbase/current
1182 if(!config_rename(mesh, "new", "current")) {
1183 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1184 meshlink_errno = MESHLINK_ESTORAGE;
1185 pthread_mutex_unlock(&mesh->mutex);
1189 devtool_keyrotate_probe(3);
1191 // Cleanup the "old" confbase sub-directory
1193 if(!config_destroy(mesh->confbase, "old")) {
1194 pthread_mutex_unlock(&mesh->mutex);
1198 // Change the mesh handle key with new key
1200 free(mesh->config_key);
1201 mesh->config_key = new_config_key;
1203 pthread_mutex_unlock(&mesh->mutex);
1208 void meshlink_open_params_free(meshlink_open_params_t *params) {
1209 logger(NULL, MESHLINK_DEBUG, "meshlink_open_params_free()");
1212 meshlink_errno = MESHLINK_EINVAL;
1216 free(params->confbase);
1218 free(params->appname);
1219 free(params->lock_filename);
1224 /// Device class traits
1225 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1226 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1227 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1228 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1229 { .pingtimeout = 5, .pinginterval = 60, .maxtimeout = 900, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1232 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1233 logger(NULL, MESHLINK_DEBUG, "meshlink_open(%s, %s, %s, %d)", confbase, name, appname, devclass);
1235 if(!confbase || !*confbase) {
1236 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1237 meshlink_errno = MESHLINK_EINVAL;
1241 char lock_filename[PATH_MAX];
1242 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1244 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1245 meshlink_open_params_t params = {
1246 .confbase = (char *)confbase,
1247 .lock_filename = lock_filename,
1248 .name = (char *)name,
1249 .appname = (char *)appname,
1250 .devclass = devclass,
1254 return meshlink_open_ex(¶ms);
1257 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) {
1258 logger(NULL, MESHLINK_DEBUG, "meshlink_open_encrypted(%s, %s, %s, %d, %p, %zu)", confbase, name, appname, devclass, key, keylen);
1260 if(!confbase || !*confbase) {
1261 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1262 meshlink_errno = MESHLINK_EINVAL;
1266 char lock_filename[PATH_MAX];
1267 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1269 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1270 meshlink_open_params_t params = {
1271 .confbase = (char *)confbase,
1272 .lock_filename = lock_filename,
1273 .name = (char *)name,
1274 .appname = (char *)appname,
1275 .devclass = devclass,
1279 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1283 return meshlink_open_ex(¶ms);
1286 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1287 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ephemeral(%s, %s, %d)", name, appname, devclass);
1290 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1291 meshlink_errno = MESHLINK_EINVAL;
1295 if(!check_id(name)) {
1296 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1297 meshlink_errno = MESHLINK_EINVAL;
1301 if(!appname || !*appname) {
1302 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1303 meshlink_errno = MESHLINK_EINVAL;
1307 if(strchr(appname, ' ')) {
1308 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1309 meshlink_errno = MESHLINK_EINVAL;
1313 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1314 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1315 meshlink_errno = MESHLINK_EINVAL;
1319 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1320 meshlink_open_params_t params = {
1321 .name = (char *)name,
1322 .appname = (char *)appname,
1323 .devclass = devclass,
1327 return meshlink_open_ex(¶ms);
1330 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1331 logger(NULL, MESHLINK_DEBUG, "meshlink_open_ex()");
1333 // Validate arguments provided by the application
1334 if(!params->appname || !*params->appname) {
1335 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1336 meshlink_errno = MESHLINK_EINVAL;
1340 if(strchr(params->appname, ' ')) {
1341 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1342 meshlink_errno = MESHLINK_EINVAL;
1346 if(params->name && !check_id(params->name)) {
1347 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1348 meshlink_errno = MESHLINK_EINVAL;
1352 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1353 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1354 meshlink_errno = MESHLINK_EINVAL;
1358 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1359 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1360 meshlink_errno = MESHLINK_EINVAL;
1364 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1366 if(params->confbase) {
1367 mesh->confbase = xstrdup(params->confbase);
1370 mesh->appname = xstrdup(params->appname);
1371 mesh->devclass = params->devclass;
1372 mesh->discovery.enabled = true;
1373 mesh->netns = params->netns;
1374 mesh->submeshes = NULL;
1375 mesh->log_cb = global_log_cb;
1376 mesh->log_level = global_log_level;
1377 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1379 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1382 randomize(&mesh->session_id, sizeof(mesh->session_id));
1383 } while(mesh->session_id == 0);
1385 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1387 mesh->name = params->name ? xstrdup(params->name) : NULL;
1391 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1393 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1394 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1395 meshlink_close(mesh);
1396 meshlink_errno = MESHLINK_EINTERNAL;
1401 // initialize mutexes and conds
1402 pthread_mutexattr_t attr;
1403 pthread_mutexattr_init(&attr);
1405 if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) != 0) {
1409 pthread_mutex_init(&mesh->mutex, &attr);
1410 pthread_cond_init(&mesh->cond, NULL);
1412 pthread_cond_init(&mesh->adns_cond, NULL);
1414 mesh->threadstarted = false;
1415 event_loop_init(&mesh->loop);
1416 mesh->loop.data = mesh;
1418 meshlink_queue_init(&mesh->outpacketqueue);
1420 // Atomically lock the configuration directory.
1421 if(!main_config_lock(mesh, params->lock_filename)) {
1422 meshlink_close(mesh);
1426 // If no configuration exists yet, create it.
1428 bool new_configuration = false;
1430 if(!meshlink_confbase_exists(mesh)) {
1432 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1433 meshlink_close(mesh);
1434 meshlink_errno = MESHLINK_ESTORAGE;
1438 if(!meshlink_setup(mesh)) {
1439 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1440 meshlink_close(mesh);
1444 new_configuration = true;
1446 if(!meshlink_read_config(mesh)) {
1447 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1448 meshlink_close(mesh);
1453 mesh->storage_policy = params->storage_policy;
1456 struct WSAData wsa_state;
1457 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1460 // Setup up everything
1461 // TODO: we should not open listening sockets yet
1463 bool success = false;
1465 if(mesh->netns != -1) {
1469 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1470 void *retval = NULL;
1471 success = pthread_join(thr, &retval) == 0 && retval;
1475 meshlink_errno = MESHLINK_EINTERNAL;
1478 #endif // HAVE_SETNS
1480 success = setup_network(mesh);
1484 meshlink_close(mesh);
1485 meshlink_errno = MESHLINK_ENETWORK;
1489 add_local_addresses(mesh);
1491 if(!node_write_config(mesh, mesh->self, new_configuration)) {
1492 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1496 idle_set(&mesh->loop, idle, mesh);
1498 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1502 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1503 logger(NULL, MESHLINK_DEBUG, "meshlink_submesh_open(%s)", submesh);
1505 meshlink_submesh_t *s = NULL;
1508 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1509 meshlink_errno = MESHLINK_EINVAL;
1513 if(!submesh || !*submesh) {
1514 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1515 meshlink_errno = MESHLINK_EINVAL;
1520 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1524 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1526 pthread_mutex_unlock(&mesh->mutex);
1531 static void *meshlink_main_loop(void *arg) {
1532 meshlink_handle_t *mesh = arg;
1534 if(mesh->netns != -1) {
1537 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1538 pthread_cond_signal(&mesh->cond);
1543 pthread_cond_signal(&mesh->cond);
1545 #endif // HAVE_SETNS
1548 if(mesh->discovery.enabled) {
1549 discovery_start(mesh);
1552 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1556 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1557 pthread_cond_broadcast(&mesh->cond);
1559 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1561 pthread_mutex_unlock(&mesh->mutex);
1564 if(mesh->discovery.enabled) {
1565 discovery_stop(mesh);
1571 bool meshlink_start(meshlink_handle_t *mesh) {
1573 meshlink_errno = MESHLINK_EINVAL;
1577 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1579 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1584 assert(mesh->private_key);
1585 assert(mesh->self->ecdsa);
1586 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1588 if(mesh->threadstarted) {
1589 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1590 pthread_mutex_unlock(&mesh->mutex);
1594 if(mesh->listen_socket[0].tcp.fd < 0) {
1595 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1596 meshlink_errno = MESHLINK_ENETWORK;
1600 // Reset node connection timers
1601 for splay_each(node_t, n, mesh->nodes) {
1602 n->last_connect_try = 0;
1605 // TODO: open listening sockets first
1607 //Check that a valid name is set
1609 logger(mesh, MESHLINK_ERROR, "No name given!\n");
1610 meshlink_errno = MESHLINK_EINVAL;
1611 pthread_mutex_unlock(&mesh->mutex);
1615 init_outgoings(mesh);
1618 // Start the main thread
1620 event_loop_start(&mesh->loop);
1622 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1623 pthread_attr_t attr;
1624 pthread_attr_init(&attr);
1625 pthread_attr_setstacksize(&attr, 1024 * 1024);
1627 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1628 logger(mesh, MESHLINK_ERROR, "Could not start thread: %s\n", strerror(errno));
1629 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1630 meshlink_errno = MESHLINK_EINTERNAL;
1631 event_loop_stop(&mesh->loop);
1632 pthread_mutex_unlock(&mesh->mutex);
1636 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1637 mesh->threadstarted = true;
1639 // Ensure we are considered reachable
1642 pthread_mutex_unlock(&mesh->mutex);
1646 void meshlink_stop(meshlink_handle_t *mesh) {
1647 logger(mesh, MESHLINK_DEBUG, "meshlink_stop()\n");
1650 meshlink_errno = MESHLINK_EINVAL;
1654 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1658 // Shut down the main thread
1659 event_loop_stop(&mesh->loop);
1661 // Send ourselves a UDP packet to kick the event loop
1662 for(int i = 0; i < mesh->listen_sockets; i++) {
1664 socklen_t salen = sizeof(sa);
1666 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1667 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1671 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1672 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1676 if(mesh->threadstarted) {
1677 // Wait for the main thread to finish
1678 pthread_mutex_unlock(&mesh->mutex);
1680 if(pthread_join(mesh->thread, NULL) != 0) {
1684 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1688 mesh->threadstarted = false;
1691 // Close all metaconnections
1692 if(mesh->connections) {
1693 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1695 connection_t *c = node->data;
1697 terminate_connection(mesh, c, false);
1702 exit_outgoings(mesh);
1704 // Ensure we are considered unreachable
1709 // Try to write out any changed node config files, ignore errors at this point.
1711 for splay_each(node_t, n, mesh->nodes) {
1712 if(n->status.dirty) {
1713 if(!node_write_config(mesh, n, false)) {
1720 pthread_mutex_unlock(&mesh->mutex);
1723 void meshlink_close(meshlink_handle_t *mesh) {
1724 logger(mesh, MESHLINK_DEBUG, "meshlink_close()\n");
1727 meshlink_errno = MESHLINK_EINVAL;
1731 // stop can be called even if mesh has not been started
1732 meshlink_stop(mesh);
1734 // lock is not released after this
1735 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1739 // Close and free all resources used.
1741 close_network_connections(mesh);
1743 logger(mesh, MESHLINK_INFO, "Terminating");
1745 event_loop_exit(&mesh->loop);
1749 if(mesh->confbase) {
1755 if(mesh->netns != -1) {
1759 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1763 meshlink_queue_exit(&mesh->outpacketqueue);
1766 free(mesh->appname);
1767 free(mesh->confbase);
1768 free(mesh->config_key);
1769 free(mesh->external_address_url);
1771 ecdsa_free(mesh->private_key);
1773 main_config_unlock(mesh);
1775 pthread_mutex_unlock(&mesh->mutex);
1776 pthread_mutex_destroy(&mesh->mutex);
1778 memset(mesh, 0, sizeof(*mesh));
1783 bool meshlink_destroy_ex(const meshlink_open_params_t *params) {
1784 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy_ex()\n");
1787 meshlink_errno = MESHLINK_EINVAL;
1791 if(!params->confbase) {
1792 /* Ephemeral instances */
1796 /* Exit early if the confbase directory itself doesn't exist */
1797 if(access(params->confbase, F_OK) && errno == ENOENT) {
1801 /* Take the lock the same way meshlink_open() would. */
1802 FILE *lockfile = fopen(params->lock_filename, "w+");
1805 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", params->lock_filename, strerror(errno));
1806 meshlink_errno = MESHLINK_ESTORAGE;
1811 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1815 // TODO: use _locking()?
1818 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1819 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", params->lock_filename);
1821 meshlink_errno = MESHLINK_EBUSY;
1827 if(!config_destroy(params->confbase, "current") || !config_destroy(params->confbase, "new") || !config_destroy(params->confbase, "old")) {
1828 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", params->confbase, strerror(errno));
1832 if(unlink(params->lock_filename)) {
1833 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", params->lock_filename, strerror(errno));
1835 meshlink_errno = MESHLINK_ESTORAGE;
1841 if(!sync_path(params->confbase)) {
1842 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", params->confbase, strerror(errno));
1843 meshlink_errno = MESHLINK_ESTORAGE;
1850 bool meshlink_destroy(const char *confbase) {
1851 logger(NULL, MESHLINK_DEBUG, "meshlink_destroy(%s)", confbase);
1853 char lock_filename[PATH_MAX];
1854 snprintf(lock_filename, sizeof(lock_filename), "%s" SLASH "meshlink.lock", confbase);
1856 meshlink_open_params_t params = {
1857 .confbase = (char *)confbase,
1858 .lock_filename = lock_filename,
1861 return meshlink_destroy_ex(¶ms);
1864 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1865 logger(mesh, MESHLINK_DEBUG, "meshlink_set_receive_cb(%p)", (void *)(intptr_t)cb);
1868 meshlink_errno = MESHLINK_EINVAL;
1872 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1876 mesh->receive_cb = cb;
1877 pthread_mutex_unlock(&mesh->mutex);
1880 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1881 logger(mesh, MESHLINK_DEBUG, "meshlink_set_connection_try_cb(%p)", (void *)(intptr_t)cb);
1884 meshlink_errno = MESHLINK_EINVAL;
1888 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1892 mesh->connection_try_cb = cb;
1893 pthread_mutex_unlock(&mesh->mutex);
1896 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1897 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_status_cb(%p)", (void *)(intptr_t)cb);
1900 meshlink_errno = MESHLINK_EINVAL;
1904 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1908 mesh->node_status_cb = cb;
1909 pthread_mutex_unlock(&mesh->mutex);
1912 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1913 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_pmtu_cb(%p)", (void *)(intptr_t)cb);
1916 meshlink_errno = MESHLINK_EINVAL;
1920 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1924 mesh->node_pmtu_cb = cb;
1925 pthread_mutex_unlock(&mesh->mutex);
1928 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1929 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_duplicate_cb(%p)", (void *)(intptr_t)cb);
1932 meshlink_errno = MESHLINK_EINVAL;
1936 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1940 mesh->node_duplicate_cb = cb;
1941 pthread_mutex_unlock(&mesh->mutex);
1944 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1945 logger(mesh, MESHLINK_DEBUG, "meshlink_set_log_cb(%p)", (void *)(intptr_t)cb);
1948 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1953 mesh->log_level = cb ? level : 0;
1954 pthread_mutex_unlock(&mesh->mutex);
1957 global_log_level = cb ? level : 0;
1961 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1962 logger(mesh, MESHLINK_DEBUG, "meshlink_set_error_cb(%p)", (void *)(intptr_t)cb);
1965 meshlink_errno = MESHLINK_EINVAL;
1969 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1973 mesh->error_cb = cb;
1974 pthread_mutex_unlock(&mesh->mutex);
1977 void meshlink_set_blacklisted_cb(struct meshlink_handle *mesh, meshlink_blacklisted_cb_t cb) {
1978 logger(mesh, MESHLINK_DEBUG, "meshlink_set_blacklisted_cb(%p)", (void *)(intptr_t)cb);
1981 meshlink_errno = MESHLINK_EINVAL;
1985 if(pthread_mutex_lock(&mesh->mutex) != 0) {
1989 mesh->blacklisted_cb = cb;
1990 pthread_mutex_unlock(&mesh->mutex);
1993 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1994 meshlink_packethdr_t *hdr;
1996 if(len > MAXSIZE - sizeof(*hdr)) {
1997 meshlink_errno = MESHLINK_EINVAL;
2001 node_t *n = (node_t *)destination;
2003 if(n->status.blacklisted) {
2004 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
2005 meshlink_errno = MESHLINK_EBLACKLISTED;
2009 // Prepare the packet
2010 packet->probe = false;
2011 packet->tcp = false;
2012 packet->len = len + sizeof(*hdr);
2014 hdr = (meshlink_packethdr_t *)packet->data;
2015 memset(hdr, 0, sizeof(*hdr));
2016 // leave the last byte as 0 to make sure strings are always
2017 // null-terminated if they are longer than the buffer
2018 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
2019 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
2021 memcpy(packet->data + sizeof(*hdr), data, len);
2026 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2028 assert(destination);
2032 // Prepare the packet
2033 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2037 // Send it immediately
2038 route(mesh, mesh->self, mesh->packet);
2043 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2044 logger(mesh, MESHLINK_DEBUG, "meshlink_send(%s, %p, %zu)", destination ? destination->name : "(null)", data, len);
2046 // Validate arguments
2047 if(!mesh || !destination) {
2048 meshlink_errno = MESHLINK_EINVAL;
2057 meshlink_errno = MESHLINK_EINVAL;
2061 // Prepare the packet
2062 vpn_packet_t *packet = malloc(sizeof(*packet));
2065 meshlink_errno = MESHLINK_ENOMEM;
2069 if(!prepare_packet(mesh, destination, data, len, packet)) {
2075 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2077 meshlink_errno = MESHLINK_ENOMEM;
2081 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2083 // Notify event loop
2084 signal_trigger(&mesh->loop, &mesh->datafromapp);
2089 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2091 meshlink_handle_t *mesh = data;
2093 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2095 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2096 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2097 mesh->self->in_packets++;
2098 mesh->self->in_bytes += packet->len;
2099 route(mesh, mesh->self, packet);
2104 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2105 if(!mesh || !destination) {
2106 meshlink_errno = MESHLINK_EINVAL;
2110 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2114 node_t *n = (node_t *)destination;
2116 if(!n->status.reachable) {
2117 pthread_mutex_unlock(&mesh->mutex);
2120 } else if(n->mtuprobes > 30 && n->minmtu) {
2121 pthread_mutex_unlock(&mesh->mutex);
2124 pthread_mutex_unlock(&mesh->mutex);
2129 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2130 if(!mesh || !node) {
2131 meshlink_errno = MESHLINK_EINVAL;
2135 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2139 node_t *n = (node_t *)node;
2141 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2142 meshlink_errno = MESHLINK_EINTERNAL;
2143 pthread_mutex_unlock(&mesh->mutex);
2147 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2150 meshlink_errno = MESHLINK_EINTERNAL;
2153 pthread_mutex_unlock(&mesh->mutex);
2157 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2159 meshlink_errno = MESHLINK_EINVAL;
2163 return (meshlink_node_t *)mesh->self;
2166 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2167 if(!mesh || !name) {
2168 meshlink_errno = MESHLINK_EINVAL;
2174 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2178 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2179 pthread_mutex_unlock(&mesh->mutex);
2182 meshlink_errno = MESHLINK_ENOENT;
2185 return (meshlink_node_t *)n;
2188 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2189 if(!mesh || !name) {
2190 meshlink_errno = MESHLINK_EINVAL;
2194 meshlink_submesh_t *submesh = NULL;
2196 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2200 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2201 pthread_mutex_unlock(&mesh->mutex);
2204 meshlink_errno = MESHLINK_ENOENT;
2210 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2211 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2212 meshlink_errno = MESHLINK_EINVAL;
2216 meshlink_node_t **result;
2219 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2223 *nmemb = mesh->nodes->count;
2224 result = realloc(nodes, *nmemb * sizeof(*nodes));
2227 meshlink_node_t **p = result;
2229 for splay_each(node_t, n, mesh->nodes) {
2230 *p++ = (meshlink_node_t *)n;
2235 meshlink_errno = MESHLINK_ENOMEM;
2238 pthread_mutex_unlock(&mesh->mutex);
2243 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) {
2244 meshlink_node_t **result;
2246 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2252 for splay_each(node_t, n, mesh->nodes) {
2253 if(search_node(n, condition)) {
2260 pthread_mutex_unlock(&mesh->mutex);
2264 result = realloc(nodes, *nmemb * sizeof(*nodes));
2267 meshlink_node_t **p = result;
2269 for splay_each(node_t, n, mesh->nodes) {
2270 if(search_node(n, condition)) {
2271 *p++ = (meshlink_node_t *)n;
2277 meshlink_errno = MESHLINK_ENOMEM;
2280 pthread_mutex_unlock(&mesh->mutex);
2285 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2286 dev_class_t *devclass = (dev_class_t *)condition;
2288 if(*devclass == (dev_class_t)node->devclass) {
2295 static bool search_node_by_blacklisted(const node_t *node, const void *condition) {
2296 return *(bool *)condition == node->status.blacklisted;
2299 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2300 if(condition == node->submesh) {
2312 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2313 const struct time_range *range = condition;
2314 time_t start = node->last_reachable;
2315 time_t end = node->last_unreachable;
2325 if(range->end >= range->start) {
2326 return start <= range->end && end >= range->start;
2328 return start > range->start || end < range->end;
2332 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) {
2333 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2334 meshlink_errno = MESHLINK_EINVAL;
2338 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2341 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2342 if(!mesh || !submesh || !nmemb) {
2343 meshlink_errno = MESHLINK_EINVAL;
2347 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2350 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) {
2351 if(!mesh || !nmemb) {
2352 meshlink_errno = MESHLINK_EINVAL;
2356 struct time_range range = {start, end};
2358 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2361 meshlink_node_t **meshlink_get_all_nodes_by_blacklisted(meshlink_handle_t *mesh, bool blacklisted, meshlink_node_t **nodes, size_t *nmemb) {
2362 if(!mesh || !nmemb) {
2363 meshlink_errno = MESHLINK_EINVAL;
2367 return meshlink_get_all_nodes_by_condition(mesh, &blacklisted, nodes, nmemb, search_node_by_blacklisted);
2370 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2371 if(!mesh || !node) {
2372 meshlink_errno = MESHLINK_EINVAL;
2376 dev_class_t devclass;
2378 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2382 devclass = ((node_t *)node)->devclass;
2384 pthread_mutex_unlock(&mesh->mutex);
2389 bool meshlink_get_node_blacklisted(meshlink_handle_t *mesh, meshlink_node_t *node) {
2391 meshlink_errno = MESHLINK_EINVAL;
2395 return mesh->default_blacklist;
2400 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2404 blacklisted = ((node_t *)node)->status.blacklisted;
2406 pthread_mutex_unlock(&mesh->mutex);
2411 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2412 if(!mesh || !node) {
2413 meshlink_errno = MESHLINK_EINVAL;
2417 node_t *n = (node_t *)node;
2419 meshlink_submesh_t *s;
2421 s = (meshlink_submesh_t *)n->submesh;
2426 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2427 if(!mesh || !node) {
2428 meshlink_errno = MESHLINK_EINVAL;
2432 node_t *n = (node_t *)node;
2435 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2439 reachable = n->status.reachable && !n->status.blacklisted;
2441 if(last_reachable) {
2442 *last_reachable = n->last_reachable;
2445 if(last_unreachable) {
2446 *last_unreachable = n->last_unreachable;
2449 pthread_mutex_unlock(&mesh->mutex);
2454 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2455 logger(mesh, MESHLINK_DEBUG, "meshlink_sign(%p, %zu, %p, %p)", data, len, signature, (void *)siglen);
2457 if(!mesh || !data || !len || !signature || !siglen) {
2458 meshlink_errno = MESHLINK_EINVAL;
2462 if(*siglen < MESHLINK_SIGLEN) {
2463 meshlink_errno = MESHLINK_EINVAL;
2467 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2471 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2472 meshlink_errno = MESHLINK_EINTERNAL;
2473 pthread_mutex_unlock(&mesh->mutex);
2477 *siglen = MESHLINK_SIGLEN;
2478 pthread_mutex_unlock(&mesh->mutex);
2482 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2483 logger(mesh, MESHLINK_DEBUG, "meshlink_verify(%p, %zu, %p, %zu)", data, len, signature, siglen);
2485 if(!mesh || !source || !data || !len || !signature) {
2486 meshlink_errno = MESHLINK_EINVAL;
2490 if(siglen != MESHLINK_SIGLEN) {
2491 meshlink_errno = MESHLINK_EINVAL;
2495 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2501 struct node_t *n = (struct node_t *)source;
2503 if(!node_read_public_key(mesh, n)) {
2504 meshlink_errno = MESHLINK_EINTERNAL;
2507 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2510 pthread_mutex_unlock(&mesh->mutex);
2514 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2515 logger(mesh, MESHLINK_DEBUG, "meshlink_set_canonical_address(%s, %s, %s)", node ? node->name : "(null)", address ? address : "(null)", port ? port : "(null)");
2517 if(!mesh || !node || !address) {
2518 meshlink_errno = MESHLINK_EINVAL;
2522 if(!is_valid_hostname(address)) {
2523 logger(mesh, MESHLINK_ERROR, "Invalid character in address: %s", address);
2524 meshlink_errno = MESHLINK_EINVAL;
2528 if((node_t *)node != mesh->self && !port) {
2529 logger(mesh, MESHLINK_ERROR, "Missing port number!");
2530 meshlink_errno = MESHLINK_EINVAL;
2535 if(port && !is_valid_port(port)) {
2536 logger(mesh, MESHLINK_ERROR, "Invalid character in port: %s", address);
2537 meshlink_errno = MESHLINK_EINVAL;
2541 char *canonical_address;
2543 xasprintf(&canonical_address, "%s %s", address, port ? port : mesh->myport);
2545 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2549 node_t *n = (node_t *)node;
2550 free(n->canonical_address);
2551 n->canonical_address = canonical_address;
2553 if(!node_write_config(mesh, n, false)) {
2554 pthread_mutex_unlock(&mesh->mutex);
2558 pthread_mutex_unlock(&mesh->mutex);
2560 return config_sync(mesh, "current");
2563 bool meshlink_clear_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node) {
2564 logger(mesh, MESHLINK_DEBUG, "meshlink_clear_canonical_address(%s)", node ? node->name : "(null)");
2566 if(!mesh || !node) {
2567 meshlink_errno = MESHLINK_EINVAL;
2571 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2575 node_t *n = (node_t *)node;
2576 free(n->canonical_address);
2577 n->canonical_address = NULL;
2579 if(!node_write_config(mesh, n, false)) {
2580 pthread_mutex_unlock(&mesh->mutex);
2584 pthread_mutex_unlock(&mesh->mutex);
2586 return config_sync(mesh, "current");
2589 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2590 logger(mesh, MESHLINK_DEBUG, "meshlink_add_address(%s)", address ? address : "(null)");
2592 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2595 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2596 logger(mesh, MESHLINK_DEBUG, "meshlink_add_external_address()");
2599 meshlink_errno = MESHLINK_EINVAL;
2603 char *address = meshlink_get_external_address(mesh);
2609 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2615 int meshlink_get_port(meshlink_handle_t *mesh) {
2617 meshlink_errno = MESHLINK_EINVAL;
2622 meshlink_errno = MESHLINK_EINTERNAL;
2628 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2632 port = atoi(mesh->myport);
2633 pthread_mutex_unlock(&mesh->mutex);
2638 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2639 logger(mesh, MESHLINK_DEBUG, "meshlink_set_port(%d)", port);
2641 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2642 meshlink_errno = MESHLINK_EINVAL;
2646 if(mesh->myport && port == atoi(mesh->myport)) {
2650 if(!try_bind(mesh, port)) {
2651 meshlink_errno = MESHLINK_ENETWORK;
2655 devtool_trybind_probe();
2659 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2663 if(mesh->threadstarted) {
2664 meshlink_errno = MESHLINK_EINVAL;
2669 xasprintf(&mesh->myport, "%d", port);
2671 /* Close down the network. This also deletes mesh->self. */
2672 close_network_connections(mesh);
2674 /* Recreate mesh->self. */
2675 mesh->self = new_node();
2676 mesh->self->name = xstrdup(mesh->name);
2677 mesh->self->devclass = mesh->devclass;
2678 mesh->self->session_id = mesh->session_id;
2679 xasprintf(&mesh->myport, "%d", port);
2681 if(!node_read_public_key(mesh, mesh->self)) {
2682 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2683 meshlink_errno = MESHLINK_ESTORAGE;
2684 free_node(mesh->self);
2687 } else if(!setup_network(mesh)) {
2688 meshlink_errno = MESHLINK_ENETWORK;
2692 /* Rebuild our own list of recent addresses */
2693 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2694 add_local_addresses(mesh);
2696 /* Write meshlink.conf with the updated port number */
2697 write_main_config_files(mesh);
2699 rval = config_sync(mesh, "current");
2702 pthread_mutex_unlock(&mesh->mutex);
2704 return rval && meshlink_get_port(mesh) == port;
2707 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2708 logger(mesh, MESHLINK_DEBUG, "meshlink_join(%s)", invitation ? invitation : "(null)");
2710 if(!mesh || !invitation) {
2711 meshlink_errno = MESHLINK_EINVAL;
2715 if(mesh->storage_policy == MESHLINK_STORAGE_DISABLED) {
2716 meshlink_errno = MESHLINK_EINVAL;
2720 join_state_t state = {
2725 ecdsa_t *key = NULL;
2726 ecdsa_t *hiskey = NULL;
2728 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2729 char copy[strlen(invitation) + 1];
2731 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2735 //Before doing meshlink_join make sure we are not connected to another mesh
2736 if(mesh->threadstarted) {
2737 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2738 meshlink_errno = MESHLINK_EINVAL;
2742 // 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.
2743 if(mesh->nodes->count > 1) {
2744 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2745 meshlink_errno = MESHLINK_EINVAL;
2749 strcpy(copy, invitation);
2751 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2753 char *slash = strchr(copy, '/');
2761 if(strlen(slash) != 48) {
2765 char *address = copy;
2768 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2772 if(mesh->inviter_commits_first) {
2773 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2776 // Generate a throw-away key for the invitation.
2777 key = ecdsa_generate();
2780 meshlink_errno = MESHLINK_EINTERNAL;
2784 char *b64key = ecdsa_get_base64_public_key(key);
2787 while(address && *address) {
2788 // We allow commas in the address part to support multiple addresses in one invitation URL.
2789 comma = strchr(address, ',');
2795 // Split of the port
2796 port = strrchr(address, ':');
2804 // IPv6 address are enclosed in brackets, per RFC 3986
2805 if(*address == '[') {
2807 char *bracket = strchr(address, ']');
2820 // Connect to the meshlink daemon mentioned in the URL.
2821 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), SOCK_STREAM, 30);
2824 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2825 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
2827 if(state.sock == -1) {
2828 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2829 meshlink_errno = MESHLINK_ENETWORK;
2835 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
2838 set_timeout(state.sock, 5000);
2840 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2841 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2842 meshlink_errno = MESHLINK_ENETWORK;
2843 closesocket(state.sock);
2853 meshlink_errno = MESHLINK_ERESOLV;
2856 if(state.sock != -1 || !comma) {
2863 if(state.sock == -1) {
2867 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2869 // Tell him we have an invitation, and give him our throw-away key.
2873 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2874 logger(mesh, MESHLINK_ERROR, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2875 meshlink_errno = MESHLINK_ENETWORK;
2881 char hisname[4096] = "";
2882 int code, hismajor, hisminor = 0;
2884 if(!recvline(&state) || sscanf(state.line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(&state) || !rstrip(state.line) || sscanf(state.line, "%d ", &code) != 1 || code != ACK || strlen(state.line) < 3) {
2885 logger(mesh, MESHLINK_ERROR, "Cannot read greeting from peer\n");
2886 meshlink_errno = MESHLINK_ENETWORK;
2890 // Check if the hash of the key he gave us matches the hash in the URL.
2891 char *fingerprint = state.line + 2;
2894 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2895 logger(mesh, MESHLINK_ERROR, "Could not create hash\n%s\n", state.line + 2);
2896 meshlink_errno = MESHLINK_EINTERNAL;
2900 if(memcmp(hishash, state.hash, 18)) {
2901 logger(mesh, MESHLINK_ERROR, "Peer has an invalid key!\n%s\n", state.line + 2);
2902 meshlink_errno = MESHLINK_EPEER;
2906 hiskey = ecdsa_set_base64_public_key(fingerprint);
2909 meshlink_errno = MESHLINK_EINTERNAL;
2913 // Start an SPTPS session
2914 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2915 meshlink_errno = MESHLINK_EINTERNAL;
2919 // Feed rest of input buffer to SPTPS
2920 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2921 meshlink_errno = MESHLINK_EPEER;
2926 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2928 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2930 if(errno == EINTR) {
2934 logger(mesh, MESHLINK_ERROR, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2935 meshlink_errno = MESHLINK_ENETWORK;
2939 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2940 meshlink_errno = MESHLINK_EPEER;
2945 if(!state.success) {
2946 logger(mesh, MESHLINK_ERROR, "Connection closed by peer, invitation cancelled.\n");
2947 meshlink_errno = MESHLINK_EPEER;
2951 sptps_stop(&state.sptps);
2954 closesocket(state.sock);
2956 pthread_mutex_unlock(&mesh->mutex);
2960 logger(mesh, MESHLINK_ERROR, "Invalid invitation URL\n");
2961 meshlink_errno = MESHLINK_EINVAL;
2963 sptps_stop(&state.sptps);
2967 if(state.sock != -1) {
2968 closesocket(state.sock);
2971 pthread_mutex_unlock(&mesh->mutex);
2975 char *meshlink_export(meshlink_handle_t *mesh) {
2977 meshlink_errno = MESHLINK_EINVAL;
2981 // Create a config file on the fly.
2984 packmsg_output_t out = {buf, sizeof(buf)};
2985 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2986 packmsg_add_str(&out, mesh->name);
2987 packmsg_add_str(&out, CORE_MESH);
2989 if(pthread_mutex_lock(&mesh->mutex) != 0) {
2993 packmsg_add_int32(&out, mesh->self->devclass);
2994 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2995 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2997 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
2998 char *canonical_address = NULL;
2999 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
3000 packmsg_add_str(&out, canonical_address);
3001 free(canonical_address);
3003 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3008 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3009 if(mesh->self->recent[i].sa.sa_family) {
3016 packmsg_add_array(&out, count);
3018 for(uint32_t i = 0; i < count; i++) {
3019 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3022 packmsg_add_int64(&out, 0);
3023 packmsg_add_int64(&out, 0);
3025 pthread_mutex_unlock(&mesh->mutex);
3027 if(!packmsg_output_ok(&out)) {
3028 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
3029 meshlink_errno = MESHLINK_EINTERNAL;
3033 // Prepare a base64-encoded packmsg array containing our config file
3035 uint32_t len = packmsg_output_size(&out, buf);
3036 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3037 uint8_t *buf2 = xmalloc(len2);
3038 packmsg_output_t out2 = {buf2, len2};
3039 packmsg_add_array(&out2, 1);
3040 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3042 if(!packmsg_output_ok(&out2)) {
3043 logger(mesh, MESHLINK_ERROR, "Error creating export data\n");
3044 meshlink_errno = MESHLINK_EINTERNAL;
3049 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3051 return (char *)buf2;
3054 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3055 logger(mesh, MESHLINK_DEBUG, "meshlink_import(%p)", (const void *)data);
3057 if(!mesh || !data) {
3058 meshlink_errno = MESHLINK_EINVAL;
3062 size_t datalen = strlen(data);
3063 uint8_t *buf = xmalloc(datalen);
3064 int buflen = b64decode(data, buf, datalen);
3067 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3069 meshlink_errno = MESHLINK_EPEER;
3073 packmsg_input_t in = {buf, buflen};
3074 uint32_t count = packmsg_get_array(&in);
3077 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3079 meshlink_errno = MESHLINK_EPEER;
3083 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3089 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
3095 packmsg_input_t in2 = {data2, len2};
3096 uint32_t version = packmsg_get_uint32(&in2);
3097 char *name = packmsg_get_str_dup(&in2);
3099 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3101 packmsg_input_invalidate(&in);
3105 if(!check_id(name)) {
3110 node_t *n = lookup_node(mesh, name);
3113 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3121 config_t config = {data2, len2};
3123 if(!node_read_from_config(mesh, n, &config)) {
3125 packmsg_input_invalidate(&in);
3129 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3130 n->last_reachable = 0;
3131 n->last_unreachable = 0;
3133 if(!node_write_config(mesh, n, true)) {
3142 pthread_mutex_unlock(&mesh->mutex);
3146 if(!packmsg_done(&in)) {
3147 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3148 meshlink_errno = MESHLINK_EPEER;
3152 if(!config_sync(mesh, "current")) {
3159 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3160 if(n == mesh->self) {
3161 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3162 meshlink_errno = MESHLINK_EINVAL;
3166 if(n->status.blacklisted) {
3167 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3171 n->status.blacklisted = true;
3173 /* Immediately shut down any connections we have with the blacklisted node.
3174 * We can't call terminate_connection(), because we might be called from a callback function.
3176 for list_each(connection_t, c, mesh->connections) {
3178 if(c->status.active) {
3179 send_error(mesh, c, BLACKLISTED, "blacklisted");
3182 shutdown(c->socket, SHUT_RDWR);
3186 utcp_reset_all_connections(n->utcp);
3192 n->status.udp_confirmed = false;
3194 if(n->status.reachable) {
3195 n->last_unreachable = time(NULL);
3198 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3199 * manually call the status callback if necessary.
3201 if(n->status.reachable && mesh->node_status_cb) {
3202 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3205 return node_write_config(mesh, n, true) && config_sync(mesh, "current");
3208 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3209 logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist(%s)", node ? node->name : "(null)");
3211 if(!mesh || !node) {
3212 meshlink_errno = MESHLINK_EINVAL;
3216 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3220 if(!blacklist(mesh, (node_t *)node)) {
3221 pthread_mutex_unlock(&mesh->mutex);
3225 pthread_mutex_unlock(&mesh->mutex);
3227 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3231 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3232 logger(mesh, MESHLINK_DEBUG, "meshlink_blacklist_by_name(%s)", name ? name : "(null)");
3234 if(!mesh || !name) {
3235 meshlink_errno = MESHLINK_EINVAL;
3239 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3243 node_t *n = lookup_node(mesh, (char *)name);
3247 n->name = xstrdup(name);
3251 if(!blacklist(mesh, (node_t *)n)) {
3252 pthread_mutex_unlock(&mesh->mutex);
3256 pthread_mutex_unlock(&mesh->mutex);
3258 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3262 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3263 if(n == mesh->self) {
3264 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3265 meshlink_errno = MESHLINK_EINVAL;
3269 if(!n->status.blacklisted) {
3270 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3274 n->status.blacklisted = false;
3276 if(n->status.reachable) {
3277 n->last_reachable = time(NULL);
3278 update_node_status(mesh, n);
3281 return node_write_config(mesh, n, true) && config_sync(mesh, "current");
3284 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3285 logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist(%s)", node ? node->name : "(null)");
3287 if(!mesh || !node) {
3288 meshlink_errno = MESHLINK_EINVAL;
3292 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3296 if(!whitelist(mesh, (node_t *)node)) {
3297 pthread_mutex_unlock(&mesh->mutex);
3301 pthread_mutex_unlock(&mesh->mutex);
3303 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3307 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3308 logger(mesh, MESHLINK_DEBUG, "meshlink_whitelist_by_name(%s)", name ? name : "(null)");
3310 if(!mesh || !name) {
3311 meshlink_errno = MESHLINK_EINVAL;
3315 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3319 node_t *n = lookup_node(mesh, (char *)name);
3323 n->name = xstrdup(name);
3327 if(!whitelist(mesh, (node_t *)n)) {
3328 pthread_mutex_unlock(&mesh->mutex);
3332 pthread_mutex_unlock(&mesh->mutex);
3334 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3338 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3339 mesh->default_blacklist = blacklist;
3342 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3343 logger(mesh, MESHLINK_DEBUG, "meshlink_forget_node(%s)", node ? node->name : "(null)");
3345 if(!mesh || !node) {
3346 meshlink_errno = MESHLINK_EINVAL;
3350 node_t *n = (node_t *)node;
3352 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3356 /* Check that the node is not reachable */
3357 if(n->status.reachable || n->connection) {
3358 pthread_mutex_unlock(&mesh->mutex);
3359 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3363 /* Check that we don't have any active UTCP connections */
3364 if(n->utcp && utcp_is_active(n->utcp)) {
3365 pthread_mutex_unlock(&mesh->mutex);
3366 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3370 /* Check that we have no active connections to this node */
3371 for list_each(connection_t, c, mesh->connections) {
3373 pthread_mutex_unlock(&mesh->mutex);
3374 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3379 /* Remove any pending outgoings to this node */
3380 if(mesh->outgoings) {
3381 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3382 if(outgoing->node == n) {
3383 list_delete_node(mesh->outgoings, list_node);
3388 /* Delete the config file for this node */
3389 if(!config_delete(mesh, "current", n->name)) {
3390 pthread_mutex_unlock(&mesh->mutex);
3394 /* Delete the node struct and any remaining edges referencing this node */
3397 pthread_mutex_unlock(&mesh->mutex);
3399 return config_sync(mesh, "current");
3402 /* Hint that a hostname may be found at an address
3403 * See header file for detailed comment.
3405 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3406 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_address(%s, %p)", node ? node->name : "(null)", (const void *)addr);
3408 if(!mesh || !node || !addr) {
3409 meshlink_errno = EINVAL;
3413 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3417 node_t *n = (node_t *)node;
3419 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3420 if(!node_write_config(mesh, n, false)) {
3421 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3425 pthread_mutex_unlock(&mesh->mutex);
3426 // @TODO do we want to fire off a connection attempt right away?
3429 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3431 node_t *n = utcp->priv;
3432 meshlink_handle_t *mesh = n->mesh;
3434 if(mesh->channel_accept_cb && mesh->channel_listen_cb) {
3435 return mesh->channel_listen_cb(mesh, (meshlink_node_t *)n, port);
3437 return mesh->channel_accept_cb;
3441 /* Finish one AIO buffer, return true if the channel is still open. */
3442 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3443 meshlink_aio_buffer_t *aio = *head;
3447 channel->in_callback = true;
3450 if(aio->cb.buffer) {
3451 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
3455 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3459 channel->in_callback = false;
3472 /* Finish all AIO buffers, return true if the channel is still open. */
3473 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3475 if(!aio_finish_one(mesh, channel, head)) {
3483 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3484 meshlink_channel_t *channel = connection->priv;
3490 node_t *n = channel->node;
3491 meshlink_handle_t *mesh = n->mesh;
3493 if(n->status.destroyed) {
3494 meshlink_channel_close(mesh, channel);
3498 const char *p = data;
3501 while(channel->aio_receive) {
3503 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
3504 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
3511 meshlink_aio_buffer_t *aio = channel->aio_receive;
3512 size_t todo = aio->len - aio->done;
3519 memcpy((char *)aio->data + aio->done, p, todo);
3521 ssize_t result = write(aio->fd, p, todo);
3524 if(result < 0 && errno == EINTR) {
3528 /* Writing to fd failed, cancel just this AIO buffer. */
3529 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
3531 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3545 if(aio->done == aio->len) {
3546 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3556 if(channel->receive_cb) {
3557 channel->receive_cb(mesh, channel, p, left);
3563 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3564 node_t *n = utcp_connection->utcp->priv;
3570 meshlink_handle_t *mesh = n->mesh;
3572 if(!mesh->channel_accept_cb) {
3576 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3578 channel->c = utcp_connection;
3580 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3581 utcp_accept(utcp_connection, channel_recv, channel);
3587 static void channel_retransmit(struct utcp_connection *utcp_connection) {
3588 node_t *n = utcp_connection->utcp->priv;
3589 meshlink_handle_t *mesh = n->mesh;
3591 if(n->mtuprobes == 31 && n->mtutimeout.cb) {
3592 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
3598 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3599 node_t *n = utcp->priv;
3601 if(n->status.destroyed) {
3605 meshlink_handle_t *mesh = n->mesh;
3606 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3609 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3610 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_receive_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
3612 if(!mesh || !channel) {
3613 meshlink_errno = MESHLINK_EINVAL;
3617 channel->receive_cb = cb;
3620 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3622 node_t *n = (node_t *)source;
3628 utcp_recv(n->utcp, data, len);
3631 static void channel_poll(struct utcp_connection *connection, size_t len) {
3632 meshlink_channel_t *channel = connection->priv;
3638 node_t *n = channel->node;
3639 meshlink_handle_t *mesh = n->mesh;
3641 while(channel->aio_send) {
3643 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
3644 if(!aio_abort(mesh, channel, &channel->aio_send)) {
3651 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
3652 meshlink_aio_buffer_t *aio = channel->aio_send;
3653 size_t todo = aio->len - aio->done;
3661 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
3663 /* Limit the amount we read at once to avoid stack overflows */
3669 ssize_t result = read(aio->fd, buf, todo);
3673 sent = utcp_send(connection, buf, todo);
3675 if(result < 0 && errno == EINTR) {
3679 /* Reading from fd failed, cancel just this AIO buffer. */
3681 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
3684 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
3692 if(sent != (ssize_t)todo) {
3693 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
3694 if(!aio_abort(mesh, channel, &channel->aio_send)) {
3705 /* If we didn't finish this buffer, exit early. */
3706 if(aio->done < aio->len) {
3710 /* Signal completion of this buffer, and go to the next one. */
3711 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
3720 if(channel->poll_cb) {
3721 channel->poll_cb(mesh, channel, len);
3723 utcp_set_poll_cb(connection, NULL);
3727 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3728 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_poll_cb(%p, %p)", (void *)channel, (void *)(intptr_t)cb);
3730 if(!mesh || !channel) {
3731 meshlink_errno = MESHLINK_EINVAL;
3735 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3739 channel->poll_cb = cb;
3740 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3741 pthread_mutex_unlock(&mesh->mutex);
3744 void meshlink_set_channel_listen_cb(meshlink_handle_t *mesh, meshlink_channel_listen_cb_t cb) {
3745 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_listen_cb(%p)", (void *)(intptr_t)cb);
3748 meshlink_errno = MESHLINK_EINVAL;
3752 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3756 mesh->channel_listen_cb = cb;
3758 pthread_mutex_unlock(&mesh->mutex);
3761 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3762 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_accept_cb(%p)", (void *)(intptr_t)cb);
3765 meshlink_errno = MESHLINK_EINVAL;
3769 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3773 mesh->channel_accept_cb = cb;
3774 mesh->receive_cb = channel_receive;
3776 for splay_each(node_t, n, mesh->nodes) {
3777 if(!n->utcp && n != mesh->self) {
3778 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3779 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3780 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3784 pthread_mutex_unlock(&mesh->mutex);
3787 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3788 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf(%p, %zu)", (void *)channel, size);
3790 meshlink_set_channel_sndbuf_storage(mesh, channel, NULL, size);
3793 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3794 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf(%p, %zu)", (void *)channel, size);
3796 meshlink_set_channel_rcvbuf_storage(mesh, channel, NULL, size);
3799 void meshlink_set_channel_sndbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
3800 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_sndbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
3802 if(!mesh || !channel) {
3803 meshlink_errno = MESHLINK_EINVAL;
3807 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3811 utcp_set_sndbuf(channel->c, buf, size);
3812 pthread_mutex_unlock(&mesh->mutex);
3815 void meshlink_set_channel_rcvbuf_storage(meshlink_handle_t *mesh, meshlink_channel_t *channel, void *buf, size_t size) {
3816 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_rcvbuf_storage(%p, %p, %zu)", (void *)channel, buf, size);
3818 if(!mesh || !channel) {
3819 meshlink_errno = MESHLINK_EINVAL;
3823 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3827 utcp_set_rcvbuf(channel->c, buf, size);
3828 pthread_mutex_unlock(&mesh->mutex);
3831 void meshlink_set_channel_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel, uint32_t flags) {
3832 logger(mesh, MESHLINK_DEBUG, "meshlink_set_channel_flags(%p, %u)", (void *)channel, flags);
3834 if(!mesh || !channel) {
3835 meshlink_errno = MESHLINK_EINVAL;
3839 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3843 utcp_set_flags(channel->c, flags);
3844 pthread_mutex_unlock(&mesh->mutex);
3847 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) {
3848 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu, %u)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len, flags);
3851 abort(); // TODO: handle non-NULL data
3854 if(!mesh || !node) {
3855 meshlink_errno = MESHLINK_EINVAL;
3859 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3863 node_t *n = (node_t *)node;
3866 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3867 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3868 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3869 mesh->receive_cb = channel_receive;
3872 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3873 pthread_mutex_unlock(&mesh->mutex);
3878 if(n->status.blacklisted) {
3879 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3880 meshlink_errno = MESHLINK_EBLACKLISTED;
3881 pthread_mutex_unlock(&mesh->mutex);
3885 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3887 channel->receive_cb = cb;
3890 channel->priv = (void *)data;
3893 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3895 pthread_mutex_unlock(&mesh->mutex);
3898 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3906 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) {
3907 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_open_ex(%s, %u, %p, %p, %zu)", node ? node->name : "(null)", port, (void *)(intptr_t)cb, data, len);
3909 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3912 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3913 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_shutdown(%p, %d)", (void *)channel, direction);
3915 if(!mesh || !channel) {
3916 meshlink_errno = MESHLINK_EINVAL;
3920 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3924 utcp_shutdown(channel->c, direction);
3925 pthread_mutex_unlock(&mesh->mutex);
3928 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3929 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_close(%p)", (void *)channel);
3931 if(!mesh || !channel) {
3932 meshlink_errno = MESHLINK_EINVAL;
3936 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3941 utcp_close(channel->c);
3944 /* Clean up any outstanding AIO buffers. */
3945 aio_abort(mesh, channel, &channel->aio_send);
3946 aio_abort(mesh, channel, &channel->aio_receive);
3949 if(!channel->in_callback) {
3953 pthread_mutex_unlock(&mesh->mutex);
3956 void meshlink_channel_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3957 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_abort(%p)", (void *)channel);
3959 if(!mesh || !channel) {
3960 meshlink_errno = MESHLINK_EINVAL;
3964 if(pthread_mutex_lock(&mesh->mutex) != 0) {
3969 utcp_abort(channel->c);
3972 /* Clean up any outstanding AIO buffers. */
3973 aio_abort(mesh, channel, &channel->aio_send);
3974 aio_abort(mesh, channel, &channel->aio_receive);
3977 if(!channel->in_callback) {
3981 pthread_mutex_unlock(&mesh->mutex);
3984 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3985 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_send(%p, %p, %zu)", (void *)channel, data, len);
3987 if(!mesh || !channel) {
3988 meshlink_errno = MESHLINK_EINVAL;
3997 meshlink_errno = MESHLINK_EINVAL;
4001 // TODO: more finegrained locking.
4002 // Ideally we want to put the data into the UTCP connection's send buffer.
4003 // Then, preferably only if there is room in the receiver window,
4004 // kick the meshlink thread to go send packets.
4008 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4012 /* Disallow direct calls to utcp_send() while we still have AIO active. */
4013 if(channel->aio_send) {
4016 retval = utcp_send(channel->c, data, len);
4019 pthread_mutex_unlock(&mesh->mutex);
4022 meshlink_errno = MESHLINK_ENETWORK;
4028 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) {
4029 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_send(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
4031 if(!mesh || !channel) {
4032 meshlink_errno = MESHLINK_EINVAL;
4037 meshlink_errno = MESHLINK_EINVAL;
4041 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4044 aio->cb.buffer = cb;
4047 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4051 /* Append the AIO buffer descriptor to the end of the chain */
4052 meshlink_aio_buffer_t **p = &channel->aio_send;
4060 /* Ensure the poll callback is set, and call it right now to push data if possible */
4061 utcp_set_poll_cb(channel->c, channel_poll);
4062 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
4065 channel_poll(channel->c, todo);
4068 pthread_mutex_unlock(&mesh->mutex);
4073 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) {
4074 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_send(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
4076 if(!mesh || !channel) {
4077 meshlink_errno = MESHLINK_EINVAL;
4081 if(!len || fd == -1) {
4082 meshlink_errno = MESHLINK_EINVAL;
4086 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4092 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4096 /* Append the AIO buffer descriptor to the end of the chain */
4097 meshlink_aio_buffer_t **p = &channel->aio_send;
4105 /* Ensure the poll callback is set, and call it right now to push data if possible */
4106 utcp_set_poll_cb(channel->c, channel_poll);
4107 size_t left = utcp_get_rcvbuf_free(channel->c);
4110 channel_poll(channel->c, left);
4113 pthread_mutex_unlock(&mesh->mutex);
4118 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) {
4119 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_receive(%p, %p, %zu, %p, %p)", (void *)channel, data, len, (void *)(intptr_t)cb, priv);
4121 if(!mesh || !channel) {
4122 meshlink_errno = MESHLINK_EINVAL;
4127 meshlink_errno = MESHLINK_EINVAL;
4131 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4134 aio->cb.buffer = cb;
4137 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4141 /* Append the AIO buffer descriptor to the end of the chain */
4142 meshlink_aio_buffer_t **p = &channel->aio_receive;
4150 pthread_mutex_unlock(&mesh->mutex);
4155 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) {
4156 logger(mesh, MESHLINK_DEBUG, "meshlink_channel_aio_fd_receive(%p, %d, %zu, %p, %p)", (void *)channel, fd, len, (void *)(intptr_t)cb, priv);
4158 if(!mesh || !channel) {
4159 meshlink_errno = MESHLINK_EINVAL;
4163 if(!len || fd == -1) {
4164 meshlink_errno = MESHLINK_EINVAL;
4168 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4174 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4178 /* Append the AIO buffer descriptor to the end of the chain */
4179 meshlink_aio_buffer_t **p = &channel->aio_receive;
4187 pthread_mutex_unlock(&mesh->mutex);
4192 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4193 if(!mesh || !channel) {
4194 meshlink_errno = MESHLINK_EINVAL;
4198 return channel->c->flags;
4201 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4202 if(!mesh || !channel) {
4203 meshlink_errno = MESHLINK_EINVAL;
4207 return utcp_get_sendq(channel->c);
4210 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4211 if(!mesh || !channel) {
4212 meshlink_errno = MESHLINK_EINVAL;
4216 return utcp_get_recvq(channel->c);
4219 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4220 if(!mesh || !channel) {
4221 meshlink_errno = MESHLINK_EINVAL;
4225 return utcp_get_mss(channel->node->utcp);
4228 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
4229 logger(mesh, MESHLINK_DEBUG, "meshlink_set_node_channel_timeout(%s, %d)", node ? node->name : "(null)", timeout);
4231 if(!mesh || !node) {
4232 meshlink_errno = MESHLINK_EINVAL;
4236 node_t *n = (node_t *)node;
4238 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4243 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4244 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4245 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4248 utcp_set_user_timeout(n->utcp, timeout);
4250 pthread_mutex_unlock(&mesh->mutex);
4253 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4254 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4255 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4256 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4257 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4260 if(mesh->node_status_cb) {
4261 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4264 if(mesh->node_pmtu_cb) {
4265 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4269 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4270 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4272 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4273 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4277 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4278 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4282 n->status.duplicate = true;
4283 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4286 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4287 logger(mesh, MESHLINK_DEBUG, "meshlink_enable_discovery(%d)", enable);
4290 meshlink_errno = MESHLINK_EINVAL;
4294 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4298 if(mesh->discovery.enabled == enable) {
4302 if(mesh->threadstarted) {
4304 discovery_start(mesh);
4306 discovery_stop(mesh);
4310 mesh->discovery.enabled = enable;
4313 pthread_mutex_unlock(&mesh->mutex);
4316 void meshlink_hint_network_change(struct meshlink_handle *mesh) {
4317 logger(mesh, MESHLINK_DEBUG, "meshlink_hint_network_change()");
4320 meshlink_errno = MESHLINK_EINVAL;
4324 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4328 if(mesh->discovery.enabled) {
4332 if(mesh->loop.now.tv_sec > mesh->discovery.last_update + 5) {
4333 mesh->discovery.last_update = mesh->loop.now.tv_sec;
4334 handle_network_change(mesh, 1);
4337 pthread_mutex_unlock(&mesh->mutex);
4340 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4341 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_timeouts(%d, %d, %d)", devclass, pinginterval, pingtimeout);
4343 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4344 meshlink_errno = EINVAL;
4348 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4349 meshlink_errno = EINVAL;
4353 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4357 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4358 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4359 pthread_mutex_unlock(&mesh->mutex);
4362 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4363 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_retry_period(%d, %d)", devclass, fast_retry_period);
4365 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4366 meshlink_errno = EINVAL;
4370 if(fast_retry_period < 0) {
4371 meshlink_errno = EINVAL;
4375 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4379 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4380 pthread_mutex_unlock(&mesh->mutex);
4383 void meshlink_set_dev_class_maxtimeout(struct meshlink_handle *mesh, dev_class_t devclass, int maxtimeout) {
4384 logger(mesh, MESHLINK_DEBUG, "meshlink_set_dev_class_fast_maxtimeout(%d, %d)", devclass, maxtimeout);
4386 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4387 meshlink_errno = EINVAL;
4391 if(maxtimeout < 0) {
4392 meshlink_errno = EINVAL;
4396 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4400 mesh->dev_class_traits[devclass].maxtimeout = maxtimeout;
4401 pthread_mutex_unlock(&mesh->mutex);
4404 void meshlink_reset_timers(struct meshlink_handle *mesh) {
4405 logger(mesh, MESHLINK_DEBUG, "meshlink_reset_timers()");
4411 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4415 handle_network_change(mesh, true);
4417 if(mesh->discovery.enabled) {
4418 discovery_refresh(mesh);
4421 pthread_mutex_unlock(&mesh->mutex);
4424 void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4425 logger(mesh, MESHLINK_DEBUG, "meshlink_set_inviter_commits_first(%d)", inviter_commits_first);
4428 meshlink_errno = EINVAL;
4432 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4436 mesh->inviter_commits_first = inviter_commits_first;
4437 pthread_mutex_unlock(&mesh->mutex);
4440 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4441 logger(mesh, MESHLINK_DEBUG, "meshlink_set_external_address_discovery_url(%s)", url ? url : "(null)");
4444 meshlink_errno = EINVAL;
4448 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4449 meshlink_errno = EINVAL;
4453 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4457 free(mesh->external_address_url);
4458 mesh->external_address_url = url ? xstrdup(url) : NULL;
4459 pthread_mutex_unlock(&mesh->mutex);
4462 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4463 logger(mesh, MESHLINK_DEBUG, "meshlink_set_scheduling_granularity(%ld)", granularity);
4465 if(!mesh || granularity < 0) {
4466 meshlink_errno = EINVAL;
4470 utcp_set_clock_granularity(granularity);
4473 void meshlink_set_storage_policy(struct meshlink_handle *mesh, meshlink_storage_policy_t policy) {
4474 logger(mesh, MESHLINK_DEBUG, "meshlink_set_storage_policy(%d)", policy);
4477 meshlink_errno = EINVAL;
4481 if(pthread_mutex_lock(&mesh->mutex) != 0) {
4485 mesh->storage_policy = policy;
4486 pthread_mutex_unlock(&mesh->mutex);
4489 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4492 if(!mesh->connections || !mesh->loop.running) {
4497 signal_trigger(&mesh->loop, &mesh->datafromapp);
4500 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
4501 // We should only call the callback function if we are in the background thread.
4502 if(!mesh->error_cb) {
4506 if(!mesh->threadstarted) {
4510 if(mesh->thread == pthread_self()) {
4511 mesh->error_cb(mesh, cb_errno);
4515 static void __attribute__((constructor)) meshlink_init(void) {
4517 utcp_set_clock_granularity(10000);
4520 static void __attribute__((destructor)) meshlink_exit(void) {