2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2018 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "meshlink_internal.h"
38 #include "ed25519/sha512.h"
39 #include "discovery.h"
44 #define MSG_NOSIGNAL 0
46 __thread meshlink_errno_t meshlink_errno;
47 meshlink_log_cb_t global_log_cb;
48 meshlink_log_level_t global_log_level;
50 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
52 static int rstrip(char *value) {
53 int len = strlen(value);
55 while(len && strchr("\t\r\n ", value[len - 1])) {
62 static void get_canonical_address(node_t *n, char **hostname, char **port) {
63 if(!n->canonical_address) {
67 *hostname = xstrdup(n->canonical_address);
68 char *space = strchr(*hostname, ' ');
72 *port = xstrdup(space);
76 static bool is_valid_hostname(const char *hostname) {
81 for(const char *p = hostname; *p; p++) {
82 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
90 static bool is_valid_port(const char *port) {
97 unsigned long int result = strtoul(port, &end, 10);
98 return result && result < 65536 && !*end;
101 for(const char *p = port; *p; p++) {
102 if(!(isalnum(*p) || *p == '-')) {
110 static void set_timeout(int sock, int timeout) {
115 tv.tv_sec = timeout / 1000;
116 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
118 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
119 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
122 struct socket_in_netns_params {
131 static void *socket_in_netns_thread(void *arg) {
132 struct socket_in_netns_params *params = arg;
134 if(setns(params->netns, CLONE_NEWNET) == -1) {
135 meshlink_errno = MESHLINK_EINVAL;
139 params->fd = socket(params->domain, params->type, params->protocol);
145 static int socket_in_netns(int domain, int type, int protocol, int netns) {
147 return socket(domain, type, protocol);
151 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
155 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
156 pthread_join(thr, NULL);
166 // Find out what local address a socket would use if we connect to the given address.
167 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
168 // of both endpoints, but this will actually not send any UDP packet.
169 static bool getlocaladdr(char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
170 struct addrinfo *rai = NULL;
171 const struct addrinfo hint = {
172 .ai_family = AF_UNSPEC,
173 .ai_socktype = SOCK_DGRAM,
174 .ai_protocol = IPPROTO_UDP,
177 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
181 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
188 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
196 if(getsockname(sock, &sa->sa, salen)) {
205 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
207 socklen_t salen = sizeof(sa);
209 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
213 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
220 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
221 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
224 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
225 const char *url = mesh->external_address_url;
228 url = "http://meshlink.io/host.cgi";
231 /* Find the hostname part between the slashes */
232 if(strncmp(url, "http://", 7)) {
234 meshlink_errno = MESHLINK_EINTERNAL;
238 const char *begin = url + 7;
240 const char *end = strchr(begin, '/');
243 end = begin + strlen(begin);
247 char host[end - begin + 1];
248 strncpy(host, begin, end - begin);
249 host[end - begin] = 0;
251 char *port = strchr(host, ':');
257 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
258 struct addrinfo *ai = str2addrinfo(host, port ? port : "80", SOCK_STREAM);
260 char *hostname = NULL;
262 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
263 if(family != AF_UNSPEC && aip->ai_family != family) {
267 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
270 set_timeout(s, 5000);
272 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
279 send(s, "GET ", 4, 0);
280 send(s, url, strlen(url), 0);
281 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
282 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
287 if(line[len - 1] == '\n') {
291 char *p = strrchr(line, '\n');
294 hostname = xstrdup(p + 1);
310 // Check that the hostname is reasonable
311 if(hostname && !is_valid_hostname(hostname)) {
317 meshlink_errno = MESHLINK_ERESOLV;
323 static bool is_localaddr(sockaddr_t *sa) {
324 switch(sa->sa.sa_family) {
326 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
329 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
330 return first == 0 || (first & 0xffc0) == 0xfe80;
338 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
341 // Determine address of the local interface used for outgoing connections.
342 char localaddr[NI_MAXHOST];
343 bool success = false;
345 if(family == AF_INET) {
346 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
347 } else if(family == AF_INET6) {
348 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
351 #ifdef HAVE_GETIFADDRS
354 struct ifaddrs *ifa = NULL;
357 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
358 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
360 if(sa->sa.sa_family != family) {
364 if(is_localaddr(sa)) {
368 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
380 meshlink_errno = MESHLINK_ENETWORK;
384 return xstrdup(localaddr);
387 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
388 for(int i = 0; i < n; i++) {
393 // Ignore duplicate hostnames
396 for(int j = 0; j < i; j++) {
401 if(strcmp(host[i], host[j])) {
405 if(strcmp(port[i], port[j])) {
413 if(found || !is_valid_hostname(host[i])) {
423 // This gets the hostname part for use in invitation URLs
424 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
425 int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
427 char *hostname[count];
429 char *hostport = NULL;
431 memset(hostname, 0, sizeof(hostname));
432 memset(port, 0, sizeof(port));
434 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
435 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
438 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
439 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
442 // Add all explicitly set invitation addresses
443 if(mesh->invitation_addresses) {
444 for list_each(char, combo, mesh->invitation_addresses) {
445 hostname[n] = xstrdup(combo);
446 char *slash = strrchr(hostname[n], '/');
450 port[n] = xstrdup(slash + 1);
457 // Add local addresses if requested
458 if(flags & MESHLINK_INVITE_LOCAL) {
459 if(flags & MESHLINK_INVITE_IPV4) {
460 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
463 if(flags & MESHLINK_INVITE_IPV6) {
464 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
468 // Add public/canonical addresses if requested
469 if(flags & MESHLINK_INVITE_PUBLIC) {
470 // Try the CanonicalAddress first
471 get_canonical_address(mesh->self, &hostname[n], &port[n]);
473 if(!hostname[n] && count == 4) {
474 if(flags & MESHLINK_INVITE_IPV4) {
475 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
478 if(flags & MESHLINK_INVITE_IPV6) {
479 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
486 for(int i = 0; i < n; i++) {
487 // Ensure we always have a port number
488 if(hostname[i] && !port[i]) {
489 port[i] = xstrdup(mesh->myport);
493 remove_duplicate_hostnames(hostname, port, n);
495 // Resolve the hostnames
496 for(int i = 0; i < n; i++) {
501 // Convert what we have to a sockaddr
502 struct addrinfo *ai_in, *ai_out;
503 struct addrinfo hint = {
504 .ai_family = AF_UNSPEC,
505 .ai_flags = AI_NUMERICSERV,
506 .ai_socktype = SOCK_STREAM,
508 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
514 // Remember the address(es)
515 for(struct addrinfo *aip = ai_in; aip; aip = aip->ai_next) {
516 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)aip->ai_addr);
519 if(flags & MESHLINK_INVITE_NUMERIC) {
520 // We don't need to do any further conversion
525 // Convert it to a hostname
526 char resolved_host[NI_MAXHOST];
527 char resolved_port[NI_MAXSERV];
528 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
530 if(err || !is_valid_hostname(resolved_host)) {
535 // Convert the hostname back to a sockaddr
536 hint.ai_family = ai_in->ai_family;
537 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
544 // Check if it's still the same sockaddr
545 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
547 freeaddrinfo(ai_out);
551 // Yes: replace the hostname with the resolved one
553 hostname[i] = xstrdup(resolved_host);
556 freeaddrinfo(ai_out);
559 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
560 remove_duplicate_hostnames(hostname, port, n);
562 // Concatenate all unique address to the hostport string
563 for(int i = 0; i < n; i++) {
568 // Append the address to the hostport string
570 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
572 hostport = newhostport;
581 static bool try_bind(meshlink_handle_t *mesh, int port) {
582 struct addrinfo *ai = NULL;
583 struct addrinfo hint = {
584 .ai_flags = AI_PASSIVE,
585 .ai_family = AF_UNSPEC,
586 .ai_socktype = SOCK_STREAM,
587 .ai_protocol = IPPROTO_TCP,
591 snprintf(portstr, sizeof(portstr), "%d", port);
593 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
597 bool success = false;
599 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
600 /* Try to bind to TCP. */
602 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
605 if(errno == EADDRINUSE) {
606 /* If this port is in use for any address family, avoid it. */
614 /* If TCP worked, then we require that UDP works as well. */
616 int udp_fd = setup_udp_listen_socket(mesh, aip);
633 int check_port(meshlink_handle_t *mesh) {
634 for(int i = 0; i < 1000; i++) {
635 int port = 0x1000 + prng(mesh, 0x8000);
637 if(try_bind(mesh, port)) {
639 xasprintf(&mesh->myport, "%d", port);
644 meshlink_errno = MESHLINK_ENETWORK;
645 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
649 static bool write_main_config_files(meshlink_handle_t *mesh) {
650 if(!mesh->confbase) {
656 /* Write the main config file */
657 packmsg_output_t out = {buf, sizeof buf};
659 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
660 packmsg_add_str(&out, mesh->name);
661 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
662 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
663 packmsg_add_uint16(&out, atoi(mesh->myport));
665 if(!packmsg_output_ok(&out)) {
669 config_t config = {buf, packmsg_output_size(&out, buf)};
671 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
675 /* Write our own host config file */
676 if(!node_write_config(mesh, mesh->self)) {
684 meshlink_handle_t *mesh;
686 char cookie[18 + 32];
697 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
698 meshlink_handle_t *mesh = state->mesh;
699 packmsg_input_t in = {buf, len};
700 uint32_t version = packmsg_get_uint32(&in);
702 if(version != MESHLINK_INVITATION_VERSION) {
703 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
707 char *name = packmsg_get_str_dup(&in);
708 packmsg_skip_element(&in); /* submesh */
709 dev_class_t devclass = packmsg_get_int32(&in);
710 uint32_t count = packmsg_get_array(&in);
713 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
717 if(!check_id(name)) {
718 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
724 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
730 free(mesh->self->name);
732 mesh->self->name = xstrdup(name);
733 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
735 // Initialize configuration directory
736 if(!config_init(mesh, "current")) {
740 if(!write_main_config_files(mesh)) {
744 // Write host config files
745 for(uint32_t i = 0; i < count; i++) {
747 uint32_t len = packmsg_get_bin_raw(&in, &data);
750 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
754 packmsg_input_t in2 = {data, len};
755 uint32_t version = packmsg_get_uint32(&in2);
756 char *name = packmsg_get_str_dup(&in2);
758 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
760 packmsg_input_invalidate(&in);
764 if(!check_id(name)) {
769 if(!strcmp(name, mesh->name)) {
770 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
772 meshlink_errno = MESHLINK_EPEER;
776 node_t *n = new_node();
779 config_t config = {data, len};
781 if(!node_read_from_config(mesh, n, &config)) {
783 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
784 meshlink_errno = MESHLINK_EPEER;
789 /* The first host config file is of the inviter itself;
790 * remember the address we are currently using for the invitation connection.
793 socklen_t salen = sizeof(sa);
795 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
796 node_add_recent_address(mesh, n, &sa);
800 /* Clear the reachability times, since we ourself have never seen these nodes yet */
801 n->last_reachable = 0;
802 n->last_unreachable = 0;
804 if(!node_write_config(mesh, n)) {
812 /* Ensure the configuration directory metadata is on disk */
813 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
817 if(!mesh->inviter_commits_first) {
818 devtool_set_inviter_commits_first(false);
821 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
823 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
828 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
830 join_state_t *state = handle;
831 const char *ptr = data;
834 int result = send(state->sock, ptr, len, 0);
836 if(result == -1 && errno == EINTR) {
838 } else if(result <= 0) {
849 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
850 join_state_t *state = handle;
851 meshlink_handle_t *mesh = state->mesh;
853 if(mesh->inviter_commits_first) {
855 case SPTPS_HANDSHAKE:
856 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
862 if(!finalize_join(state, msg, len)) {
866 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
867 shutdown(state->sock, SHUT_RDWR);
868 state->success = true;
876 case SPTPS_HANDSHAKE:
877 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
880 return finalize_join(state, msg, len);
883 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
884 shutdown(state->sock, SHUT_RDWR);
885 state->success = true;
896 static bool recvline(join_state_t *state) {
897 char *newline = NULL;
899 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
900 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
902 if(result == -1 && errno == EINTR) {
904 } else if(result <= 0) {
908 state->blen += result;
911 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
915 size_t len = newline - state->buffer;
917 memcpy(state->line, state->buffer, len);
918 state->line[len] = 0;
919 memmove(state->buffer, newline + 1, state->blen - len - 1);
920 state->blen -= len + 1;
925 static bool sendline(int fd, char *format, ...) {
931 va_start(ap, format);
932 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
935 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
943 int result = send(fd, p, blen, MSG_NOSIGNAL);
945 if(result == -1 && errno == EINTR) {
947 } else if(result <= 0) {
958 static const char *errstr[] = {
959 [MESHLINK_OK] = "No error",
960 [MESHLINK_EINVAL] = "Invalid argument",
961 [MESHLINK_ENOMEM] = "Out of memory",
962 [MESHLINK_ENOENT] = "No such node",
963 [MESHLINK_EEXIST] = "Node already exists",
964 [MESHLINK_EINTERNAL] = "Internal error",
965 [MESHLINK_ERESOLV] = "Could not resolve hostname",
966 [MESHLINK_ESTORAGE] = "Storage error",
967 [MESHLINK_ENETWORK] = "Network error",
968 [MESHLINK_EPEER] = "Error communicating with peer",
969 [MESHLINK_ENOTSUP] = "Operation not supported",
970 [MESHLINK_EBUSY] = "MeshLink instance already in use",
971 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
974 const char *meshlink_strerror(meshlink_errno_t err) {
975 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
976 return "Invalid error code";
982 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
983 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
985 mesh->private_key = ecdsa_generate();
986 mesh->invitation_key = ecdsa_generate();
988 if(!mesh->private_key || !mesh->invitation_key) {
989 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
990 meshlink_errno = MESHLINK_EINTERNAL;
994 logger(mesh, MESHLINK_DEBUG, "Done.\n");
999 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
1000 if(a->tv_sec == b->tv_sec) {
1001 return a->tv_nsec < b->tv_nsec;
1003 return a->tv_sec < b->tv_sec;
1007 static struct timespec idle(event_loop_t *loop, void *data) {
1009 meshlink_handle_t *mesh = data;
1010 struct timespec t, tmin = {3600, 0};
1012 for splay_each(node_t, n, mesh->nodes) {
1017 t = utcp_timeout(n->utcp);
1019 if(timespec_lt(&t, &tmin)) {
1027 // Get our local address(es) by simulating connecting to an Internet host.
1028 static void add_local_addresses(meshlink_handle_t *mesh) {
1030 sa.storage.ss_family = AF_UNKNOWN;
1031 socklen_t salen = sizeof(sa);
1035 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
1036 sa.in.sin_port = ntohs(atoi(mesh->myport));
1037 node_add_recent_address(mesh, mesh->self, &sa);
1044 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
1045 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
1046 node_add_recent_address(mesh, mesh->self, &sa);
1050 static bool meshlink_setup(meshlink_handle_t *mesh) {
1051 if(!config_destroy(mesh->confbase, "new")) {
1052 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1053 meshlink_errno = MESHLINK_ESTORAGE;
1057 if(!config_destroy(mesh->confbase, "old")) {
1058 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1059 meshlink_errno = MESHLINK_ESTORAGE;
1063 if(!config_init(mesh, "current")) {
1064 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1065 meshlink_errno = MESHLINK_ESTORAGE;
1069 if(!ecdsa_keygen(mesh)) {
1070 meshlink_errno = MESHLINK_EINTERNAL;
1074 if(check_port(mesh) == 0) {
1075 meshlink_errno = MESHLINK_ENETWORK;
1079 /* Create a node for ourself */
1081 mesh->self = new_node();
1082 mesh->self->name = xstrdup(mesh->name);
1083 mesh->self->devclass = mesh->devclass;
1084 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1085 mesh->self->session_id = mesh->session_id;
1087 if(!write_main_config_files(mesh)) {
1088 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1089 meshlink_errno = MESHLINK_ESTORAGE;
1093 /* Ensure the configuration directory metadata is on disk */
1094 if(!config_sync(mesh, "current")) {
1101 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1104 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1105 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1109 packmsg_input_t in = {config.buf, config.len};
1110 const void *private_key;
1111 const void *invitation_key;
1113 uint32_t version = packmsg_get_uint32(&in);
1114 char *name = packmsg_get_str_dup(&in);
1115 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1116 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1117 uint16_t myport = packmsg_get_uint16(&in);
1119 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1120 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1122 config_free(&config);
1128 // TODO: check this?
1129 if(mesh->name && strcmp(mesh->name, name)) {
1130 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1131 meshlink_errno = MESHLINK_ESTORAGE;
1133 config_free(&config);
1141 xasprintf(&mesh->myport, "%u", myport);
1142 mesh->private_key = ecdsa_set_private_key(private_key);
1143 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1144 config_free(&config);
1146 /* Create a node for ourself and read our host configuration file */
1148 mesh->self = new_node();
1149 mesh->self->name = xstrdup(name);
1150 mesh->self->devclass = mesh->devclass;
1151 mesh->self->session_id = mesh->session_id;
1153 if(!node_read_public_key(mesh, mesh->self)) {
1154 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1155 meshlink_errno = MESHLINK_ESTORAGE;
1156 free_node(mesh->self);
1165 static void *setup_network_in_netns_thread(void *arg) {
1166 meshlink_handle_t *mesh = arg;
1168 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1172 bool success = setup_network(mesh);
1173 return success ? arg : NULL;
1175 #endif // HAVE_SETNS
1177 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1178 if(!confbase || !*confbase) {
1179 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1180 meshlink_errno = MESHLINK_EINVAL;
1184 if(!appname || !*appname) {
1185 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1186 meshlink_errno = MESHLINK_EINVAL;
1190 if(strchr(appname, ' ')) {
1191 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1192 meshlink_errno = MESHLINK_EINVAL;
1196 if(!name || !*name) {
1197 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1198 meshlink_errno = MESHLINK_EINVAL;
1202 if(!check_id(name)) {
1203 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1204 meshlink_errno = MESHLINK_EINVAL;
1208 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1209 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1210 meshlink_errno = MESHLINK_EINVAL;
1214 meshlink_open_params_t *params = xzalloc(sizeof * params);
1216 params->confbase = xstrdup(confbase);
1217 params->name = xstrdup(name);
1218 params->appname = xstrdup(appname);
1219 params->devclass = devclass;
1225 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1227 meshlink_errno = MESHLINK_EINVAL;
1231 params->netns = netns;
1236 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1238 meshlink_errno = MESHLINK_EINVAL;
1242 if((!key && keylen) || (key && !keylen)) {
1243 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1244 meshlink_errno = MESHLINK_EINVAL;
1249 params->keylen = keylen;
1254 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1255 if(!mesh || !new_key || !new_keylen) {
1256 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1257 meshlink_errno = MESHLINK_EINVAL;
1261 pthread_mutex_lock(&mesh->mutex);
1263 // Create hash for the new key
1264 void *new_config_key;
1265 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1267 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1268 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1269 meshlink_errno = MESHLINK_EINTERNAL;
1270 pthread_mutex_unlock(&mesh->mutex);
1274 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1276 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1277 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1278 meshlink_errno = MESHLINK_ESTORAGE;
1279 pthread_mutex_unlock(&mesh->mutex);
1283 devtool_keyrotate_probe(1);
1285 // Rename confbase/current/ to confbase/old
1287 if(!config_rename(mesh, "current", "old")) {
1288 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1289 meshlink_errno = MESHLINK_ESTORAGE;
1290 pthread_mutex_unlock(&mesh->mutex);
1294 devtool_keyrotate_probe(2);
1296 // Rename confbase/new/ to confbase/current
1298 if(!config_rename(mesh, "new", "current")) {
1299 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1300 meshlink_errno = MESHLINK_ESTORAGE;
1301 pthread_mutex_unlock(&mesh->mutex);
1305 devtool_keyrotate_probe(3);
1307 // Cleanup the "old" confbase sub-directory
1309 if(!config_destroy(mesh->confbase, "old")) {
1310 pthread_mutex_unlock(&mesh->mutex);
1314 // Change the mesh handle key with new key
1316 free(mesh->config_key);
1317 mesh->config_key = new_config_key;
1319 pthread_mutex_unlock(&mesh->mutex);
1324 void meshlink_open_params_free(meshlink_open_params_t *params) {
1326 meshlink_errno = MESHLINK_EINVAL;
1330 free(params->confbase);
1332 free(params->appname);
1337 /// Device class traits
1338 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1339 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1340 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1341 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1342 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1345 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1346 if(!confbase || !*confbase) {
1347 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1348 meshlink_errno = MESHLINK_EINVAL;
1352 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1353 meshlink_open_params_t params;
1354 memset(¶ms, 0, sizeof(params));
1356 params.confbase = (char *)confbase;
1357 params.name = (char *)name;
1358 params.appname = (char *)appname;
1359 params.devclass = devclass;
1362 return meshlink_open_ex(¶ms);
1365 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) {
1366 if(!confbase || !*confbase) {
1367 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1368 meshlink_errno = MESHLINK_EINVAL;
1372 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1373 meshlink_open_params_t params;
1374 memset(¶ms, 0, sizeof(params));
1376 params.confbase = (char *)confbase;
1377 params.name = (char *)name;
1378 params.appname = (char *)appname;
1379 params.devclass = devclass;
1382 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1386 return meshlink_open_ex(¶ms);
1389 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1390 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1391 meshlink_open_params_t params;
1392 memset(¶ms, 0, sizeof(params));
1394 params.name = (char *)name;
1395 params.appname = (char *)appname;
1396 params.devclass = devclass;
1399 return meshlink_open_ex(¶ms);
1402 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1403 // Validate arguments provided by the application
1404 bool usingname = false;
1406 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1408 if(!params->appname || !*params->appname) {
1409 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1410 meshlink_errno = MESHLINK_EINVAL;
1414 if(strchr(params->appname, ' ')) {
1415 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1416 meshlink_errno = MESHLINK_EINVAL;
1420 if(!params->name || !*params->name) {
1421 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1423 } else { //check name only if there is a name != NULL
1425 if(!check_id(params->name)) {
1426 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1427 meshlink_errno = MESHLINK_EINVAL;
1434 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1435 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1436 meshlink_errno = MESHLINK_EINVAL;
1440 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1441 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1442 meshlink_errno = MESHLINK_EINVAL;
1446 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1448 if(params->confbase) {
1449 mesh->confbase = xstrdup(params->confbase);
1452 mesh->appname = xstrdup(params->appname);
1453 mesh->devclass = params->devclass;
1454 mesh->discovery = true;
1455 mesh->invitation_timeout = 604800; // 1 week
1456 mesh->netns = params->netns;
1457 mesh->submeshes = NULL;
1458 mesh->log_cb = global_log_cb;
1459 mesh->log_level = global_log_level;
1460 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1462 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1465 randomize(&mesh->session_id, sizeof(mesh->session_id));
1466 } while(mesh->session_id == 0);
1468 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1471 mesh->name = xstrdup(params->name);
1476 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1478 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1479 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1480 meshlink_close(mesh);
1481 meshlink_errno = MESHLINK_EINTERNAL;
1487 pthread_mutexattr_t attr;
1488 pthread_mutexattr_init(&attr);
1489 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1490 pthread_mutex_init(&mesh->mutex, &attr);
1492 mesh->threadstarted = false;
1493 event_loop_init(&mesh->loop);
1494 mesh->loop.data = mesh;
1496 meshlink_queue_init(&mesh->outpacketqueue);
1498 // Atomically lock the configuration directory.
1499 if(!main_config_lock(mesh)) {
1500 meshlink_close(mesh);
1504 // If no configuration exists yet, create it.
1506 if(!meshlink_confbase_exists(mesh)) {
1507 if(!meshlink_setup(mesh)) {
1508 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1509 meshlink_close(mesh);
1513 if(!meshlink_read_config(mesh)) {
1514 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1515 meshlink_close(mesh);
1521 struct WSAData wsa_state;
1522 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1525 // Setup up everything
1526 // TODO: we should not open listening sockets yet
1528 bool success = false;
1530 if(mesh->netns != -1) {
1534 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1535 void *retval = NULL;
1536 success = pthread_join(thr, &retval) == 0 && retval;
1540 meshlink_errno = MESHLINK_EINTERNAL;
1543 #endif // HAVE_SETNS
1545 success = setup_network(mesh);
1549 meshlink_close(mesh);
1550 meshlink_errno = MESHLINK_ENETWORK;
1554 add_local_addresses(mesh);
1556 if(!node_write_config(mesh, mesh->self)) {
1557 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1561 idle_set(&mesh->loop, idle, mesh);
1563 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1567 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1568 meshlink_submesh_t *s = NULL;
1571 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1572 meshlink_errno = MESHLINK_EINVAL;
1576 if(!submesh || !*submesh) {
1577 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1578 meshlink_errno = MESHLINK_EINVAL;
1583 pthread_mutex_lock(&mesh->mutex);
1585 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1587 pthread_mutex_unlock(&mesh->mutex);
1592 static void *meshlink_main_loop(void *arg) {
1593 meshlink_handle_t *mesh = arg;
1595 if(mesh->netns != -1) {
1598 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1599 pthread_cond_signal(&mesh->cond);
1604 pthread_cond_signal(&mesh->cond);
1606 #endif // HAVE_SETNS
1611 if(mesh->discovery) {
1612 discovery_start(mesh);
1617 pthread_mutex_lock(&mesh->mutex);
1619 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1620 pthread_cond_broadcast(&mesh->cond);
1622 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1624 pthread_mutex_unlock(&mesh->mutex);
1629 if(mesh->discovery) {
1630 discovery_stop(mesh);
1638 bool meshlink_start(meshlink_handle_t *mesh) {
1640 meshlink_errno = MESHLINK_EINVAL;
1644 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1646 pthread_mutex_lock(&mesh->mutex);
1649 assert(mesh->private_key);
1650 assert(mesh->self->ecdsa);
1651 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1653 if(mesh->threadstarted) {
1654 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1655 pthread_mutex_unlock(&mesh->mutex);
1659 if(mesh->listen_socket[0].tcp.fd < 0) {
1660 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1661 meshlink_errno = MESHLINK_ENETWORK;
1665 // TODO: open listening sockets first
1667 //Check that a valid name is set
1669 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1670 meshlink_errno = MESHLINK_EINVAL;
1671 pthread_mutex_unlock(&mesh->mutex);
1675 init_outgoings(mesh);
1677 // Start the main thread
1679 event_loop_start(&mesh->loop);
1681 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1682 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1683 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1684 meshlink_errno = MESHLINK_EINTERNAL;
1685 event_loop_stop(&mesh->loop);
1686 pthread_mutex_unlock(&mesh->mutex);
1690 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1691 mesh->threadstarted = true;
1693 // Ensure we are considered reachable
1696 pthread_mutex_unlock(&mesh->mutex);
1700 void meshlink_stop(meshlink_handle_t *mesh) {
1702 meshlink_errno = MESHLINK_EINVAL;
1706 pthread_mutex_lock(&mesh->mutex);
1707 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1709 // Shut down the main thread
1710 event_loop_stop(&mesh->loop);
1712 // Send ourselves a UDP packet to kick the event loop
1713 for(int i = 0; i < mesh->listen_sockets; i++) {
1715 socklen_t salen = sizeof(sa);
1717 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1718 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1722 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1723 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1727 if(mesh->threadstarted) {
1728 // Wait for the main thread to finish
1729 pthread_mutex_unlock(&mesh->mutex);
1730 pthread_join(mesh->thread, NULL);
1731 pthread_mutex_lock(&mesh->mutex);
1733 mesh->threadstarted = false;
1736 // Close all metaconnections
1737 if(mesh->connections) {
1738 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1740 connection_t *c = node->data;
1742 terminate_connection(mesh, c, false);
1746 exit_outgoings(mesh);
1748 // Ensure we are considered unreachable
1753 // Try to write out any changed node config files, ignore errors at this point.
1755 for splay_each(node_t, n, mesh->nodes) {
1756 if(n->status.dirty) {
1757 n->status.dirty = !node_write_config(mesh, n);
1762 pthread_mutex_unlock(&mesh->mutex);
1765 void meshlink_close(meshlink_handle_t *mesh) {
1767 meshlink_errno = MESHLINK_EINVAL;
1771 // stop can be called even if mesh has not been started
1772 meshlink_stop(mesh);
1774 // lock is not released after this
1775 pthread_mutex_lock(&mesh->mutex);
1777 // Close and free all resources used.
1779 close_network_connections(mesh);
1781 logger(mesh, MESHLINK_INFO, "Terminating");
1783 event_loop_exit(&mesh->loop);
1787 if(mesh->confbase) {
1793 ecdsa_free(mesh->invitation_key);
1795 if(mesh->netns != -1) {
1799 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1803 meshlink_queue_exit(&mesh->outpacketqueue);
1806 free(mesh->appname);
1807 free(mesh->confbase);
1808 free(mesh->config_key);
1809 free(mesh->external_address_url);
1811 ecdsa_free(mesh->private_key);
1813 if(mesh->invitation_addresses) {
1814 list_delete_list(mesh->invitation_addresses);
1817 main_config_unlock(mesh);
1819 pthread_mutex_unlock(&mesh->mutex);
1820 pthread_mutex_destroy(&mesh->mutex);
1822 memset(mesh, 0, sizeof(*mesh));
1827 bool meshlink_destroy(const char *confbase) {
1829 meshlink_errno = MESHLINK_EINVAL;
1833 /* Exit early if the confbase directory itself doesn't exist */
1834 if(access(confbase, F_OK) && errno == ENOENT) {
1838 /* Take the lock the same way meshlink_open() would. */
1839 char lockfilename[PATH_MAX];
1840 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1842 FILE *lockfile = fopen(lockfilename, "w+");
1845 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1846 meshlink_errno = MESHLINK_ESTORAGE;
1851 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1855 // TODO: use _locking()?
1858 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1859 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1861 meshlink_errno = MESHLINK_EBUSY;
1867 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1868 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1872 if(unlink(lockfilename)) {
1873 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1875 meshlink_errno = MESHLINK_ESTORAGE;
1881 if(!sync_path(confbase)) {
1882 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1883 meshlink_errno = MESHLINK_ESTORAGE;
1890 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1892 meshlink_errno = MESHLINK_EINVAL;
1896 pthread_mutex_lock(&mesh->mutex);
1897 mesh->receive_cb = cb;
1898 pthread_mutex_unlock(&mesh->mutex);
1901 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1903 meshlink_errno = MESHLINK_EINVAL;
1907 pthread_mutex_lock(&mesh->mutex);
1908 mesh->connection_try_cb = cb;
1909 pthread_mutex_unlock(&mesh->mutex);
1912 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1914 meshlink_errno = MESHLINK_EINVAL;
1918 pthread_mutex_lock(&mesh->mutex);
1919 mesh->node_status_cb = cb;
1920 pthread_mutex_unlock(&mesh->mutex);
1923 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1925 meshlink_errno = MESHLINK_EINVAL;
1929 pthread_mutex_lock(&mesh->mutex);
1930 mesh->node_pmtu_cb = cb;
1931 pthread_mutex_unlock(&mesh->mutex);
1934 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1936 meshlink_errno = MESHLINK_EINVAL;
1940 pthread_mutex_lock(&mesh->mutex);
1941 mesh->node_duplicate_cb = cb;
1942 pthread_mutex_unlock(&mesh->mutex);
1945 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1947 pthread_mutex_lock(&mesh->mutex);
1949 mesh->log_level = cb ? level : 0;
1950 pthread_mutex_unlock(&mesh->mutex);
1953 global_log_level = cb ? level : 0;
1957 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1959 meshlink_errno = MESHLINK_EINVAL;
1963 pthread_mutex_lock(&mesh->mutex);
1964 mesh->error_cb = cb;
1965 pthread_mutex_unlock(&mesh->mutex);
1968 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1969 meshlink_packethdr_t *hdr;
1971 if(len >= MAXSIZE - sizeof(*hdr)) {
1972 meshlink_errno = MESHLINK_EINVAL;
1976 node_t *n = (node_t *)destination;
1978 if(n->status.blacklisted) {
1979 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1980 meshlink_errno = MESHLINK_EBLACKLISTED;
1984 // Prepare the packet
1985 packet->probe = false;
1986 packet->tcp = false;
1987 packet->len = len + sizeof(*hdr);
1989 hdr = (meshlink_packethdr_t *)packet->data;
1990 memset(hdr, 0, sizeof(*hdr));
1991 // leave the last byte as 0 to make sure strings are always
1992 // null-terminated if they are longer than the buffer
1993 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1994 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1996 memcpy(packet->data + sizeof(*hdr), data, len);
2001 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2003 assert(destination);
2007 // Prepare the packet
2008 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2012 // Send it immediately
2013 route(mesh, mesh->self, mesh->packet);
2018 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2019 // Validate arguments
2020 if(!mesh || !destination) {
2021 meshlink_errno = MESHLINK_EINVAL;
2030 meshlink_errno = MESHLINK_EINVAL;
2034 // Prepare the packet
2035 vpn_packet_t *packet = malloc(sizeof(*packet));
2038 meshlink_errno = MESHLINK_ENOMEM;
2042 if(!prepare_packet(mesh, destination, data, len, packet)) {
2047 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2049 meshlink_errno = MESHLINK_ENOMEM;
2053 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2055 // Notify event loop
2056 signal_trigger(&mesh->loop, &mesh->datafromapp);
2061 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2063 meshlink_handle_t *mesh = data;
2065 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2067 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2068 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2069 mesh->self->in_packets++;
2070 mesh->self->in_bytes += packet->len;
2071 route(mesh, mesh->self, packet);
2076 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2077 if(!mesh || !destination) {
2078 meshlink_errno = MESHLINK_EINVAL;
2082 pthread_mutex_lock(&mesh->mutex);
2084 node_t *n = (node_t *)destination;
2086 if(!n->status.reachable) {
2087 pthread_mutex_unlock(&mesh->mutex);
2090 } else if(n->mtuprobes > 30 && n->minmtu) {
2091 pthread_mutex_unlock(&mesh->mutex);
2094 pthread_mutex_unlock(&mesh->mutex);
2099 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2100 if(!mesh || !node) {
2101 meshlink_errno = MESHLINK_EINVAL;
2105 pthread_mutex_lock(&mesh->mutex);
2107 node_t *n = (node_t *)node;
2109 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2110 meshlink_errno = MESHLINK_EINTERNAL;
2111 pthread_mutex_unlock(&mesh->mutex);
2115 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2118 meshlink_errno = MESHLINK_EINTERNAL;
2121 pthread_mutex_unlock(&mesh->mutex);
2125 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2127 meshlink_errno = MESHLINK_EINVAL;
2131 return (meshlink_node_t *)mesh->self;
2134 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2135 if(!mesh || !name) {
2136 meshlink_errno = MESHLINK_EINVAL;
2142 pthread_mutex_lock(&mesh->mutex);
2143 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2144 pthread_mutex_unlock(&mesh->mutex);
2147 meshlink_errno = MESHLINK_ENOENT;
2150 return (meshlink_node_t *)n;
2153 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2154 if(!mesh || !name) {
2155 meshlink_errno = MESHLINK_EINVAL;
2159 meshlink_submesh_t *submesh = NULL;
2161 pthread_mutex_lock(&mesh->mutex);
2162 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2163 pthread_mutex_unlock(&mesh->mutex);
2166 meshlink_errno = MESHLINK_ENOENT;
2172 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2173 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2174 meshlink_errno = MESHLINK_EINVAL;
2178 meshlink_node_t **result;
2181 pthread_mutex_lock(&mesh->mutex);
2183 *nmemb = mesh->nodes->count;
2184 result = realloc(nodes, *nmemb * sizeof(*nodes));
2187 meshlink_node_t **p = result;
2189 for splay_each(node_t, n, mesh->nodes) {
2190 *p++ = (meshlink_node_t *)n;
2195 meshlink_errno = MESHLINK_ENOMEM;
2198 pthread_mutex_unlock(&mesh->mutex);
2203 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) {
2204 meshlink_node_t **result;
2206 pthread_mutex_lock(&mesh->mutex);
2210 for splay_each(node_t, n, mesh->nodes) {
2211 if(search_node(n, condition)) {
2218 pthread_mutex_unlock(&mesh->mutex);
2222 result = realloc(nodes, *nmemb * sizeof(*nodes));
2225 meshlink_node_t **p = result;
2227 for splay_each(node_t, n, mesh->nodes) {
2228 if(search_node(n, condition)) {
2229 *p++ = (meshlink_node_t *)n;
2235 meshlink_errno = MESHLINK_ENOMEM;
2238 pthread_mutex_unlock(&mesh->mutex);
2243 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2244 dev_class_t *devclass = (dev_class_t *)condition;
2246 if(*devclass == (dev_class_t)node->devclass) {
2253 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2254 if(condition == node->submesh) {
2266 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2267 const struct time_range *range = condition;
2268 time_t start = node->last_reachable;
2269 time_t end = node->last_unreachable;
2279 if(range->end >= range->start) {
2280 return start <= range->end && end >= range->start;
2282 return start > range->start || end < range->end;
2286 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) {
2287 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2288 meshlink_errno = MESHLINK_EINVAL;
2292 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2295 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2296 if(!mesh || !submesh || !nmemb) {
2297 meshlink_errno = MESHLINK_EINVAL;
2301 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2304 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) {
2305 if(!mesh || !nmemb) {
2306 meshlink_errno = MESHLINK_EINVAL;
2310 struct time_range range = {start, end};
2312 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2315 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2316 if(!mesh || !node) {
2317 meshlink_errno = MESHLINK_EINVAL;
2321 dev_class_t devclass;
2323 pthread_mutex_lock(&mesh->mutex);
2325 devclass = ((node_t *)node)->devclass;
2327 pthread_mutex_unlock(&mesh->mutex);
2332 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2333 if(!mesh || !node) {
2334 meshlink_errno = MESHLINK_EINVAL;
2338 node_t *n = (node_t *)node;
2340 meshlink_submesh_t *s;
2342 s = (meshlink_submesh_t *)n->submesh;
2347 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2348 if(!mesh || !node) {
2349 meshlink_errno = MESHLINK_EINVAL;
2353 node_t *n = (node_t *)node;
2356 pthread_mutex_lock(&mesh->mutex);
2357 reachable = n->status.reachable && !n->status.blacklisted;
2359 if(last_reachable) {
2360 *last_reachable = n->last_reachable;
2363 if(last_unreachable) {
2364 *last_unreachable = n->last_unreachable;
2367 pthread_mutex_unlock(&mesh->mutex);
2372 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2373 if(!mesh || !data || !len || !signature || !siglen) {
2374 meshlink_errno = MESHLINK_EINVAL;
2378 if(*siglen < MESHLINK_SIGLEN) {
2379 meshlink_errno = MESHLINK_EINVAL;
2383 pthread_mutex_lock(&mesh->mutex);
2385 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2386 meshlink_errno = MESHLINK_EINTERNAL;
2387 pthread_mutex_unlock(&mesh->mutex);
2391 *siglen = MESHLINK_SIGLEN;
2392 pthread_mutex_unlock(&mesh->mutex);
2396 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2397 if(!mesh || !source || !data || !len || !signature) {
2398 meshlink_errno = MESHLINK_EINVAL;
2402 if(siglen != MESHLINK_SIGLEN) {
2403 meshlink_errno = MESHLINK_EINVAL;
2407 pthread_mutex_lock(&mesh->mutex);
2411 struct node_t *n = (struct node_t *)source;
2413 if(!node_read_public_key(mesh, n)) {
2414 meshlink_errno = MESHLINK_EINTERNAL;
2417 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2420 pthread_mutex_unlock(&mesh->mutex);
2424 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2425 pthread_mutex_lock(&mesh->mutex);
2427 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2430 // TODO: Update invitation key if necessary?
2433 pthread_mutex_unlock(&mesh->mutex);
2435 return mesh->invitation_key;
2438 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2439 if(!mesh || !node || !address) {
2440 meshlink_errno = MESHLINK_EINVAL;
2444 if(!is_valid_hostname(address)) {
2445 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2446 meshlink_errno = MESHLINK_EINVAL;
2450 if(port && !is_valid_port(port)) {
2451 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2452 meshlink_errno = MESHLINK_EINVAL;
2456 char *canonical_address;
2459 xasprintf(&canonical_address, "%s %s", address, port);
2461 canonical_address = xstrdup(address);
2464 pthread_mutex_lock(&mesh->mutex);
2466 node_t *n = (node_t *)node;
2467 free(n->canonical_address);
2468 n->canonical_address = canonical_address;
2470 if(!node_write_config(mesh, n)) {
2471 pthread_mutex_unlock(&mesh->mutex);
2475 pthread_mutex_unlock(&mesh->mutex);
2477 return config_sync(mesh, "current");
2480 bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
2481 if(!mesh || !address) {
2482 meshlink_errno = MESHLINK_EINVAL;
2486 if(!is_valid_hostname(address)) {
2487 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2488 meshlink_errno = MESHLINK_EINVAL;
2492 if(port && !is_valid_port(port)) {
2493 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2494 meshlink_errno = MESHLINK_EINVAL;
2501 xasprintf(&combo, "%s/%s", address, port);
2503 combo = xstrdup(address);
2506 pthread_mutex_lock(&mesh->mutex);
2508 if(!mesh->invitation_addresses) {
2509 mesh->invitation_addresses = list_alloc((list_action_t)free);
2512 list_insert_tail(mesh->invitation_addresses, combo);
2513 pthread_mutex_unlock(&mesh->mutex);
2518 void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
2520 meshlink_errno = MESHLINK_EINVAL;
2524 pthread_mutex_lock(&mesh->mutex);
2526 if(mesh->invitation_addresses) {
2527 list_delete_list(mesh->invitation_addresses);
2528 mesh->invitation_addresses = NULL;
2531 pthread_mutex_unlock(&mesh->mutex);
2534 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2535 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2538 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2540 meshlink_errno = MESHLINK_EINVAL;
2544 char *address = meshlink_get_external_address(mesh);
2550 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2556 int meshlink_get_port(meshlink_handle_t *mesh) {
2558 meshlink_errno = MESHLINK_EINVAL;
2563 meshlink_errno = MESHLINK_EINTERNAL;
2569 pthread_mutex_lock(&mesh->mutex);
2570 port = atoi(mesh->myport);
2571 pthread_mutex_unlock(&mesh->mutex);
2576 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2577 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2578 meshlink_errno = MESHLINK_EINVAL;
2582 if(mesh->myport && port == atoi(mesh->myport)) {
2586 if(!try_bind(mesh, port)) {
2587 meshlink_errno = MESHLINK_ENETWORK;
2591 devtool_trybind_probe();
2595 pthread_mutex_lock(&mesh->mutex);
2597 if(mesh->threadstarted) {
2598 meshlink_errno = MESHLINK_EINVAL;
2603 xasprintf(&mesh->myport, "%d", port);
2605 /* Close down the network. This also deletes mesh->self. */
2606 close_network_connections(mesh);
2608 /* Recreate mesh->self. */
2609 mesh->self = new_node();
2610 mesh->self->name = xstrdup(mesh->name);
2611 mesh->self->devclass = mesh->devclass;
2612 mesh->self->session_id = mesh->session_id;
2613 xasprintf(&mesh->myport, "%d", port);
2615 if(!node_read_public_key(mesh, mesh->self)) {
2616 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2617 meshlink_errno = MESHLINK_ESTORAGE;
2618 free_node(mesh->self);
2621 } else if(!setup_network(mesh)) {
2622 meshlink_errno = MESHLINK_ENETWORK;
2626 /* Rebuild our own list of recent addresses */
2627 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2628 add_local_addresses(mesh);
2630 /* Write meshlink.conf with the updated port number */
2631 write_main_config_files(mesh);
2633 rval = config_sync(mesh, "current");
2636 pthread_mutex_unlock(&mesh->mutex);
2638 return rval && meshlink_get_port(mesh) == port;
2641 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2642 mesh->invitation_timeout = timeout;
2645 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2646 meshlink_submesh_t *s = NULL;
2649 meshlink_errno = MESHLINK_EINVAL;
2654 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2657 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2658 meshlink_errno = MESHLINK_EINVAL;
2662 s = (meshlink_submesh_t *)mesh->self->submesh;
2665 pthread_mutex_lock(&mesh->mutex);
2667 // Check validity of the new node's name
2668 if(!check_id(name)) {
2669 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2670 meshlink_errno = MESHLINK_EINVAL;
2671 pthread_mutex_unlock(&mesh->mutex);
2675 // Ensure no host configuration file with that name exists
2676 if(config_exists(mesh, "current", name)) {
2677 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2678 meshlink_errno = MESHLINK_EEXIST;
2679 pthread_mutex_unlock(&mesh->mutex);
2683 // Ensure no other nodes know about this name
2684 if(lookup_node(mesh, name)) {
2685 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2686 meshlink_errno = MESHLINK_EEXIST;
2687 pthread_mutex_unlock(&mesh->mutex);
2691 // Get the local address
2692 char *address = get_my_hostname(mesh, flags);
2695 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2696 meshlink_errno = MESHLINK_ERESOLV;
2697 pthread_mutex_unlock(&mesh->mutex);
2701 if(!refresh_invitation_key(mesh)) {
2702 meshlink_errno = MESHLINK_EINTERNAL;
2703 pthread_mutex_unlock(&mesh->mutex);
2707 // If we changed our own host config file, write it out now
2708 if(mesh->self->status.dirty) {
2709 if(!node_write_config(mesh, mesh->self)) {
2710 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2711 pthread_mutex_unlock(&mesh->mutex);
2718 // Create a hash of the key.
2719 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2720 sha512(fingerprint, strlen(fingerprint), hash);
2721 b64encode_urlsafe(hash, hash, 18);
2723 // Create a random cookie for this invitation.
2725 randomize(cookie, 18);
2727 // Create a filename that doesn't reveal the cookie itself
2728 char buf[18 + strlen(fingerprint)];
2729 char cookiehash[64];
2730 memcpy(buf, cookie, 18);
2731 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2732 sha512(buf, sizeof(buf), cookiehash);
2733 b64encode_urlsafe(cookiehash, cookiehash, 18);
2735 b64encode_urlsafe(cookie, cookie, 18);
2739 /* Construct the invitation file */
2740 uint8_t outbuf[4096];
2741 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2743 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2744 packmsg_add_str(&inv, name);
2745 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2746 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2748 /* TODO: Add several host config files to bootstrap connections.
2749 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2750 * and are not blacklisted.
2752 config_t configs[5];
2753 memset(configs, 0, sizeof(configs));
2756 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2760 /* Append host config files to the invitation file */
2761 packmsg_add_array(&inv, count);
2763 for(int i = 0; i < count; i++) {
2764 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2765 config_free(&configs[i]);
2768 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2770 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2771 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2772 meshlink_errno = MESHLINK_ESTORAGE;
2773 pthread_mutex_unlock(&mesh->mutex);
2777 // Create an URL from the local address, key hash and cookie
2779 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2782 pthread_mutex_unlock(&mesh->mutex);
2786 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2787 return meshlink_invite_ex(mesh, submesh, name, 0);
2790 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2791 if(!mesh || !invitation) {
2792 meshlink_errno = MESHLINK_EINVAL;
2796 join_state_t state = {
2801 ecdsa_t *key = NULL;
2802 ecdsa_t *hiskey = NULL;
2804 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2805 char copy[strlen(invitation) + 1];
2807 pthread_mutex_lock(&mesh->mutex);
2809 //Before doing meshlink_join make sure we are not connected to another mesh
2810 if(mesh->threadstarted) {
2811 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2812 meshlink_errno = MESHLINK_EINVAL;
2816 // 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.
2817 if(mesh->nodes->count > 1) {
2818 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2819 meshlink_errno = MESHLINK_EINVAL;
2823 strcpy(copy, invitation);
2825 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2827 char *slash = strchr(copy, '/');
2835 if(strlen(slash) != 48) {
2839 char *address = copy;
2842 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2846 if(mesh->inviter_commits_first) {
2847 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2850 // Generate a throw-away key for the invitation.
2851 key = ecdsa_generate();
2854 meshlink_errno = MESHLINK_EINTERNAL;
2858 char *b64key = ecdsa_get_base64_public_key(key);
2861 while(address && *address) {
2862 // We allow commas in the address part to support multiple addresses in one invitation URL.
2863 comma = strchr(address, ',');
2869 // Split of the port
2870 port = strrchr(address, ':');
2878 // IPv6 address are enclosed in brackets, per RFC 3986
2879 if(*address == '[') {
2881 char *bracket = strchr(address, ']');
2894 // Connect to the meshlink daemon mentioned in the URL.
2895 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2898 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2899 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2901 if(state.sock == -1) {
2902 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2903 meshlink_errno = MESHLINK_ENETWORK;
2907 set_timeout(state.sock, 5000);
2909 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2910 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2911 meshlink_errno = MESHLINK_ENETWORK;
2912 closesocket(state.sock);
2922 meshlink_errno = MESHLINK_ERESOLV;
2925 if(state.sock != -1 || !comma) {
2932 if(state.sock == -1) {
2936 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2938 // Tell him we have an invitation, and give him our throw-away key.
2942 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2943 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2944 meshlink_errno = MESHLINK_ENETWORK;
2950 char hisname[4096] = "";
2951 int code, hismajor, hisminor = 0;
2953 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) {
2954 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2955 meshlink_errno = MESHLINK_ENETWORK;
2959 // Check if the hash of the key he gave us matches the hash in the URL.
2960 char *fingerprint = state.line + 2;
2963 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2964 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2965 meshlink_errno = MESHLINK_EINTERNAL;
2969 if(memcmp(hishash, state.hash, 18)) {
2970 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2971 meshlink_errno = MESHLINK_EPEER;
2975 hiskey = ecdsa_set_base64_public_key(fingerprint);
2978 meshlink_errno = MESHLINK_EINTERNAL;
2982 // Start an SPTPS session
2983 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2984 meshlink_errno = MESHLINK_EINTERNAL;
2988 // Feed rest of input buffer to SPTPS
2989 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2990 meshlink_errno = MESHLINK_EPEER;
2995 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2997 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2999 if(errno == EINTR) {
3003 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
3004 meshlink_errno = MESHLINK_ENETWORK;
3008 if(!sptps_receive_data(&state.sptps, state.line, len)) {
3009 meshlink_errno = MESHLINK_EPEER;
3014 if(!state.success) {
3015 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
3016 meshlink_errno = MESHLINK_EPEER;
3020 sptps_stop(&state.sptps);
3023 closesocket(state.sock);
3025 pthread_mutex_unlock(&mesh->mutex);
3029 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
3030 meshlink_errno = MESHLINK_EINVAL;
3032 sptps_stop(&state.sptps);
3036 if(state.sock != -1) {
3037 closesocket(state.sock);
3040 pthread_mutex_unlock(&mesh->mutex);
3044 char *meshlink_export(meshlink_handle_t *mesh) {
3046 meshlink_errno = MESHLINK_EINVAL;
3050 // Create a config file on the fly.
3053 packmsg_output_t out = {buf, sizeof(buf)};
3054 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
3055 packmsg_add_str(&out, mesh->name);
3056 packmsg_add_str(&out, CORE_MESH);
3058 pthread_mutex_lock(&mesh->mutex);
3060 packmsg_add_int32(&out, mesh->self->devclass);
3061 packmsg_add_bool(&out, mesh->self->status.blacklisted);
3062 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
3063 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3067 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3068 if(mesh->self->recent[i].sa.sa_family) {
3075 packmsg_add_array(&out, count);
3077 for(uint32_t i = 0; i < count; i++) {
3078 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3081 packmsg_add_int64(&out, 0);
3082 packmsg_add_int64(&out, 0);
3084 pthread_mutex_unlock(&mesh->mutex);
3086 if(!packmsg_output_ok(&out)) {
3087 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3088 meshlink_errno = MESHLINK_EINTERNAL;
3092 // Prepare a base64-encoded packmsg array containing our config file
3094 uint32_t len = packmsg_output_size(&out, buf);
3095 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3096 uint8_t *buf2 = xmalloc(len2);
3097 packmsg_output_t out2 = {buf2, len2};
3098 packmsg_add_array(&out2, 1);
3099 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3101 if(!packmsg_output_ok(&out2)) {
3102 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3103 meshlink_errno = MESHLINK_EINTERNAL;
3108 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3110 return (char *)buf2;
3113 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3114 if(!mesh || !data) {
3115 meshlink_errno = MESHLINK_EINVAL;
3119 size_t datalen = strlen(data);
3120 uint8_t *buf = xmalloc(datalen);
3121 int buflen = b64decode(data, buf, datalen);
3124 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3125 meshlink_errno = MESHLINK_EPEER;
3129 packmsg_input_t in = {buf, buflen};
3130 uint32_t count = packmsg_get_array(&in);
3133 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3134 meshlink_errno = MESHLINK_EPEER;
3138 pthread_mutex_lock(&mesh->mutex);
3142 uint32_t len = packmsg_get_bin_raw(&in, &data);
3148 packmsg_input_t in2 = {data, len};
3149 uint32_t version = packmsg_get_uint32(&in2);
3150 char *name = packmsg_get_str_dup(&in2);
3152 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3154 packmsg_input_invalidate(&in);
3158 if(!check_id(name)) {
3163 node_t *n = lookup_node(mesh, name);
3166 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3174 config_t config = {data, len};
3176 if(!node_read_from_config(mesh, n, &config)) {
3178 packmsg_input_invalidate(&in);
3182 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3183 n->last_reachable = 0;
3184 n->last_unreachable = 0;
3186 if(!node_write_config(mesh, n)) {
3194 pthread_mutex_unlock(&mesh->mutex);
3198 if(!packmsg_done(&in)) {
3199 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3200 meshlink_errno = MESHLINK_EPEER;
3204 if(!config_sync(mesh, "current")) {
3211 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3212 if(n == mesh->self) {
3213 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3214 meshlink_errno = MESHLINK_EINVAL;
3218 if(n->status.blacklisted) {
3219 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3223 n->status.blacklisted = true;
3225 /* Immediately shut down any connections we have with the blacklisted node.
3226 * We can't call terminate_connection(), because we might be called from a callback function.
3228 for list_each(connection_t, c, mesh->connections) {
3230 shutdown(c->socket, SHUT_RDWR);
3234 utcp_abort_all_connections(n->utcp);
3240 n->status.udp_confirmed = false;
3242 if(n->status.reachable) {
3243 n->last_unreachable = time(NULL);
3246 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3247 * manually call the status callback if necessary.
3249 if(n->status.reachable && mesh->node_status_cb) {
3250 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3253 return node_write_config(mesh, n) && config_sync(mesh, "current");
3256 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3257 if(!mesh || !node) {
3258 meshlink_errno = MESHLINK_EINVAL;
3262 pthread_mutex_lock(&mesh->mutex);
3264 if(!blacklist(mesh, (node_t *)node)) {
3265 pthread_mutex_unlock(&mesh->mutex);
3269 pthread_mutex_unlock(&mesh->mutex);
3271 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3275 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3276 if(!mesh || !name) {
3277 meshlink_errno = MESHLINK_EINVAL;
3281 pthread_mutex_lock(&mesh->mutex);
3283 node_t *n = lookup_node(mesh, (char *)name);
3287 n->name = xstrdup(name);
3291 if(!blacklist(mesh, (node_t *)n)) {
3292 pthread_mutex_unlock(&mesh->mutex);
3296 pthread_mutex_unlock(&mesh->mutex);
3298 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3302 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3303 if(n == mesh->self) {
3304 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3305 meshlink_errno = MESHLINK_EINVAL;
3309 if(!n->status.blacklisted) {
3310 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3314 n->status.blacklisted = false;
3316 if(n->status.reachable) {
3317 n->last_reachable = time(NULL);
3318 update_node_status(mesh, n);
3321 return node_write_config(mesh, n) && config_sync(mesh, "current");
3324 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3325 if(!mesh || !node) {
3326 meshlink_errno = MESHLINK_EINVAL;
3330 pthread_mutex_lock(&mesh->mutex);
3332 if(!whitelist(mesh, (node_t *)node)) {
3333 pthread_mutex_unlock(&mesh->mutex);
3337 pthread_mutex_unlock(&mesh->mutex);
3339 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3343 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3344 if(!mesh || !name) {
3345 meshlink_errno = MESHLINK_EINVAL;
3349 pthread_mutex_lock(&mesh->mutex);
3351 node_t *n = lookup_node(mesh, (char *)name);
3355 n->name = xstrdup(name);
3359 if(!whitelist(mesh, (node_t *)n)) {
3360 pthread_mutex_unlock(&mesh->mutex);
3364 pthread_mutex_unlock(&mesh->mutex);
3366 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3370 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3371 mesh->default_blacklist = blacklist;
3374 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3375 if(!mesh || !node) {
3376 meshlink_errno = MESHLINK_EINVAL;
3380 node_t *n = (node_t *)node;
3382 pthread_mutex_lock(&mesh->mutex);
3384 /* Check that the node is not reachable */
3385 if(n->status.reachable || n->connection) {
3386 pthread_mutex_unlock(&mesh->mutex);
3387 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3391 /* Check that we don't have any active UTCP connections */
3392 if(n->utcp && utcp_is_active(n->utcp)) {
3393 pthread_mutex_unlock(&mesh->mutex);
3394 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3398 /* Check that we have no active connections to this node */
3399 for list_each(connection_t, c, mesh->connections) {
3401 pthread_mutex_unlock(&mesh->mutex);
3402 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3407 /* Remove any pending outgoings to this node */
3408 if(mesh->outgoings) {
3409 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3410 if(outgoing->node == n) {
3411 list_delete_node(mesh->outgoings, node);
3416 /* Delete the config file for this node */
3417 if(!config_delete(mesh, "current", n->name)) {
3418 pthread_mutex_unlock(&mesh->mutex);
3422 /* Delete the node struct and any remaining edges referencing this node */
3425 pthread_mutex_unlock(&mesh->mutex);
3427 return config_sync(mesh, "current");
3430 /* Hint that a hostname may be found at an address
3431 * See header file for detailed comment.
3433 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3434 if(!mesh || !node || !addr) {
3435 meshlink_errno = EINVAL;
3439 pthread_mutex_lock(&mesh->mutex);
3441 node_t *n = (node_t *)node;
3443 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3444 if(!node_write_config(mesh, n)) {
3445 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3449 pthread_mutex_unlock(&mesh->mutex);
3450 // @TODO do we want to fire off a connection attempt right away?
3453 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3455 node_t *n = utcp->priv;
3456 meshlink_handle_t *mesh = n->mesh;
3457 return mesh->channel_accept_cb;
3460 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3462 if(aio->cb.buffer) {
3463 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3467 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3472 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3473 meshlink_channel_t *channel = connection->priv;
3479 node_t *n = channel->node;
3480 meshlink_handle_t *mesh = n->mesh;
3482 if(n->status.destroyed) {
3483 meshlink_channel_close(mesh, channel);
3487 const char *p = data;
3490 while(channel->aio_receive) {
3491 meshlink_aio_buffer_t *aio = channel->aio_receive;
3492 size_t todo = aio->len - aio->done;
3499 memcpy((char *)aio->data + aio->done, p, todo);
3501 ssize_t result = write(aio->fd, p, todo);
3510 if(aio->done == aio->len) {
3511 channel->aio_receive = aio->next;
3512 aio_signal(mesh, channel, aio);
3524 if(channel->receive_cb) {
3525 channel->receive_cb(mesh, channel, p, left);
3531 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3532 node_t *n = utcp_connection->utcp->priv;
3538 meshlink_handle_t *mesh = n->mesh;
3540 if(!mesh->channel_accept_cb) {
3544 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3546 channel->c = utcp_connection;
3548 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3549 utcp_accept(utcp_connection, channel_recv, channel);
3555 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3556 node_t *n = utcp->priv;
3558 if(n->status.destroyed) {
3562 meshlink_handle_t *mesh = n->mesh;
3563 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3566 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3567 if(!mesh || !channel) {
3568 meshlink_errno = MESHLINK_EINVAL;
3572 channel->receive_cb = cb;
3575 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3577 node_t *n = (node_t *)source;
3583 utcp_recv(n->utcp, data, len);
3586 static void channel_poll(struct utcp_connection *connection, size_t len) {
3587 meshlink_channel_t *channel = connection->priv;
3593 node_t *n = channel->node;
3594 meshlink_handle_t *mesh = n->mesh;
3595 meshlink_aio_buffer_t *aio = channel->aio_send;
3598 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3599 size_t left = aio->len - aio->done;
3607 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3610 size_t todo = utcp_get_sndbuf_free(connection);
3616 if(todo > sizeof(buf)) {
3620 ssize_t result = read(aio->fd, buf, todo);
3623 sent = utcp_send(connection, buf, result);
3633 /* If the buffer is now completely sent, call the callback and dispose of it. */
3634 if(aio->done >= aio->len) {
3635 channel->aio_send = aio->next;
3636 aio_signal(mesh, channel, aio);
3640 if(channel->poll_cb) {
3641 channel->poll_cb(mesh, channel, len);
3643 utcp_set_poll_cb(connection, NULL);
3648 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3649 if(!mesh || !channel) {
3650 meshlink_errno = MESHLINK_EINVAL;
3654 pthread_mutex_lock(&mesh->mutex);
3655 channel->poll_cb = cb;
3656 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3657 pthread_mutex_unlock(&mesh->mutex);
3660 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3662 meshlink_errno = MESHLINK_EINVAL;
3666 pthread_mutex_lock(&mesh->mutex);
3667 mesh->channel_accept_cb = cb;
3668 mesh->receive_cb = channel_receive;
3670 for splay_each(node_t, n, mesh->nodes) {
3671 if(!n->utcp && n != mesh->self) {
3672 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3673 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3677 pthread_mutex_unlock(&mesh->mutex);
3680 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3684 meshlink_errno = MESHLINK_EINVAL;
3688 pthread_mutex_lock(&mesh->mutex);
3689 utcp_set_sndbuf(channel->c, size);
3690 pthread_mutex_unlock(&mesh->mutex);
3693 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3697 meshlink_errno = MESHLINK_EINVAL;
3701 pthread_mutex_lock(&mesh->mutex);
3702 utcp_set_rcvbuf(channel->c, size);
3703 pthread_mutex_unlock(&mesh->mutex);
3706 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) {
3708 abort(); // TODO: handle non-NULL data
3711 if(!mesh || !node) {
3712 meshlink_errno = MESHLINK_EINVAL;
3716 pthread_mutex_lock(&mesh->mutex);
3718 node_t *n = (node_t *)node;
3721 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3722 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3723 mesh->receive_cb = channel_receive;
3726 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3727 pthread_mutex_unlock(&mesh->mutex);
3732 if(n->status.blacklisted) {
3733 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3734 meshlink_errno = MESHLINK_EBLACKLISTED;
3735 pthread_mutex_unlock(&mesh->mutex);
3739 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3741 channel->receive_cb = cb;
3744 channel->priv = (void *)data;
3747 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3749 pthread_mutex_unlock(&mesh->mutex);
3752 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3760 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) {
3761 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3764 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3765 if(!mesh || !channel) {
3766 meshlink_errno = MESHLINK_EINVAL;
3770 pthread_mutex_lock(&mesh->mutex);
3771 utcp_shutdown(channel->c, direction);
3772 pthread_mutex_unlock(&mesh->mutex);
3775 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3776 if(!mesh || !channel) {
3777 meshlink_errno = MESHLINK_EINVAL;
3781 pthread_mutex_lock(&mesh->mutex);
3783 utcp_close(channel->c);
3785 /* Clean up any outstanding AIO buffers. */
3786 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3788 aio_signal(mesh, channel, aio);
3792 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3794 aio_signal(mesh, channel, aio);
3798 pthread_mutex_unlock(&mesh->mutex);
3803 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3804 if(!mesh || !channel) {
3805 meshlink_errno = MESHLINK_EINVAL;
3814 meshlink_errno = MESHLINK_EINVAL;
3818 // TODO: more finegrained locking.
3819 // Ideally we want to put the data into the UTCP connection's send buffer.
3820 // Then, preferably only if there is room in the receiver window,
3821 // kick the meshlink thread to go send packets.
3825 pthread_mutex_lock(&mesh->mutex);
3827 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3828 if(channel->aio_send) {
3831 retval = utcp_send(channel->c, data, len);
3834 pthread_mutex_unlock(&mesh->mutex);
3837 meshlink_errno = MESHLINK_ENETWORK;
3843 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) {
3844 if(!mesh || !channel) {
3845 meshlink_errno = MESHLINK_EINVAL;
3850 meshlink_errno = MESHLINK_EINVAL;
3854 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3857 aio->cb.buffer = cb;
3860 pthread_mutex_lock(&mesh->mutex);
3862 /* Append the AIO buffer descriptor to the end of the chain */
3863 meshlink_aio_buffer_t **p = &channel->aio_send;
3871 /* Ensure the poll callback is set, and call it right now to push data if possible */
3872 utcp_set_poll_cb(channel->c, channel_poll);
3873 channel_poll(channel->c, len);
3875 pthread_mutex_unlock(&mesh->mutex);
3880 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) {
3881 if(!mesh || !channel) {
3882 meshlink_errno = MESHLINK_EINVAL;
3886 if(!len || fd == -1) {
3887 meshlink_errno = MESHLINK_EINVAL;
3891 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3897 pthread_mutex_lock(&mesh->mutex);
3899 /* Append the AIO buffer descriptor to the end of the chain */
3900 meshlink_aio_buffer_t **p = &channel->aio_send;
3908 /* Ensure the poll callback is set, and call it right now to push data if possible */
3909 utcp_set_poll_cb(channel->c, channel_poll);
3910 channel_poll(channel->c, len);
3912 pthread_mutex_unlock(&mesh->mutex);
3917 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) {
3918 if(!mesh || !channel) {
3919 meshlink_errno = MESHLINK_EINVAL;
3924 meshlink_errno = MESHLINK_EINVAL;
3928 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3931 aio->cb.buffer = cb;
3934 pthread_mutex_lock(&mesh->mutex);
3936 /* Append the AIO buffer descriptor to the end of the chain */
3937 meshlink_aio_buffer_t **p = &channel->aio_receive;
3945 pthread_mutex_unlock(&mesh->mutex);
3950 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) {
3951 if(!mesh || !channel) {
3952 meshlink_errno = MESHLINK_EINVAL;
3956 if(!len || fd == -1) {
3957 meshlink_errno = MESHLINK_EINVAL;
3961 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3967 pthread_mutex_lock(&mesh->mutex);
3969 /* Append the AIO buffer descriptor to the end of the chain */
3970 meshlink_aio_buffer_t **p = &channel->aio_receive;
3978 pthread_mutex_unlock(&mesh->mutex);
3983 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3984 if(!mesh || !channel) {
3985 meshlink_errno = MESHLINK_EINVAL;
3989 return channel->c->flags;
3992 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3993 if(!mesh || !channel) {
3994 meshlink_errno = MESHLINK_EINVAL;
3998 return utcp_get_sendq(channel->c);
4001 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4002 if(!mesh || !channel) {
4003 meshlink_errno = MESHLINK_EINVAL;
4007 return utcp_get_recvq(channel->c);
4010 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4011 if(!mesh || !channel) {
4012 meshlink_errno = MESHLINK_EINVAL;
4016 return utcp_get_mss(channel->node->utcp);
4019 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
4020 if(!mesh || !node) {
4021 meshlink_errno = MESHLINK_EINVAL;
4025 node_t *n = (node_t *)node;
4027 pthread_mutex_lock(&mesh->mutex);
4030 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4031 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4034 utcp_set_user_timeout(n->utcp, timeout);
4036 pthread_mutex_unlock(&mesh->mutex);
4039 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4040 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4041 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4042 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4045 if(mesh->node_status_cb) {
4046 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4049 if(mesh->node_pmtu_cb) {
4050 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4054 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4055 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4057 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4058 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4062 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4063 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4067 n->status.duplicate = true;
4068 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4071 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4075 meshlink_errno = MESHLINK_EINVAL;
4079 pthread_mutex_lock(&mesh->mutex);
4081 if(mesh->discovery == enable) {
4085 if(mesh->threadstarted) {
4087 discovery_start(mesh);
4089 discovery_stop(mesh);
4093 mesh->discovery = enable;
4096 pthread_mutex_unlock(&mesh->mutex);
4100 meshlink_errno = MESHLINK_ENOTSUP;
4104 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4105 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4106 meshlink_errno = EINVAL;
4110 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4111 meshlink_errno = EINVAL;
4115 pthread_mutex_lock(&mesh->mutex);
4116 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4117 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4118 pthread_mutex_unlock(&mesh->mutex);
4121 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4122 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4123 meshlink_errno = EINVAL;
4127 if(fast_retry_period < 0) {
4128 meshlink_errno = EINVAL;
4132 pthread_mutex_lock(&mesh->mutex);
4133 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4134 pthread_mutex_unlock(&mesh->mutex);
4137 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4139 meshlink_errno = EINVAL;
4143 pthread_mutex_lock(&mesh->mutex);
4144 mesh->inviter_commits_first = inviter_commits_first;
4145 pthread_mutex_unlock(&mesh->mutex);
4148 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4150 meshlink_errno = EINVAL;
4154 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4155 meshlink_errno = EINVAL;
4159 pthread_mutex_lock(&mesh->mutex);
4160 free(mesh->external_address_url);
4161 mesh->external_address_url = url ? xstrdup(url) : NULL;
4162 pthread_mutex_unlock(&mesh->mutex);
4165 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4168 if(!mesh->connections || !mesh->loop.running) {
4175 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
4176 // We should only call the callback function if we are in the background thread.
4177 if(!mesh->error_cb) {
4181 if(!mesh->threadstarted) {
4185 if(mesh->thread == pthread_self()) {
4186 mesh->error_cb(mesh, meshlink_errno);
4190 static void __attribute__((constructor)) meshlink_init(void) {
4194 static void __attribute__((destructor)) meshlink_exit(void) {