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.
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 void get_canonical_address(node_t *n, char **hostname, char **port) {
64 if(!n->canonical_address) {
68 *hostname = xstrdup(n->canonical_address);
69 char *space = strchr(*hostname, ' ');
73 *port = xstrdup(space);
77 static bool is_valid_hostname(const char *hostname) {
82 for(const char *p = hostname; *p; p++) {
83 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
91 static bool is_valid_port(const char *port) {
98 unsigned long int result = strtoul(port, &end, 10);
99 return result && result < 65536 && !*end;
102 for(const char *p = port; *p; p++) {
103 if(!(isalnum(*p) || *p == '-')) {
111 static void set_timeout(int sock, int timeout) {
116 tv.tv_sec = timeout / 1000;
117 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
119 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
120 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
123 struct socket_in_netns_params {
132 static void *socket_in_netns_thread(void *arg) {
133 struct socket_in_netns_params *params = arg;
135 if(setns(params->netns, CLONE_NEWNET) == -1) {
136 meshlink_errno = MESHLINK_EINVAL;
140 params->fd = socket(params->domain, params->type, params->protocol);
146 static int socket_in_netns(int domain, int type, int protocol, int netns) {
148 return socket(domain, type, protocol);
152 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
156 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
157 assert(pthread_join(thr, NULL) == 0);
167 // Find out what local address a socket would use if we connect to the given address.
168 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
169 // of both endpoints, but this will actually not send any UDP packet.
170 static bool getlocaladdr(const char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
171 struct addrinfo *rai = NULL;
172 const struct addrinfo hint = {
173 .ai_family = AF_UNSPEC,
174 .ai_socktype = SOCK_DGRAM,
175 .ai_protocol = IPPROTO_UDP,
176 .ai_flags = AI_NUMERICHOST | AI_NUMERICSERV,
179 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
183 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
190 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
198 if(getsockname(sock, &sa->sa, salen)) {
207 static bool getlocaladdrname(const char *destaddr, char *host, socklen_t hostlen, int netns) {
209 socklen_t salen = sizeof(sa);
211 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
215 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
222 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
223 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
226 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
227 const char *url = mesh->external_address_url;
230 url = "http://meshlink.io/host.cgi";
233 /* Find the hostname part between the slashes */
234 if(strncmp(url, "http://", 7)) {
236 meshlink_errno = MESHLINK_EINTERNAL;
240 const char *begin = url + 7;
242 const char *end = strchr(begin, '/');
245 end = begin + strlen(begin);
249 char host[end - begin + 1];
250 strncpy(host, begin, end - begin);
251 host[end - begin] = 0;
253 char *port = strchr(host, ':');
259 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
260 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(host), xstrdup(port ? port : "80"), SOCK_STREAM, 5);
262 char *hostname = NULL;
264 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
265 if(family != AF_UNSPEC && aip->ai_family != family) {
269 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
273 setsockopt(s, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
277 set_timeout(s, 5000);
279 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
286 send(s, "GET ", 4, 0);
287 send(s, url, strlen(url), 0);
288 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
289 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
294 if(line[len - 1] == '\n') {
298 char *p = strrchr(line, '\n');
301 hostname = xstrdup(p + 1);
317 // Check that the hostname is reasonable
318 if(hostname && !is_valid_hostname(hostname)) {
324 meshlink_errno = MESHLINK_ERESOLV;
330 static bool is_localaddr(sockaddr_t *sa) {
331 switch(sa->sa.sa_family) {
333 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
336 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
337 return first == 0 || (first & 0xffc0) == 0xfe80;
345 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
348 // Determine address of the local interface used for outgoing connections.
349 char localaddr[NI_MAXHOST];
350 bool success = false;
352 if(family == AF_INET) {
353 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
354 } else if(family == AF_INET6) {
355 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
358 #ifdef HAVE_GETIFADDRS
361 struct ifaddrs *ifa = NULL;
364 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
365 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
367 if(sa->sa.sa_family != family) {
371 if(is_localaddr(sa)) {
375 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
387 meshlink_errno = MESHLINK_ENETWORK;
391 return xstrdup(localaddr);
394 static void remove_duplicate_hostnames(char *host[], char *port[], int n) {
395 for(int i = 0; i < n; i++) {
400 // Ignore duplicate hostnames
403 for(int j = 0; j < i; j++) {
408 if(strcmp(host[i], host[j])) {
412 if(strcmp(port[i], port[j])) {
420 if(found || !is_valid_hostname(host[i])) {
430 // This gets the hostname part for use in invitation URLs
431 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
432 int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
434 char *hostname[count];
436 char *hostport = NULL;
438 memset(hostname, 0, sizeof(hostname));
439 memset(port, 0, sizeof(port));
441 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
442 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
445 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
446 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
449 // Add all explicitly set invitation addresses
450 if(mesh->invitation_addresses) {
451 for list_each(char, combo, mesh->invitation_addresses) {
452 hostname[n] = xstrdup(combo);
453 char *slash = strrchr(hostname[n], '/');
457 port[n] = xstrdup(slash + 1);
464 // Add local addresses if requested
465 if(flags & MESHLINK_INVITE_LOCAL) {
466 if(flags & MESHLINK_INVITE_IPV4) {
467 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
470 if(flags & MESHLINK_INVITE_IPV6) {
471 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
475 // Add public/canonical addresses if requested
476 if(flags & MESHLINK_INVITE_PUBLIC) {
477 // Try the CanonicalAddress first
478 get_canonical_address(mesh->self, &hostname[n], &port[n]);
480 if(!hostname[n] && count == 4) {
481 if(flags & MESHLINK_INVITE_IPV4) {
482 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
485 if(flags & MESHLINK_INVITE_IPV6) {
486 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
493 for(int i = 0; i < n; i++) {
494 // Ensure we always have a port number
495 if(hostname[i] && !port[i]) {
496 port[i] = xstrdup(mesh->myport);
500 remove_duplicate_hostnames(hostname, port, n);
502 // Resolve the hostnames
503 for(int i = 0; i < n; i++) {
508 // Convert what we have to a sockaddr
509 struct addrinfo *ai_in = adns_blocking_request(mesh, xstrdup(hostname[i]), xstrdup(port[i]), SOCK_STREAM, 5);
515 // Remember the address(es)
516 for(struct addrinfo *aip = ai_in; aip; aip = aip->ai_next) {
517 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)aip->ai_addr);
524 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
525 remove_duplicate_hostnames(hostname, port, n);
527 // Concatenate all unique address to the hostport string
528 for(int i = 0; i < n; i++) {
533 // Append the address to the hostport string
535 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
537 hostport = newhostport;
546 static bool try_bind(meshlink_handle_t *mesh, int port) {
547 struct addrinfo *ai = NULL;
548 struct addrinfo hint = {
549 .ai_flags = AI_PASSIVE,
550 .ai_family = AF_UNSPEC,
551 .ai_socktype = SOCK_STREAM,
552 .ai_protocol = IPPROTO_TCP,
556 snprintf(portstr, sizeof(portstr), "%d", port);
558 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
562 bool success = false;
564 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
565 /* Try to bind to TCP. */
567 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
570 if(errno == EADDRINUSE) {
571 /* If this port is in use for any address family, avoid it. */
579 /* If TCP worked, then we require that UDP works as well. */
581 int udp_fd = setup_udp_listen_socket(mesh, aip);
598 int check_port(meshlink_handle_t *mesh) {
599 for(int i = 0; i < 1000; i++) {
600 int port = 0x1000 + prng(mesh, 0x8000);
602 if(try_bind(mesh, port)) {
604 xasprintf(&mesh->myport, "%d", port);
609 meshlink_errno = MESHLINK_ENETWORK;
610 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
614 static bool write_main_config_files(meshlink_handle_t *mesh) {
615 if(!mesh->confbase) {
621 /* Write the main config file */
622 packmsg_output_t out = {buf, sizeof buf};
624 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
625 packmsg_add_str(&out, mesh->name);
626 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
627 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
628 packmsg_add_uint16(&out, atoi(mesh->myport));
630 if(!packmsg_output_ok(&out)) {
634 config_t config = {buf, packmsg_output_size(&out, buf)};
636 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
640 /* Write our own host config file */
641 if(!node_write_config(mesh, mesh->self)) {
649 meshlink_handle_t *mesh;
651 char cookie[18 + 32];
662 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
663 meshlink_handle_t *mesh = state->mesh;
664 packmsg_input_t in = {buf, len};
665 uint32_t version = packmsg_get_uint32(&in);
667 if(version != MESHLINK_INVITATION_VERSION) {
668 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
672 char *name = packmsg_get_str_dup(&in);
673 char *submesh_name = packmsg_get_str_dup(&in);
674 dev_class_t devclass = packmsg_get_int32(&in);
675 uint32_t count = packmsg_get_array(&in);
677 if(!name || !check_id(name)) {
678 logger(mesh, MESHLINK_DEBUG, "No valid Name found in invitation!\n");
684 if(!submesh_name || (strcmp(submesh_name, CORE_MESH) && !check_id(submesh_name))) {
685 logger(mesh, MESHLINK_DEBUG, "No valid Submesh found in invitation!\n");
692 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
699 free(mesh->self->name);
701 mesh->self->name = xstrdup(name);
702 mesh->self->submesh = strcmp(submesh_name, CORE_MESH) ? lookup_or_create_submesh(mesh, submesh_name) : NULL;
704 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
706 // Initialize configuration directory
707 if(!config_init(mesh, "current")) {
711 if(!write_main_config_files(mesh)) {
715 // Write host config files
716 for(uint32_t i = 0; i < count; i++) {
718 uint32_t data_len = packmsg_get_bin_raw(&in, &data);
721 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
725 packmsg_input_t in2 = {data, data_len};
726 uint32_t version2 = packmsg_get_uint32(&in2);
727 char *name2 = packmsg_get_str_dup(&in2);
729 if(!packmsg_input_ok(&in2) || version2 != MESHLINK_CONFIG_VERSION || !check_id(name2)) {
731 packmsg_input_invalidate(&in);
735 if(!check_id(name2)) {
740 if(!strcmp(name2, mesh->name)) {
741 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
743 meshlink_errno = MESHLINK_EPEER;
747 node_t *n = new_node();
750 config_t config = {data, data_len};
752 if(!node_read_from_config(mesh, n, &config)) {
754 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
755 meshlink_errno = MESHLINK_EPEER;
760 /* The first host config file is of the inviter itself;
761 * remember the address we are currently using for the invitation connection.
764 socklen_t salen = sizeof(sa);
766 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
767 node_add_recent_address(mesh, n, &sa);
771 /* Clear the reachability times, since we ourself have never seen these nodes yet */
772 n->last_reachable = 0;
773 n->last_unreachable = 0;
775 if(!node_write_config(mesh, n)) {
783 /* Ensure the configuration directory metadata is on disk */
784 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
788 if(!mesh->inviter_commits_first) {
789 devtool_set_inviter_commits_first(false);
792 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
794 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
799 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
801 join_state_t *state = handle;
802 const char *ptr = data;
805 int result = send(state->sock, ptr, len, 0);
807 if(result == -1 && errno == EINTR) {
809 } else if(result <= 0) {
820 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
821 join_state_t *state = handle;
822 meshlink_handle_t *mesh = state->mesh;
824 if(mesh->inviter_commits_first) {
826 case SPTPS_HANDSHAKE:
827 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
833 if(!finalize_join(state, msg, len)) {
837 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
838 shutdown(state->sock, SHUT_RDWR);
839 state->success = true;
847 case SPTPS_HANDSHAKE:
848 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
851 return finalize_join(state, msg, len);
854 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
855 shutdown(state->sock, SHUT_RDWR);
856 state->success = true;
867 static bool recvline(join_state_t *state) {
868 char *newline = NULL;
870 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
871 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
873 if(result == -1 && errno == EINTR) {
875 } else if(result <= 0) {
879 state->blen += result;
882 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
886 size_t len = newline - state->buffer;
888 memcpy(state->line, state->buffer, len);
889 state->line[len] = 0;
890 memmove(state->buffer, newline + 1, state->blen - len - 1);
891 state->blen -= len + 1;
896 static bool sendline(int fd, const char *format, ...) {
902 va_start(ap, format);
903 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
906 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
914 int result = send(fd, p, blen, MSG_NOSIGNAL);
916 if(result == -1 && errno == EINTR) {
918 } else if(result <= 0) {
929 static const char *errstr[] = {
930 [MESHLINK_OK] = "No error",
931 [MESHLINK_EINVAL] = "Invalid argument",
932 [MESHLINK_ENOMEM] = "Out of memory",
933 [MESHLINK_ENOENT] = "No such node",
934 [MESHLINK_EEXIST] = "Node already exists",
935 [MESHLINK_EINTERNAL] = "Internal error",
936 [MESHLINK_ERESOLV] = "Could not resolve hostname",
937 [MESHLINK_ESTORAGE] = "Storage error",
938 [MESHLINK_ENETWORK] = "Network error",
939 [MESHLINK_EPEER] = "Error communicating with peer",
940 [MESHLINK_ENOTSUP] = "Operation not supported",
941 [MESHLINK_EBUSY] = "MeshLink instance already in use",
942 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
945 const char *meshlink_strerror(meshlink_errno_t err) {
946 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
947 return "Invalid error code";
953 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
954 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
956 mesh->private_key = ecdsa_generate();
957 mesh->invitation_key = ecdsa_generate();
959 if(!mesh->private_key || !mesh->invitation_key) {
960 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
961 meshlink_errno = MESHLINK_EINTERNAL;
965 logger(mesh, MESHLINK_DEBUG, "Done.\n");
970 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
971 if(a->tv_sec == b->tv_sec) {
972 return a->tv_nsec < b->tv_nsec;
974 return a->tv_sec < b->tv_sec;
978 static struct timespec idle(event_loop_t *loop, void *data) {
980 meshlink_handle_t *mesh = data;
981 struct timespec t, tmin = {3600, 0};
983 for splay_each(node_t, n, mesh->nodes) {
988 t = utcp_timeout(n->utcp);
990 if(timespec_lt(&t, &tmin)) {
998 // Get our local address(es) by simulating connecting to an Internet host.
999 static void add_local_addresses(meshlink_handle_t *mesh) {
1001 sa.storage.ss_family = AF_UNKNOWN;
1002 socklen_t salen = sizeof(sa);
1006 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
1007 sa.in.sin_port = ntohs(atoi(mesh->myport));
1008 node_add_recent_address(mesh, mesh->self, &sa);
1015 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
1016 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
1017 node_add_recent_address(mesh, mesh->self, &sa);
1021 static bool meshlink_setup(meshlink_handle_t *mesh) {
1022 if(!config_destroy(mesh->confbase, "new")) {
1023 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1024 meshlink_errno = MESHLINK_ESTORAGE;
1028 if(!config_destroy(mesh->confbase, "old")) {
1029 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1030 meshlink_errno = MESHLINK_ESTORAGE;
1034 if(!config_init(mesh, "current")) {
1035 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1036 meshlink_errno = MESHLINK_ESTORAGE;
1040 if(!ecdsa_keygen(mesh)) {
1041 meshlink_errno = MESHLINK_EINTERNAL;
1045 if(check_port(mesh) == 0) {
1046 meshlink_errno = MESHLINK_ENETWORK;
1050 /* Create a node for ourself */
1052 mesh->self = new_node();
1053 mesh->self->name = xstrdup(mesh->name);
1054 mesh->self->devclass = mesh->devclass;
1055 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1056 mesh->self->session_id = mesh->session_id;
1058 if(!write_main_config_files(mesh)) {
1059 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1060 meshlink_errno = MESHLINK_ESTORAGE;
1064 /* Ensure the configuration directory metadata is on disk */
1065 if(!config_sync(mesh, "current")) {
1072 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1075 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1076 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1080 packmsg_input_t in = {config.buf, config.len};
1081 const void *private_key;
1082 const void *invitation_key;
1084 uint32_t version = packmsg_get_uint32(&in);
1085 char *name = packmsg_get_str_dup(&in);
1086 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1087 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1088 uint16_t myport = packmsg_get_uint16(&in);
1090 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1091 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1093 config_free(&config);
1097 if(mesh->name && strcmp(mesh->name, name)) {
1098 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1099 meshlink_errno = MESHLINK_ESTORAGE;
1101 config_free(&config);
1107 xasprintf(&mesh->myport, "%u", myport);
1108 mesh->private_key = ecdsa_set_private_key(private_key);
1109 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1110 config_free(&config);
1112 /* Create a node for ourself and read our host configuration file */
1114 mesh->self = new_node();
1115 mesh->self->name = xstrdup(name);
1116 mesh->self->devclass = mesh->devclass;
1117 mesh->self->session_id = mesh->session_id;
1119 if(!node_read_public_key(mesh, mesh->self)) {
1120 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1121 meshlink_errno = MESHLINK_ESTORAGE;
1122 free_node(mesh->self);
1131 static void *setup_network_in_netns_thread(void *arg) {
1132 meshlink_handle_t *mesh = arg;
1134 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1138 bool success = setup_network(mesh);
1139 return success ? arg : NULL;
1141 #endif // HAVE_SETNS
1143 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1144 if(!confbase || !*confbase) {
1145 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1146 meshlink_errno = MESHLINK_EINVAL;
1150 if(!appname || !*appname) {
1151 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1152 meshlink_errno = MESHLINK_EINVAL;
1156 if(strchr(appname, ' ')) {
1157 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1158 meshlink_errno = MESHLINK_EINVAL;
1162 if(name && !check_id(name)) {
1163 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1164 meshlink_errno = MESHLINK_EINVAL;
1168 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1169 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1170 meshlink_errno = MESHLINK_EINVAL;
1174 meshlink_open_params_t *params = xzalloc(sizeof * params);
1176 params->confbase = xstrdup(confbase);
1177 params->name = name ? xstrdup(name) : NULL;
1178 params->appname = xstrdup(appname);
1179 params->devclass = devclass;
1185 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1187 meshlink_errno = MESHLINK_EINVAL;
1191 params->netns = netns;
1196 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1198 meshlink_errno = MESHLINK_EINVAL;
1202 if((!key && keylen) || (key && !keylen)) {
1203 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1204 meshlink_errno = MESHLINK_EINVAL;
1209 params->keylen = keylen;
1214 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1215 if(!mesh || !new_key || !new_keylen) {
1216 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1217 meshlink_errno = MESHLINK_EINVAL;
1221 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1223 // Create hash for the new key
1224 void *new_config_key;
1225 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1227 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1228 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1229 meshlink_errno = MESHLINK_EINTERNAL;
1230 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1234 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1236 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1237 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1238 meshlink_errno = MESHLINK_ESTORAGE;
1239 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1243 devtool_keyrotate_probe(1);
1245 // Rename confbase/current/ to confbase/old
1247 if(!config_rename(mesh, "current", "old")) {
1248 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1249 meshlink_errno = MESHLINK_ESTORAGE;
1250 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1254 devtool_keyrotate_probe(2);
1256 // Rename confbase/new/ to confbase/current
1258 if(!config_rename(mesh, "new", "current")) {
1259 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1260 meshlink_errno = MESHLINK_ESTORAGE;
1261 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1265 devtool_keyrotate_probe(3);
1267 // Cleanup the "old" confbase sub-directory
1269 if(!config_destroy(mesh->confbase, "old")) {
1270 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1274 // Change the mesh handle key with new key
1276 free(mesh->config_key);
1277 mesh->config_key = new_config_key;
1279 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1284 void meshlink_open_params_free(meshlink_open_params_t *params) {
1286 meshlink_errno = MESHLINK_EINVAL;
1290 free(params->confbase);
1292 free(params->appname);
1297 /// Device class traits
1298 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1299 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1300 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1301 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1302 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1305 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1306 if(!confbase || !*confbase) {
1307 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1308 meshlink_errno = MESHLINK_EINVAL;
1312 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1313 meshlink_open_params_t params;
1314 memset(¶ms, 0, sizeof(params));
1316 params.confbase = (char *)confbase;
1317 params.name = (char *)name;
1318 params.appname = (char *)appname;
1319 params.devclass = devclass;
1322 return meshlink_open_ex(¶ms);
1325 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) {
1326 if(!confbase || !*confbase) {
1327 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1328 meshlink_errno = MESHLINK_EINVAL;
1332 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1333 meshlink_open_params_t params;
1334 memset(¶ms, 0, sizeof(params));
1336 params.confbase = (char *)confbase;
1337 params.name = (char *)name;
1338 params.appname = (char *)appname;
1339 params.devclass = devclass;
1342 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1346 return meshlink_open_ex(¶ms);
1349 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1351 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1352 meshlink_errno = MESHLINK_EINVAL;
1356 if(!check_id(name)) {
1357 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1358 meshlink_errno = MESHLINK_EINVAL;
1362 if(!appname || !*appname) {
1363 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1364 meshlink_errno = MESHLINK_EINVAL;
1368 if(strchr(appname, ' ')) {
1369 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1370 meshlink_errno = MESHLINK_EINVAL;
1374 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1375 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1376 meshlink_errno = MESHLINK_EINVAL;
1380 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1381 meshlink_open_params_t params;
1382 memset(¶ms, 0, sizeof(params));
1384 params.name = (char *)name;
1385 params.appname = (char *)appname;
1386 params.devclass = devclass;
1389 return meshlink_open_ex(¶ms);
1392 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1393 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1395 // Validate arguments provided by the application
1396 if(!params->appname || !*params->appname) {
1397 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1398 meshlink_errno = MESHLINK_EINVAL;
1402 if(strchr(params->appname, ' ')) {
1403 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1404 meshlink_errno = MESHLINK_EINVAL;
1408 if(params->name && !check_id(params->name)) {
1409 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1410 meshlink_errno = MESHLINK_EINVAL;
1414 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1415 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1416 meshlink_errno = MESHLINK_EINVAL;
1420 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1421 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1422 meshlink_errno = MESHLINK_EINVAL;
1426 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1428 if(params->confbase) {
1429 mesh->confbase = xstrdup(params->confbase);
1432 mesh->appname = xstrdup(params->appname);
1433 mesh->devclass = params->devclass;
1434 mesh->discovery = true;
1435 mesh->invitation_timeout = 604800; // 1 week
1436 mesh->netns = params->netns;
1437 mesh->submeshes = NULL;
1438 mesh->log_cb = global_log_cb;
1439 mesh->log_level = global_log_level;
1440 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1442 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1445 randomize(&mesh->session_id, sizeof(mesh->session_id));
1446 } while(mesh->session_id == 0);
1448 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1450 mesh->name = params->name ? xstrdup(params->name) : NULL;
1454 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1456 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1457 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1458 meshlink_close(mesh);
1459 meshlink_errno = MESHLINK_EINTERNAL;
1464 // initialize mutexes and conds
1465 pthread_mutexattr_t attr;
1466 assert(pthread_mutexattr_init(&attr) == 0);
1467 assert(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE) == 0);
1468 assert(pthread_mutex_init(&mesh->mutex, &attr) == 0);
1469 assert(pthread_cond_init(&mesh->cond, NULL) == 0);
1471 assert(pthread_mutex_init(&mesh->discovery_mutex, NULL) == 0);
1472 assert(pthread_cond_init(&mesh->discovery_cond, NULL) == 0);
1474 assert(pthread_cond_init(&mesh->adns_cond, NULL) == 0);
1476 mesh->threadstarted = false;
1477 event_loop_init(&mesh->loop);
1478 mesh->loop.data = mesh;
1480 meshlink_queue_init(&mesh->outpacketqueue);
1482 // Atomically lock the configuration directory.
1483 if(!main_config_lock(mesh)) {
1484 meshlink_close(mesh);
1488 // If no configuration exists yet, create it.
1490 if(!meshlink_confbase_exists(mesh)) {
1492 logger(NULL, MESHLINK_ERROR, "No configuration files found!\n");
1493 meshlink_close(mesh);
1494 meshlink_errno = MESHLINK_ESTORAGE;
1498 if(!meshlink_setup(mesh)) {
1499 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1500 meshlink_close(mesh);
1504 if(!meshlink_read_config(mesh)) {
1505 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1506 meshlink_close(mesh);
1512 struct WSAData wsa_state;
1513 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1516 // Setup up everything
1517 // TODO: we should not open listening sockets yet
1519 bool success = false;
1521 if(mesh->netns != -1) {
1525 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1526 void *retval = NULL;
1527 success = pthread_join(thr, &retval) == 0 && retval;
1531 meshlink_errno = MESHLINK_EINTERNAL;
1534 #endif // HAVE_SETNS
1536 success = setup_network(mesh);
1540 meshlink_close(mesh);
1541 meshlink_errno = MESHLINK_ENETWORK;
1545 add_local_addresses(mesh);
1547 if(!node_write_config(mesh, mesh->self)) {
1548 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1552 idle_set(&mesh->loop, idle, mesh);
1554 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1558 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1559 meshlink_submesh_t *s = NULL;
1562 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1563 meshlink_errno = MESHLINK_EINVAL;
1567 if(!submesh || !*submesh) {
1568 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1569 meshlink_errno = MESHLINK_EINVAL;
1574 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1576 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1578 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1583 static void *meshlink_main_loop(void *arg) {
1584 meshlink_handle_t *mesh = arg;
1586 if(mesh->netns != -1) {
1589 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1590 assert(pthread_cond_signal(&mesh->cond) == 0);
1595 assert(pthread_cond_signal(&mesh->cond) == 0);
1597 #endif // HAVE_SETNS
1602 if(mesh->discovery) {
1603 discovery_start(mesh);
1608 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1610 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1611 assert(pthread_cond_broadcast(&mesh->cond) == 0);
1613 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1615 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1620 if(mesh->discovery) {
1621 discovery_stop(mesh);
1629 bool meshlink_start(meshlink_handle_t *mesh) {
1631 meshlink_errno = MESHLINK_EINVAL;
1635 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1637 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1640 assert(mesh->private_key);
1641 assert(mesh->self->ecdsa);
1642 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1644 if(mesh->threadstarted) {
1645 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1646 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1650 if(mesh->listen_socket[0].tcp.fd < 0) {
1651 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1652 meshlink_errno = MESHLINK_ENETWORK;
1656 // TODO: open listening sockets first
1658 //Check that a valid name is set
1660 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1661 meshlink_errno = MESHLINK_EINVAL;
1662 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1666 init_outgoings(mesh);
1669 // Start the main thread
1671 event_loop_start(&mesh->loop);
1673 // Ensure we have a decent amount of stack space. Musl's default of 80 kB is too small.
1674 pthread_attr_t attr;
1675 assert(pthread_attr_init(&attr) == 0);
1676 assert(pthread_attr_setstacksize(&attr, 1024 * 1024) == 0);
1678 if(pthread_create(&mesh->thread, &attr, meshlink_main_loop, mesh) != 0) {
1679 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1680 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1681 meshlink_errno = MESHLINK_EINTERNAL;
1682 event_loop_stop(&mesh->loop);
1683 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1687 assert(pthread_cond_wait(&mesh->cond, &mesh->mutex) == 0);
1688 mesh->threadstarted = true;
1690 // Ensure we are considered reachable
1693 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1697 void meshlink_stop(meshlink_handle_t *mesh) {
1699 meshlink_errno = MESHLINK_EINVAL;
1703 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1704 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1706 // Shut down the main thread
1707 event_loop_stop(&mesh->loop);
1709 // Send ourselves a UDP packet to kick the event loop
1710 for(int i = 0; i < mesh->listen_sockets; i++) {
1712 socklen_t salen = sizeof(sa);
1714 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1715 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1719 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1720 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1724 if(mesh->threadstarted) {
1725 // Wait for the main thread to finish
1726 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1727 assert(pthread_join(mesh->thread, NULL) == 0);
1728 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1730 mesh->threadstarted = false;
1733 // Close all metaconnections
1734 if(mesh->connections) {
1735 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1737 connection_t *c = node->data;
1739 terminate_connection(mesh, c, false);
1744 exit_outgoings(mesh);
1746 // Ensure we are considered unreachable
1751 // Try to write out any changed node config files, ignore errors at this point.
1753 for splay_each(node_t, n, mesh->nodes) {
1754 if(n->status.dirty) {
1755 n->status.dirty = !node_write_config(mesh, n);
1760 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1763 void meshlink_close(meshlink_handle_t *mesh) {
1765 meshlink_errno = MESHLINK_EINVAL;
1769 // stop can be called even if mesh has not been started
1770 meshlink_stop(mesh);
1772 // lock is not released after this
1773 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1775 // Close and free all resources used.
1777 close_network_connections(mesh);
1779 logger(mesh, MESHLINK_INFO, "Terminating");
1781 event_loop_exit(&mesh->loop);
1785 if(mesh->confbase) {
1791 ecdsa_free(mesh->invitation_key);
1793 if(mesh->netns != -1) {
1797 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1801 meshlink_queue_exit(&mesh->outpacketqueue);
1804 free(mesh->appname);
1805 free(mesh->confbase);
1806 free(mesh->config_key);
1807 free(mesh->external_address_url);
1809 ecdsa_free(mesh->private_key);
1811 if(mesh->invitation_addresses) {
1812 list_delete_list(mesh->invitation_addresses);
1815 main_config_unlock(mesh);
1817 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1818 assert(pthread_mutex_destroy(&mesh->mutex) == 0);
1820 memset(mesh, 0, sizeof(*mesh));
1825 bool meshlink_destroy(const char *confbase) {
1827 meshlink_errno = MESHLINK_EINVAL;
1831 /* Exit early if the confbase directory itself doesn't exist */
1832 if(access(confbase, F_OK) && errno == ENOENT) {
1836 /* Take the lock the same way meshlink_open() would. */
1837 char lockfilename[PATH_MAX];
1838 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1840 FILE *lockfile = fopen(lockfilename, "w+");
1843 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1844 meshlink_errno = MESHLINK_ESTORAGE;
1849 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1853 // TODO: use _locking()?
1856 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1857 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1859 meshlink_errno = MESHLINK_EBUSY;
1865 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1866 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1870 if(unlink(lockfilename)) {
1871 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1873 meshlink_errno = MESHLINK_ESTORAGE;
1879 if(!sync_path(confbase)) {
1880 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1881 meshlink_errno = MESHLINK_ESTORAGE;
1888 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1890 meshlink_errno = MESHLINK_EINVAL;
1894 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1895 mesh->receive_cb = cb;
1896 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1899 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1901 meshlink_errno = MESHLINK_EINVAL;
1905 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1906 mesh->connection_try_cb = cb;
1907 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1910 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1912 meshlink_errno = MESHLINK_EINVAL;
1916 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1917 mesh->node_status_cb = cb;
1918 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1921 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1923 meshlink_errno = MESHLINK_EINVAL;
1927 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1928 mesh->node_pmtu_cb = cb;
1929 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1932 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1934 meshlink_errno = MESHLINK_EINVAL;
1938 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1939 mesh->node_duplicate_cb = cb;
1940 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1943 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1945 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1947 mesh->log_level = cb ? level : 0;
1948 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1951 global_log_level = cb ? level : 0;
1955 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1957 meshlink_errno = MESHLINK_EINVAL;
1961 assert(pthread_mutex_lock(&mesh->mutex) == 0);
1962 mesh->error_cb = cb;
1963 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
1966 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1967 meshlink_packethdr_t *hdr;
1969 if(len > MAXSIZE - sizeof(*hdr)) {
1970 meshlink_errno = MESHLINK_EINVAL;
1974 node_t *n = (node_t *)destination;
1976 if(n->status.blacklisted) {
1977 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1978 meshlink_errno = MESHLINK_EBLACKLISTED;
1982 // Prepare the packet
1983 packet->probe = false;
1984 packet->tcp = false;
1985 packet->len = len + sizeof(*hdr);
1987 hdr = (meshlink_packethdr_t *)packet->data;
1988 memset(hdr, 0, sizeof(*hdr));
1989 // leave the last byte as 0 to make sure strings are always
1990 // null-terminated if they are longer than the buffer
1991 strncpy((char *)hdr->destination, destination->name, sizeof(hdr->destination) - 1);
1992 strncpy((char *)hdr->source, mesh->self->name, sizeof(hdr->source) - 1);
1994 memcpy(packet->data + sizeof(*hdr), data, len);
1999 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2001 assert(destination);
2005 // Prepare the packet
2006 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2010 // Send it immediately
2011 route(mesh, mesh->self, mesh->packet);
2016 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2017 // Validate arguments
2018 if(!mesh || !destination) {
2019 meshlink_errno = MESHLINK_EINVAL;
2028 meshlink_errno = MESHLINK_EINVAL;
2032 // Prepare the packet
2033 vpn_packet_t *packet = malloc(sizeof(*packet));
2036 meshlink_errno = MESHLINK_ENOMEM;
2040 if(!prepare_packet(mesh, destination, data, len, packet)) {
2046 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2048 meshlink_errno = MESHLINK_ENOMEM;
2052 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2054 // Notify event loop
2055 signal_trigger(&mesh->loop, &mesh->datafromapp);
2060 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2062 meshlink_handle_t *mesh = data;
2064 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2066 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2067 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2068 mesh->self->in_packets++;
2069 mesh->self->in_bytes += packet->len;
2070 route(mesh, mesh->self, packet);
2075 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2076 if(!mesh || !destination) {
2077 meshlink_errno = MESHLINK_EINVAL;
2081 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2083 node_t *n = (node_t *)destination;
2085 if(!n->status.reachable) {
2086 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2089 } else if(n->mtuprobes > 30 && n->minmtu) {
2090 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2093 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2098 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2099 if(!mesh || !node) {
2100 meshlink_errno = MESHLINK_EINVAL;
2104 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2106 node_t *n = (node_t *)node;
2108 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2109 meshlink_errno = MESHLINK_EINTERNAL;
2110 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2114 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2117 meshlink_errno = MESHLINK_EINTERNAL;
2120 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2124 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2126 meshlink_errno = MESHLINK_EINVAL;
2130 return (meshlink_node_t *)mesh->self;
2133 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2134 if(!mesh || !name) {
2135 meshlink_errno = MESHLINK_EINVAL;
2141 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2142 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2143 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2146 meshlink_errno = MESHLINK_ENOENT;
2149 return (meshlink_node_t *)n;
2152 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2153 if(!mesh || !name) {
2154 meshlink_errno = MESHLINK_EINVAL;
2158 meshlink_submesh_t *submesh = NULL;
2160 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2161 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2162 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2165 meshlink_errno = MESHLINK_ENOENT;
2171 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2172 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2173 meshlink_errno = MESHLINK_EINVAL;
2177 meshlink_node_t **result;
2180 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2182 *nmemb = mesh->nodes->count;
2183 result = realloc(nodes, *nmemb * sizeof(*nodes));
2186 meshlink_node_t **p = result;
2188 for splay_each(node_t, n, mesh->nodes) {
2189 *p++ = (meshlink_node_t *)n;
2194 meshlink_errno = MESHLINK_ENOMEM;
2197 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2202 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) {
2203 meshlink_node_t **result;
2205 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2209 for splay_each(node_t, n, mesh->nodes) {
2210 if(search_node(n, condition)) {
2217 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2221 result = realloc(nodes, *nmemb * sizeof(*nodes));
2224 meshlink_node_t **p = result;
2226 for splay_each(node_t, n, mesh->nodes) {
2227 if(search_node(n, condition)) {
2228 *p++ = (meshlink_node_t *)n;
2234 meshlink_errno = MESHLINK_ENOMEM;
2237 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2242 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2243 dev_class_t *devclass = (dev_class_t *)condition;
2245 if(*devclass == (dev_class_t)node->devclass) {
2252 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2253 if(condition == node->submesh) {
2265 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2266 const struct time_range *range = condition;
2267 time_t start = node->last_reachable;
2268 time_t end = node->last_unreachable;
2278 if(range->end >= range->start) {
2279 return start <= range->end && end >= range->start;
2281 return start > range->start || end < range->end;
2285 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) {
2286 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2287 meshlink_errno = MESHLINK_EINVAL;
2291 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2294 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2295 if(!mesh || !submesh || !nmemb) {
2296 meshlink_errno = MESHLINK_EINVAL;
2300 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2303 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) {
2304 if(!mesh || !nmemb) {
2305 meshlink_errno = MESHLINK_EINVAL;
2309 struct time_range range = {start, end};
2311 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2314 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2315 if(!mesh || !node) {
2316 meshlink_errno = MESHLINK_EINVAL;
2320 dev_class_t devclass;
2322 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2324 devclass = ((node_t *)node)->devclass;
2326 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2331 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2332 if(!mesh || !node) {
2333 meshlink_errno = MESHLINK_EINVAL;
2337 node_t *n = (node_t *)node;
2339 meshlink_submesh_t *s;
2341 s = (meshlink_submesh_t *)n->submesh;
2346 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2347 if(!mesh || !node) {
2348 meshlink_errno = MESHLINK_EINVAL;
2352 node_t *n = (node_t *)node;
2355 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2356 reachable = n->status.reachable && !n->status.blacklisted;
2358 if(last_reachable) {
2359 *last_reachable = n->last_reachable;
2362 if(last_unreachable) {
2363 *last_unreachable = n->last_unreachable;
2366 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2371 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2372 if(!mesh || !data || !len || !signature || !siglen) {
2373 meshlink_errno = MESHLINK_EINVAL;
2377 if(*siglen < MESHLINK_SIGLEN) {
2378 meshlink_errno = MESHLINK_EINVAL;
2382 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2384 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2385 meshlink_errno = MESHLINK_EINTERNAL;
2386 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2390 *siglen = MESHLINK_SIGLEN;
2391 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2395 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2396 if(!mesh || !source || !data || !len || !signature) {
2397 meshlink_errno = MESHLINK_EINVAL;
2401 if(siglen != MESHLINK_SIGLEN) {
2402 meshlink_errno = MESHLINK_EINVAL;
2406 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2410 struct node_t *n = (struct node_t *)source;
2412 if(!node_read_public_key(mesh, n)) {
2413 meshlink_errno = MESHLINK_EINTERNAL;
2416 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2419 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2423 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2424 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2426 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2429 // TODO: Update invitation key if necessary?
2432 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2434 return mesh->invitation_key;
2437 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2438 if(!mesh || !node || !address) {
2439 meshlink_errno = MESHLINK_EINVAL;
2443 if(!is_valid_hostname(address)) {
2444 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s", address);
2445 meshlink_errno = MESHLINK_EINVAL;
2449 if((node_t *)node != mesh->self && !port) {
2450 logger(mesh, MESHLINK_DEBUG, "Missing port number!");
2451 meshlink_errno = MESHLINK_EINVAL;
2456 if(port && !is_valid_port(port)) {
2457 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s", address);
2458 meshlink_errno = MESHLINK_EINVAL;
2462 char *canonical_address;
2465 xasprintf(&canonical_address, "%s %s", address, port);
2467 canonical_address = xstrdup(address);
2470 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2472 node_t *n = (node_t *)node;
2473 free(n->canonical_address);
2474 n->canonical_address = canonical_address;
2476 if(!node_write_config(mesh, n)) {
2477 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2481 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2483 return config_sync(mesh, "current");
2486 bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
2487 if(!mesh || !address) {
2488 meshlink_errno = MESHLINK_EINVAL;
2492 if(!is_valid_hostname(address)) {
2493 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2494 meshlink_errno = MESHLINK_EINVAL;
2498 if(port && !is_valid_port(port)) {
2499 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2500 meshlink_errno = MESHLINK_EINVAL;
2507 xasprintf(&combo, "%s/%s", address, port);
2509 combo = xstrdup(address);
2512 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2514 if(!mesh->invitation_addresses) {
2515 mesh->invitation_addresses = list_alloc((list_action_t)free);
2518 list_insert_tail(mesh->invitation_addresses, combo);
2519 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2524 void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
2526 meshlink_errno = MESHLINK_EINVAL;
2530 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2532 if(mesh->invitation_addresses) {
2533 list_delete_list(mesh->invitation_addresses);
2534 mesh->invitation_addresses = NULL;
2537 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2540 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2541 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2544 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2546 meshlink_errno = MESHLINK_EINVAL;
2550 char *address = meshlink_get_external_address(mesh);
2556 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2562 int meshlink_get_port(meshlink_handle_t *mesh) {
2564 meshlink_errno = MESHLINK_EINVAL;
2569 meshlink_errno = MESHLINK_EINTERNAL;
2575 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2576 port = atoi(mesh->myport);
2577 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2582 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2583 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2584 meshlink_errno = MESHLINK_EINVAL;
2588 if(mesh->myport && port == atoi(mesh->myport)) {
2592 if(!try_bind(mesh, port)) {
2593 meshlink_errno = MESHLINK_ENETWORK;
2597 devtool_trybind_probe();
2601 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2603 if(mesh->threadstarted) {
2604 meshlink_errno = MESHLINK_EINVAL;
2609 xasprintf(&mesh->myport, "%d", port);
2611 /* Close down the network. This also deletes mesh->self. */
2612 close_network_connections(mesh);
2614 /* Recreate mesh->self. */
2615 mesh->self = new_node();
2616 mesh->self->name = xstrdup(mesh->name);
2617 mesh->self->devclass = mesh->devclass;
2618 mesh->self->session_id = mesh->session_id;
2619 xasprintf(&mesh->myport, "%d", port);
2621 if(!node_read_public_key(mesh, mesh->self)) {
2622 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2623 meshlink_errno = MESHLINK_ESTORAGE;
2624 free_node(mesh->self);
2627 } else if(!setup_network(mesh)) {
2628 meshlink_errno = MESHLINK_ENETWORK;
2632 /* Rebuild our own list of recent addresses */
2633 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2634 add_local_addresses(mesh);
2636 /* Write meshlink.conf with the updated port number */
2637 write_main_config_files(mesh);
2639 rval = config_sync(mesh, "current");
2642 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2644 return rval && meshlink_get_port(mesh) == port;
2647 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2648 mesh->invitation_timeout = timeout;
2651 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2652 meshlink_submesh_t *s = NULL;
2655 meshlink_errno = MESHLINK_EINVAL;
2660 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2663 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2664 meshlink_errno = MESHLINK_EINVAL;
2668 s = (meshlink_submesh_t *)mesh->self->submesh;
2671 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2673 // Check validity of the new node's name
2674 if(!check_id(name)) {
2675 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2676 meshlink_errno = MESHLINK_EINVAL;
2677 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2681 // Ensure no host configuration file with that name exists
2682 if(config_exists(mesh, "current", name)) {
2683 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2684 meshlink_errno = MESHLINK_EEXIST;
2685 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2689 // Ensure no other nodes know about this name
2690 if(lookup_node(mesh, name)) {
2691 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2692 meshlink_errno = MESHLINK_EEXIST;
2693 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2697 // Get the local address
2698 char *address = get_my_hostname(mesh, flags);
2701 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2702 meshlink_errno = MESHLINK_ERESOLV;
2703 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2707 if(!refresh_invitation_key(mesh)) {
2708 meshlink_errno = MESHLINK_EINTERNAL;
2709 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2713 // If we changed our own host config file, write it out now
2714 if(mesh->self->status.dirty) {
2715 if(!node_write_config(mesh, mesh->self)) {
2716 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2717 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2724 // Create a hash of the key.
2725 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2726 sha512(fingerprint, strlen(fingerprint), hash);
2727 b64encode_urlsafe(hash, hash, 18);
2729 // Create a random cookie for this invitation.
2731 randomize(cookie, 18);
2733 // Create a filename that doesn't reveal the cookie itself
2734 char buf[18 + strlen(fingerprint)];
2735 char cookiehash[64];
2736 memcpy(buf, cookie, 18);
2737 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2738 sha512(buf, sizeof(buf), cookiehash);
2739 b64encode_urlsafe(cookiehash, cookiehash, 18);
2741 b64encode_urlsafe(cookie, cookie, 18);
2745 /* Construct the invitation file */
2746 uint8_t outbuf[4096];
2747 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2749 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2750 packmsg_add_str(&inv, name);
2751 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2752 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2754 /* TODO: Add several host config files to bootstrap connections.
2755 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2756 * and are not blacklisted.
2758 config_t configs[5];
2759 memset(configs, 0, sizeof(configs));
2762 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2766 /* Append host config files to the invitation file */
2767 packmsg_add_array(&inv, count);
2769 for(int i = 0; i < count; i++) {
2770 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2771 config_free(&configs[i]);
2774 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2776 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2777 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2778 meshlink_errno = MESHLINK_ESTORAGE;
2779 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2783 // Create an URL from the local address, key hash and cookie
2785 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2788 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
2792 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2793 return meshlink_invite_ex(mesh, submesh, name, 0);
2796 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2797 if(!mesh || !invitation) {
2798 meshlink_errno = MESHLINK_EINVAL;
2802 join_state_t state = {
2807 ecdsa_t *key = NULL;
2808 ecdsa_t *hiskey = NULL;
2810 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2811 char copy[strlen(invitation) + 1];
2813 assert(pthread_mutex_lock(&mesh->mutex) == 0);
2815 //Before doing meshlink_join make sure we are not connected to another mesh
2816 if(mesh->threadstarted) {
2817 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2818 meshlink_errno = MESHLINK_EINVAL;
2822 // 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.
2823 if(mesh->nodes->count > 1) {
2824 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2825 meshlink_errno = MESHLINK_EINVAL;
2829 strcpy(copy, invitation);
2831 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2833 char *slash = strchr(copy, '/');
2841 if(strlen(slash) != 48) {
2845 char *address = copy;
2848 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2852 if(mesh->inviter_commits_first) {
2853 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2856 // Generate a throw-away key for the invitation.
2857 key = ecdsa_generate();
2860 meshlink_errno = MESHLINK_EINTERNAL;
2864 char *b64key = ecdsa_get_base64_public_key(key);
2867 while(address && *address) {
2868 // We allow commas in the address part to support multiple addresses in one invitation URL.
2869 comma = strchr(address, ',');
2875 // Split of the port
2876 port = strrchr(address, ':');
2884 // IPv6 address are enclosed in brackets, per RFC 3986
2885 if(*address == '[') {
2887 char *bracket = strchr(address, ']');
2900 // Connect to the meshlink daemon mentioned in the URL.
2901 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), SOCK_STREAM, 5);
2904 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2905 state.sock = socket_in_netns(aip->ai_family, SOCK_STREAM, IPPROTO_TCP, mesh->netns);
2907 if(state.sock == -1) {
2908 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2909 meshlink_errno = MESHLINK_ENETWORK;
2915 setsockopt(state.sock, SOL_SOCKET, SO_NOSIGPIPE, &nosigpipe, sizeof(nosigpipe));
2918 set_timeout(state.sock, 5000);
2920 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2921 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2922 meshlink_errno = MESHLINK_ENETWORK;
2923 closesocket(state.sock);
2933 meshlink_errno = MESHLINK_ERESOLV;
2936 if(state.sock != -1 || !comma) {
2943 if(state.sock == -1) {
2947 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2949 // Tell him we have an invitation, and give him our throw-away key.
2953 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2954 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2955 meshlink_errno = MESHLINK_ENETWORK;
2961 char hisname[4096] = "";
2962 int code, hismajor, hisminor = 0;
2964 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) {
2965 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2966 meshlink_errno = MESHLINK_ENETWORK;
2970 // Check if the hash of the key he gave us matches the hash in the URL.
2971 char *fingerprint = state.line + 2;
2974 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2975 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2976 meshlink_errno = MESHLINK_EINTERNAL;
2980 if(memcmp(hishash, state.hash, 18)) {
2981 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2982 meshlink_errno = MESHLINK_EPEER;
2986 hiskey = ecdsa_set_base64_public_key(fingerprint);
2989 meshlink_errno = MESHLINK_EINTERNAL;
2993 // Start an SPTPS session
2994 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2995 meshlink_errno = MESHLINK_EINTERNAL;
2999 // Feed rest of input buffer to SPTPS
3000 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
3001 meshlink_errno = MESHLINK_EPEER;
3006 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
3008 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
3010 if(errno == EINTR) {
3014 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
3015 meshlink_errno = MESHLINK_ENETWORK;
3019 if(!sptps_receive_data(&state.sptps, state.line, len)) {
3020 meshlink_errno = MESHLINK_EPEER;
3025 if(!state.success) {
3026 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
3027 meshlink_errno = MESHLINK_EPEER;
3031 sptps_stop(&state.sptps);
3034 closesocket(state.sock);
3036 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3040 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
3041 meshlink_errno = MESHLINK_EINVAL;
3043 sptps_stop(&state.sptps);
3047 if(state.sock != -1) {
3048 closesocket(state.sock);
3051 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3055 char *meshlink_export(meshlink_handle_t *mesh) {
3057 meshlink_errno = MESHLINK_EINVAL;
3061 // Create a config file on the fly.
3064 packmsg_output_t out = {buf, sizeof(buf)};
3065 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
3066 packmsg_add_str(&out, mesh->name);
3067 packmsg_add_str(&out, CORE_MESH);
3069 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3071 packmsg_add_int32(&out, mesh->self->devclass);
3072 packmsg_add_bool(&out, mesh->self->status.blacklisted);
3073 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
3075 if(mesh->self->canonical_address && !strchr(mesh->self->canonical_address, ' ')) {
3076 char *canonical_address = NULL;
3077 xasprintf(&canonical_address, "%s %s", mesh->self->canonical_address, mesh->myport);
3078 packmsg_add_str(&out, canonical_address);
3079 free(canonical_address);
3081 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3086 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3087 if(mesh->self->recent[i].sa.sa_family) {
3094 packmsg_add_array(&out, count);
3096 for(uint32_t i = 0; i < count; i++) {
3097 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3100 packmsg_add_int64(&out, 0);
3101 packmsg_add_int64(&out, 0);
3103 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3105 if(!packmsg_output_ok(&out)) {
3106 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3107 meshlink_errno = MESHLINK_EINTERNAL;
3111 // Prepare a base64-encoded packmsg array containing our config file
3113 uint32_t len = packmsg_output_size(&out, buf);
3114 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3115 uint8_t *buf2 = xmalloc(len2);
3116 packmsg_output_t out2 = {buf2, len2};
3117 packmsg_add_array(&out2, 1);
3118 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3120 if(!packmsg_output_ok(&out2)) {
3121 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3122 meshlink_errno = MESHLINK_EINTERNAL;
3127 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3129 return (char *)buf2;
3132 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3133 if(!mesh || !data) {
3134 meshlink_errno = MESHLINK_EINVAL;
3138 size_t datalen = strlen(data);
3139 uint8_t *buf = xmalloc(datalen);
3140 int buflen = b64decode(data, buf, datalen);
3143 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3144 meshlink_errno = MESHLINK_EPEER;
3148 packmsg_input_t in = {buf, buflen};
3149 uint32_t count = packmsg_get_array(&in);
3152 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3153 meshlink_errno = MESHLINK_EPEER;
3157 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3161 uint32_t len2 = packmsg_get_bin_raw(&in, &data2);
3167 packmsg_input_t in2 = {data2, len2};
3168 uint32_t version = packmsg_get_uint32(&in2);
3169 char *name = packmsg_get_str_dup(&in2);
3171 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3173 packmsg_input_invalidate(&in);
3177 if(!check_id(name)) {
3182 node_t *n = lookup_node(mesh, name);
3185 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3193 config_t config = {data2, len2};
3195 if(!node_read_from_config(mesh, n, &config)) {
3197 packmsg_input_invalidate(&in);
3201 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3202 n->last_reachable = 0;
3203 n->last_unreachable = 0;
3205 if(!node_write_config(mesh, n)) {
3213 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3217 if(!packmsg_done(&in)) {
3218 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3219 meshlink_errno = MESHLINK_EPEER;
3223 if(!config_sync(mesh, "current")) {
3230 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3231 if(n == mesh->self) {
3232 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3233 meshlink_errno = MESHLINK_EINVAL;
3237 if(n->status.blacklisted) {
3238 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3242 n->status.blacklisted = true;
3244 /* Immediately shut down any connections we have with the blacklisted node.
3245 * We can't call terminate_connection(), because we might be called from a callback function.
3247 for list_each(connection_t, c, mesh->connections) {
3249 shutdown(c->socket, SHUT_RDWR);
3253 utcp_abort_all_connections(n->utcp);
3259 n->status.udp_confirmed = false;
3261 if(n->status.reachable) {
3262 n->last_unreachable = time(NULL);
3265 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3266 * manually call the status callback if necessary.
3268 if(n->status.reachable && mesh->node_status_cb) {
3269 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3272 return node_write_config(mesh, n) && config_sync(mesh, "current");
3275 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3276 if(!mesh || !node) {
3277 meshlink_errno = MESHLINK_EINVAL;
3281 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3283 if(!blacklist(mesh, (node_t *)node)) {
3284 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3288 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3290 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3294 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3295 if(!mesh || !name) {
3296 meshlink_errno = MESHLINK_EINVAL;
3300 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3302 node_t *n = lookup_node(mesh, (char *)name);
3306 n->name = xstrdup(name);
3310 if(!blacklist(mesh, (node_t *)n)) {
3311 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3315 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3317 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3321 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3322 if(n == mesh->self) {
3323 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3324 meshlink_errno = MESHLINK_EINVAL;
3328 if(!n->status.blacklisted) {
3329 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3333 n->status.blacklisted = false;
3335 if(n->status.reachable) {
3336 n->last_reachable = time(NULL);
3337 update_node_status(mesh, n);
3340 return node_write_config(mesh, n) && config_sync(mesh, "current");
3343 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3344 if(!mesh || !node) {
3345 meshlink_errno = MESHLINK_EINVAL;
3349 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3351 if(!whitelist(mesh, (node_t *)node)) {
3352 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3356 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3358 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3362 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3363 if(!mesh || !name) {
3364 meshlink_errno = MESHLINK_EINVAL;
3368 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3370 node_t *n = lookup_node(mesh, (char *)name);
3374 n->name = xstrdup(name);
3378 if(!whitelist(mesh, (node_t *)n)) {
3379 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3383 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3385 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3389 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3390 mesh->default_blacklist = blacklist;
3393 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3394 if(!mesh || !node) {
3395 meshlink_errno = MESHLINK_EINVAL;
3399 node_t *n = (node_t *)node;
3401 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3403 /* Check that the node is not reachable */
3404 if(n->status.reachable || n->connection) {
3405 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3406 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3410 /* Check that we don't have any active UTCP connections */
3411 if(n->utcp && utcp_is_active(n->utcp)) {
3412 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3413 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3417 /* Check that we have no active connections to this node */
3418 for list_each(connection_t, c, mesh->connections) {
3420 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3421 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3426 /* Remove any pending outgoings to this node */
3427 if(mesh->outgoings) {
3428 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3429 if(outgoing->node == n) {
3430 list_delete_node(mesh->outgoings, list_node);
3435 /* Delete the config file for this node */
3436 if(!config_delete(mesh, "current", n->name)) {
3437 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3441 /* Delete the node struct and any remaining edges referencing this node */
3444 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3446 return config_sync(mesh, "current");
3449 /* Hint that a hostname may be found at an address
3450 * See header file for detailed comment.
3452 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3453 if(!mesh || !node || !addr) {
3454 meshlink_errno = EINVAL;
3458 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3460 node_t *n = (node_t *)node;
3462 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3463 if(!node_write_config(mesh, n)) {
3464 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3468 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3469 // @TODO do we want to fire off a connection attempt right away?
3472 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3474 node_t *n = utcp->priv;
3475 meshlink_handle_t *mesh = n->mesh;
3476 return mesh->channel_accept_cb;
3479 /* Finish one AIO buffer, return true if the channel is still open. */
3480 static bool aio_finish_one(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3481 meshlink_aio_buffer_t *aio = *head;
3485 channel->in_callback = true;
3488 if(aio->cb.buffer) {
3489 aio->cb.buffer(mesh, channel, aio->data, aio->done, aio->priv);
3493 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3497 channel->in_callback = false;
3510 /* Finish all AIO buffers, return true if the channel is still open. */
3511 static bool aio_abort(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t **head) {
3513 if(!aio_finish_one(mesh, channel, head)) {
3521 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3522 meshlink_channel_t *channel = connection->priv;
3528 node_t *n = channel->node;
3529 meshlink_handle_t *mesh = n->mesh;
3531 if(n->status.destroyed) {
3532 meshlink_channel_close(mesh, channel);
3536 const char *p = data;
3539 while(channel->aio_receive) {
3541 /* This receive callback signalled an error, abort all outstanding AIO buffers. */
3542 if(!aio_abort(mesh, channel, &channel->aio_receive)) {
3549 meshlink_aio_buffer_t *aio = channel->aio_receive;
3550 size_t todo = aio->len - aio->done;
3557 memcpy((char *)aio->data + aio->done, p, todo);
3559 ssize_t result = write(aio->fd, p, todo);
3562 if(result < 0 && errno == EINTR) {
3566 /* Writing to fd failed, cancel just this AIO buffer. */
3567 logger(mesh, MESHLINK_ERROR, "Writing to AIO fd %d failed: %s", aio->fd, strerror(errno));
3569 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3583 if(aio->done == aio->len) {
3584 if(!aio_finish_one(mesh, channel, &channel->aio_receive)) {
3594 if(channel->receive_cb) {
3595 channel->receive_cb(mesh, channel, p, left);
3601 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3602 node_t *n = utcp_connection->utcp->priv;
3608 meshlink_handle_t *mesh = n->mesh;
3610 if(!mesh->channel_accept_cb) {
3614 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3616 channel->c = utcp_connection;
3618 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3619 utcp_accept(utcp_connection, channel_recv, channel);
3625 static void channel_retransmit(struct utcp_connection *utcp_connection) {
3626 node_t *n = utcp_connection->utcp->priv;
3627 meshlink_handle_t *mesh = n->mesh;
3629 if(n->mtuprobes == 31) {
3630 timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
3636 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3637 node_t *n = utcp->priv;
3639 if(n->status.destroyed) {
3643 meshlink_handle_t *mesh = n->mesh;
3644 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3647 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3648 if(!mesh || !channel) {
3649 meshlink_errno = MESHLINK_EINVAL;
3653 channel->receive_cb = cb;
3656 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3658 node_t *n = (node_t *)source;
3664 utcp_recv(n->utcp, data, len);
3667 static void channel_poll(struct utcp_connection *connection, size_t len) {
3668 meshlink_channel_t *channel = connection->priv;
3674 node_t *n = channel->node;
3675 meshlink_handle_t *mesh = n->mesh;
3677 while(channel->aio_send) {
3679 /* This poll callback signalled an error, abort all outstanding AIO buffers. */
3680 if(!aio_abort(mesh, channel, &channel->aio_send)) {
3687 /* We have at least one AIO buffer. Send as much as possible from the buffers. */
3688 meshlink_aio_buffer_t *aio = channel->aio_send;
3689 size_t todo = aio->len - aio->done;
3697 sent = utcp_send(connection, (char *)aio->data + aio->done, todo);
3699 /* Limit the amount we read at once to avoid stack overflows */
3705 ssize_t result = read(aio->fd, buf, todo);
3709 sent = utcp_send(connection, buf, todo);
3711 if(result < 0 && errno == EINTR) {
3715 /* Reading from fd failed, cancel just this AIO buffer. */
3717 logger(mesh, MESHLINK_ERROR, "Reading from AIO fd %d failed: %s", aio->fd, strerror(errno));
3720 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
3728 if(sent != (ssize_t)todo) {
3729 /* We should never get a partial send at this point */
3732 /* Sending failed, abort all outstanding AIO buffers and send a poll callback. */
3733 if(!aio_abort(mesh, channel, &channel->aio_send)) {
3744 /* If we didn't finish this buffer, exit early. */
3745 if(aio->done < aio->len) {
3749 /* Signal completion of this buffer, and go to the next one. */
3750 if(!aio_finish_one(mesh, channel, &channel->aio_send)) {
3759 if(channel->poll_cb) {
3760 channel->poll_cb(mesh, channel, len);
3762 utcp_set_poll_cb(connection, NULL);
3766 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3767 if(!mesh || !channel) {
3768 meshlink_errno = MESHLINK_EINVAL;
3772 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3773 channel->poll_cb = cb;
3774 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3775 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3778 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3780 meshlink_errno = MESHLINK_EINVAL;
3784 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3785 mesh->channel_accept_cb = cb;
3786 mesh->receive_cb = channel_receive;
3788 for splay_each(node_t, n, mesh->nodes) {
3789 if(!n->utcp && n != mesh->self) {
3790 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3791 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3792 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3796 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3799 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3803 meshlink_errno = MESHLINK_EINVAL;
3807 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3808 utcp_set_sndbuf(channel->c, size);
3809 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3812 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3816 meshlink_errno = MESHLINK_EINVAL;
3820 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3821 utcp_set_rcvbuf(channel->c, size);
3822 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3825 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) {
3827 abort(); // TODO: handle non-NULL data
3830 if(!mesh || !node) {
3831 meshlink_errno = MESHLINK_EINVAL;
3835 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3837 node_t *n = (node_t *)node;
3840 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3841 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3842 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
3843 mesh->receive_cb = channel_receive;
3846 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3847 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3852 if(n->status.blacklisted) {
3853 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3854 meshlink_errno = MESHLINK_EBLACKLISTED;
3855 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3859 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3861 channel->receive_cb = cb;
3864 channel->priv = (void *)data;
3867 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3869 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3872 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3880 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) {
3881 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3884 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3885 if(!mesh || !channel) {
3886 meshlink_errno = MESHLINK_EINVAL;
3890 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3891 utcp_shutdown(channel->c, direction);
3892 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3895 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3896 if(!mesh || !channel) {
3897 meshlink_errno = MESHLINK_EINVAL;
3901 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3904 utcp_close(channel->c);
3907 /* Clean up any outstanding AIO buffers. */
3908 aio_abort(mesh, channel, &channel->aio_send);
3909 aio_abort(mesh, channel, &channel->aio_receive);
3912 if(!channel->in_callback) {
3916 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3919 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3920 if(!mesh || !channel) {
3921 meshlink_errno = MESHLINK_EINVAL;
3930 meshlink_errno = MESHLINK_EINVAL;
3934 // TODO: more finegrained locking.
3935 // Ideally we want to put the data into the UTCP connection's send buffer.
3936 // Then, preferably only if there is room in the receiver window,
3937 // kick the meshlink thread to go send packets.
3941 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3943 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3944 if(channel->aio_send) {
3947 retval = utcp_send(channel->c, data, len);
3950 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
3953 meshlink_errno = MESHLINK_ENETWORK;
3959 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) {
3960 if(!mesh || !channel) {
3961 meshlink_errno = MESHLINK_EINVAL;
3966 meshlink_errno = MESHLINK_EINVAL;
3970 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3973 aio->cb.buffer = cb;
3976 assert(pthread_mutex_lock(&mesh->mutex) == 0);
3978 /* Append the AIO buffer descriptor to the end of the chain */
3979 meshlink_aio_buffer_t **p = &channel->aio_send;
3987 /* Ensure the poll callback is set, and call it right now to push data if possible */
3988 utcp_set_poll_cb(channel->c, channel_poll);
3989 size_t todo = MIN(len, utcp_get_rcvbuf_free(channel->c));
3992 channel_poll(channel->c, todo);
3995 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4000 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) {
4001 if(!mesh || !channel) {
4002 meshlink_errno = MESHLINK_EINVAL;
4006 if(!len || fd == -1) {
4007 meshlink_errno = MESHLINK_EINVAL;
4011 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4017 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4019 /* Append the AIO buffer descriptor to the end of the chain */
4020 meshlink_aio_buffer_t **p = &channel->aio_send;
4028 /* Ensure the poll callback is set, and call it right now to push data if possible */
4029 utcp_set_poll_cb(channel->c, channel_poll);
4030 size_t left = utcp_get_rcvbuf_free(channel->c);
4033 channel_poll(channel->c, left);
4036 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4041 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) {
4042 if(!mesh || !channel) {
4043 meshlink_errno = MESHLINK_EINVAL;
4048 meshlink_errno = MESHLINK_EINVAL;
4052 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4055 aio->cb.buffer = cb;
4058 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4060 /* Append the AIO buffer descriptor to the end of the chain */
4061 meshlink_aio_buffer_t **p = &channel->aio_receive;
4069 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4074 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) {
4075 if(!mesh || !channel) {
4076 meshlink_errno = MESHLINK_EINVAL;
4080 if(!len || fd == -1) {
4081 meshlink_errno = MESHLINK_EINVAL;
4085 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
4091 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4093 /* Append the AIO buffer descriptor to the end of the chain */
4094 meshlink_aio_buffer_t **p = &channel->aio_receive;
4102 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4107 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4108 if(!mesh || !channel) {
4109 meshlink_errno = MESHLINK_EINVAL;
4113 return channel->c->flags;
4116 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4117 if(!mesh || !channel) {
4118 meshlink_errno = MESHLINK_EINVAL;
4122 return utcp_get_sendq(channel->c);
4125 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4126 if(!mesh || !channel) {
4127 meshlink_errno = MESHLINK_EINVAL;
4131 return utcp_get_recvq(channel->c);
4134 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4135 if(!mesh || !channel) {
4136 meshlink_errno = MESHLINK_EINVAL;
4140 return utcp_get_mss(channel->node->utcp);
4143 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
4144 if(!mesh || !node) {
4145 meshlink_errno = MESHLINK_EINVAL;
4149 node_t *n = (node_t *)node;
4151 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4154 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4155 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4156 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4159 utcp_set_user_timeout(n->utcp, timeout);
4161 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4164 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4165 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4166 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4167 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4168 utcp_set_retransmit_cb(n->utcp, channel_retransmit);
4171 if(mesh->node_status_cb) {
4172 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4175 if(mesh->node_pmtu_cb) {
4176 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4180 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4181 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4183 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4184 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4188 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4189 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4193 n->status.duplicate = true;
4194 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4197 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4201 meshlink_errno = MESHLINK_EINVAL;
4205 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4207 if(mesh->discovery == enable) {
4211 if(mesh->threadstarted) {
4213 discovery_start(mesh);
4215 discovery_stop(mesh);
4219 mesh->discovery = enable;
4222 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4226 meshlink_errno = MESHLINK_ENOTSUP;
4230 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4231 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4232 meshlink_errno = EINVAL;
4236 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4237 meshlink_errno = EINVAL;
4241 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4242 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4243 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4244 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4247 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4248 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4249 meshlink_errno = EINVAL;
4253 if(fast_retry_period < 0) {
4254 meshlink_errno = EINVAL;
4258 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4259 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4260 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4263 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4265 meshlink_errno = EINVAL;
4269 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4270 mesh->inviter_commits_first = inviter_commits_first;
4271 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4274 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4276 meshlink_errno = EINVAL;
4280 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4281 meshlink_errno = EINVAL;
4285 assert(pthread_mutex_lock(&mesh->mutex) == 0);
4286 free(mesh->external_address_url);
4287 mesh->external_address_url = url ? xstrdup(url) : NULL;
4288 assert(pthread_mutex_unlock(&mesh->mutex) == 0);
4291 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4292 if(!mesh || granularity < 0) {
4293 meshlink_errno = EINVAL;
4297 utcp_set_clock_granularity(granularity);
4300 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4303 if(!mesh->connections || !mesh->loop.running) {
4308 signal_trigger(&mesh->loop, &mesh->datafromapp);
4311 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t cb_errno) {
4312 // We should only call the callback function if we are in the background thread.
4313 if(!mesh->error_cb) {
4317 if(!mesh->threadstarted) {
4321 if(mesh->thread == pthread_self()) {
4322 mesh->error_cb(mesh, cb_errno);
4326 static void __attribute__((constructor)) meshlink_init(void) {
4328 utcp_set_clock_granularity(10000);
4331 static void __attribute__((destructor)) meshlink_exit(void) {