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 pthread_join(thr, NULL);
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(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(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"), 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);
272 set_timeout(s, 5000);
274 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
281 send(s, "GET ", 4, 0);
282 send(s, url, strlen(url), 0);
283 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
284 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
289 if(line[len - 1] == '\n') {
293 char *p = strrchr(line, '\n');
296 hostname = xstrdup(p + 1);
312 // Check that the hostname is reasonable
313 if(hostname && !is_valid_hostname(hostname)) {
319 meshlink_errno = MESHLINK_ERESOLV;
325 static bool is_localaddr(sockaddr_t *sa) {
326 switch(sa->sa.sa_family) {
328 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
331 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
332 return first == 0 || (first & 0xffc0) == 0xfe80;
340 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
343 // Determine address of the local interface used for outgoing connections.
344 char localaddr[NI_MAXHOST];
345 bool success = false;
347 if(family == AF_INET) {
348 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
349 } else if(family == AF_INET6) {
350 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
353 #ifdef HAVE_GETIFADDRS
356 struct ifaddrs *ifa = NULL;
359 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
360 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
362 if(sa->sa.sa_family != family) {
366 if(is_localaddr(sa)) {
370 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
382 meshlink_errno = MESHLINK_ENETWORK;
386 return xstrdup(localaddr);
389 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
390 for(int i = 0; i < n; i++) {
395 // Ignore duplicate hostnames
398 for(int j = 0; j < i; j++) {
403 if(strcmp(host[i], host[j])) {
407 if(strcmp(port[i], port[j])) {
415 if(found || !is_valid_hostname(host[i])) {
425 // This gets the hostname part for use in invitation URLs
426 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
427 int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
429 char *hostname[count];
431 char *hostport = NULL;
433 memset(hostname, 0, sizeof(hostname));
434 memset(port, 0, sizeof(port));
436 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
437 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
440 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
441 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
444 // Add all explicitly set invitation addresses
445 if(mesh->invitation_addresses) {
446 for list_each(char, combo, mesh->invitation_addresses) {
447 hostname[n] = xstrdup(combo);
448 char *slash = strrchr(hostname[n], '/');
452 port[n] = xstrdup(slash + 1);
459 // Add local addresses if requested
460 if(flags & MESHLINK_INVITE_LOCAL) {
461 if(flags & MESHLINK_INVITE_IPV4) {
462 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
465 if(flags & MESHLINK_INVITE_IPV6) {
466 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
470 // Add public/canonical addresses if requested
471 if(flags & MESHLINK_INVITE_PUBLIC) {
472 // Try the CanonicalAddress first
473 get_canonical_address(mesh->self, &hostname[n], &port[n]);
475 if(!hostname[n] && count == 4) {
476 if(flags & MESHLINK_INVITE_IPV4) {
477 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
480 if(flags & MESHLINK_INVITE_IPV6) {
481 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
488 for(int i = 0; i < n; i++) {
489 // Ensure we always have a port number
490 if(hostname[i] && !port[i]) {
491 port[i] = xstrdup(mesh->myport);
495 remove_duplicate_hostnames(hostname, port, n);
497 // Resolve the hostnames
498 for(int i = 0; i < n; i++) {
503 // Convert what we have to a sockaddr
504 struct addrinfo *ai_in = adns_blocking_request(mesh, xstrdup(hostname[i]), xstrdup(port[i]), 5);
510 // Remember the address(es)
511 for(struct addrinfo *aip = ai_in; aip; aip = aip->ai_next) {
512 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)aip->ai_addr);
519 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
520 remove_duplicate_hostnames(hostname, port, n);
522 // Concatenate all unique address to the hostport string
523 for(int i = 0; i < n; i++) {
528 // Append the address to the hostport string
530 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
532 hostport = newhostport;
541 static bool try_bind(meshlink_handle_t *mesh, int port) {
542 struct addrinfo *ai = NULL;
543 struct addrinfo hint = {
544 .ai_flags = AI_PASSIVE,
545 .ai_family = AF_UNSPEC,
546 .ai_socktype = SOCK_STREAM,
547 .ai_protocol = IPPROTO_TCP,
551 snprintf(portstr, sizeof(portstr), "%d", port);
553 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
557 bool success = false;
559 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
560 /* Try to bind to TCP. */
562 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
565 if(errno == EADDRINUSE) {
566 /* If this port is in use for any address family, avoid it. */
574 /* If TCP worked, then we require that UDP works as well. */
576 int udp_fd = setup_udp_listen_socket(mesh, aip);
593 int check_port(meshlink_handle_t *mesh) {
594 for(int i = 0; i < 1000; i++) {
595 int port = 0x1000 + prng(mesh, 0x8000);
597 if(try_bind(mesh, port)) {
599 xasprintf(&mesh->myport, "%d", port);
604 meshlink_errno = MESHLINK_ENETWORK;
605 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
609 static bool write_main_config_files(meshlink_handle_t *mesh) {
610 if(!mesh->confbase) {
616 /* Write the main config file */
617 packmsg_output_t out = {buf, sizeof buf};
619 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
620 packmsg_add_str(&out, mesh->name);
621 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
622 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
623 packmsg_add_uint16(&out, atoi(mesh->myport));
625 if(!packmsg_output_ok(&out)) {
629 config_t config = {buf, packmsg_output_size(&out, buf)};
631 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
635 /* Write our own host config file */
636 if(!node_write_config(mesh, mesh->self)) {
644 meshlink_handle_t *mesh;
646 char cookie[18 + 32];
657 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
658 meshlink_handle_t *mesh = state->mesh;
659 packmsg_input_t in = {buf, len};
660 uint32_t version = packmsg_get_uint32(&in);
662 if(version != MESHLINK_INVITATION_VERSION) {
663 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
667 char *name = packmsg_get_str_dup(&in);
668 packmsg_skip_element(&in); /* submesh */
669 dev_class_t devclass = packmsg_get_int32(&in);
670 uint32_t count = packmsg_get_array(&in);
673 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
677 if(!check_id(name)) {
678 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
684 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
690 free(mesh->self->name);
692 mesh->self->name = xstrdup(name);
693 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
695 // Initialize configuration directory
696 if(!config_init(mesh, "current")) {
700 if(!write_main_config_files(mesh)) {
704 // Write host config files
705 for(uint32_t i = 0; i < count; i++) {
707 uint32_t len = packmsg_get_bin_raw(&in, &data);
710 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
714 packmsg_input_t in2 = {data, len};
715 uint32_t version = packmsg_get_uint32(&in2);
716 char *name = packmsg_get_str_dup(&in2);
718 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
720 packmsg_input_invalidate(&in);
724 if(!check_id(name)) {
729 if(!strcmp(name, mesh->name)) {
730 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
732 meshlink_errno = MESHLINK_EPEER;
736 node_t *n = new_node();
739 config_t config = {data, len};
741 if(!node_read_from_config(mesh, n, &config)) {
743 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
744 meshlink_errno = MESHLINK_EPEER;
749 /* The first host config file is of the inviter itself;
750 * remember the address we are currently using for the invitation connection.
753 socklen_t salen = sizeof(sa);
755 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
756 node_add_recent_address(mesh, n, &sa);
760 /* Clear the reachability times, since we ourself have never seen these nodes yet */
761 n->last_reachable = 0;
762 n->last_unreachable = 0;
764 if(!node_write_config(mesh, n)) {
772 /* Ensure the configuration directory metadata is on disk */
773 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
777 if(!mesh->inviter_commits_first) {
778 devtool_set_inviter_commits_first(false);
781 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
783 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
788 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
790 join_state_t *state = handle;
791 const char *ptr = data;
794 int result = send(state->sock, ptr, len, 0);
796 if(result == -1 && errno == EINTR) {
798 } else if(result <= 0) {
809 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
810 join_state_t *state = handle;
811 meshlink_handle_t *mesh = state->mesh;
813 if(mesh->inviter_commits_first) {
815 case SPTPS_HANDSHAKE:
816 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
822 if(!finalize_join(state, msg, len)) {
826 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
827 shutdown(state->sock, SHUT_RDWR);
828 state->success = true;
836 case SPTPS_HANDSHAKE:
837 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
840 return finalize_join(state, msg, len);
843 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
844 shutdown(state->sock, SHUT_RDWR);
845 state->success = true;
856 static bool recvline(join_state_t *state) {
857 char *newline = NULL;
859 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
860 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
862 if(result == -1 && errno == EINTR) {
864 } else if(result <= 0) {
868 state->blen += result;
871 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
875 size_t len = newline - state->buffer;
877 memcpy(state->line, state->buffer, len);
878 state->line[len] = 0;
879 memmove(state->buffer, newline + 1, state->blen - len - 1);
880 state->blen -= len + 1;
885 static bool sendline(int fd, char *format, ...) {
891 va_start(ap, format);
892 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
895 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
903 int result = send(fd, p, blen, MSG_NOSIGNAL);
905 if(result == -1 && errno == EINTR) {
907 } else if(result <= 0) {
918 static const char *errstr[] = {
919 [MESHLINK_OK] = "No error",
920 [MESHLINK_EINVAL] = "Invalid argument",
921 [MESHLINK_ENOMEM] = "Out of memory",
922 [MESHLINK_ENOENT] = "No such node",
923 [MESHLINK_EEXIST] = "Node already exists",
924 [MESHLINK_EINTERNAL] = "Internal error",
925 [MESHLINK_ERESOLV] = "Could not resolve hostname",
926 [MESHLINK_ESTORAGE] = "Storage error",
927 [MESHLINK_ENETWORK] = "Network error",
928 [MESHLINK_EPEER] = "Error communicating with peer",
929 [MESHLINK_ENOTSUP] = "Operation not supported",
930 [MESHLINK_EBUSY] = "MeshLink instance already in use",
931 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
934 const char *meshlink_strerror(meshlink_errno_t err) {
935 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
936 return "Invalid error code";
942 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
943 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
945 mesh->private_key = ecdsa_generate();
946 mesh->invitation_key = ecdsa_generate();
948 if(!mesh->private_key || !mesh->invitation_key) {
949 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
950 meshlink_errno = MESHLINK_EINTERNAL;
954 logger(mesh, MESHLINK_DEBUG, "Done.\n");
959 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
960 if(a->tv_sec == b->tv_sec) {
961 return a->tv_nsec < b->tv_nsec;
963 return a->tv_sec < b->tv_sec;
967 static struct timespec idle(event_loop_t *loop, void *data) {
969 meshlink_handle_t *mesh = data;
970 struct timespec t, tmin = {3600, 0};
972 for splay_each(node_t, n, mesh->nodes) {
977 t = utcp_timeout(n->utcp);
979 if(timespec_lt(&t, &tmin)) {
987 // Get our local address(es) by simulating connecting to an Internet host.
988 static void add_local_addresses(meshlink_handle_t *mesh) {
990 sa.storage.ss_family = AF_UNKNOWN;
991 socklen_t salen = sizeof(sa);
995 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
996 sa.in.sin_port = ntohs(atoi(mesh->myport));
997 node_add_recent_address(mesh, mesh->self, &sa);
1004 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
1005 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
1006 node_add_recent_address(mesh, mesh->self, &sa);
1010 static bool meshlink_setup(meshlink_handle_t *mesh) {
1011 if(!config_destroy(mesh->confbase, "new")) {
1012 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1013 meshlink_errno = MESHLINK_ESTORAGE;
1017 if(!config_destroy(mesh->confbase, "old")) {
1018 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1019 meshlink_errno = MESHLINK_ESTORAGE;
1023 if(!config_init(mesh, "current")) {
1024 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1025 meshlink_errno = MESHLINK_ESTORAGE;
1029 if(!ecdsa_keygen(mesh)) {
1030 meshlink_errno = MESHLINK_EINTERNAL;
1034 if(check_port(mesh) == 0) {
1035 meshlink_errno = MESHLINK_ENETWORK;
1039 /* Create a node for ourself */
1041 mesh->self = new_node();
1042 mesh->self->name = xstrdup(mesh->name);
1043 mesh->self->devclass = mesh->devclass;
1044 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1045 mesh->self->session_id = mesh->session_id;
1047 if(!write_main_config_files(mesh)) {
1048 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1049 meshlink_errno = MESHLINK_ESTORAGE;
1053 /* Ensure the configuration directory metadata is on disk */
1054 if(!config_sync(mesh, "current")) {
1061 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1064 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1065 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1069 packmsg_input_t in = {config.buf, config.len};
1070 const void *private_key;
1071 const void *invitation_key;
1073 uint32_t version = packmsg_get_uint32(&in);
1074 char *name = packmsg_get_str_dup(&in);
1075 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1076 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1077 uint16_t myport = packmsg_get_uint16(&in);
1079 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1080 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1082 config_free(&config);
1088 // TODO: check this?
1089 if(mesh->name && strcmp(mesh->name, name)) {
1090 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1091 meshlink_errno = MESHLINK_ESTORAGE;
1093 config_free(&config);
1101 xasprintf(&mesh->myport, "%u", myport);
1102 mesh->private_key = ecdsa_set_private_key(private_key);
1103 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1104 config_free(&config);
1106 /* Create a node for ourself and read our host configuration file */
1108 mesh->self = new_node();
1109 mesh->self->name = xstrdup(name);
1110 mesh->self->devclass = mesh->devclass;
1111 mesh->self->session_id = mesh->session_id;
1113 if(!node_read_public_key(mesh, mesh->self)) {
1114 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1115 meshlink_errno = MESHLINK_ESTORAGE;
1116 free_node(mesh->self);
1125 static void *setup_network_in_netns_thread(void *arg) {
1126 meshlink_handle_t *mesh = arg;
1128 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1132 bool success = setup_network(mesh);
1133 return success ? arg : NULL;
1135 #endif // HAVE_SETNS
1137 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1138 if(!confbase || !*confbase) {
1139 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1140 meshlink_errno = MESHLINK_EINVAL;
1144 if(!appname || !*appname) {
1145 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1146 meshlink_errno = MESHLINK_EINVAL;
1150 if(strchr(appname, ' ')) {
1151 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1152 meshlink_errno = MESHLINK_EINVAL;
1156 if(!name || !*name) {
1157 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1158 meshlink_errno = MESHLINK_EINVAL;
1162 if(!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 = xstrdup(name);
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 pthread_mutex_lock(&mesh->mutex);
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 pthread_mutex_unlock(&mesh->mutex);
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 pthread_mutex_unlock(&mesh->mutex);
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 pthread_mutex_unlock(&mesh->mutex);
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 pthread_mutex_unlock(&mesh->mutex);
1265 devtool_keyrotate_probe(3);
1267 // Cleanup the "old" confbase sub-directory
1269 if(!config_destroy(mesh->confbase, "old")) {
1270 pthread_mutex_unlock(&mesh->mutex);
1274 // Change the mesh handle key with new key
1276 free(mesh->config_key);
1277 mesh->config_key = new_config_key;
1279 pthread_mutex_unlock(&mesh->mutex);
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) {
1350 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1351 meshlink_open_params_t params;
1352 memset(¶ms, 0, sizeof(params));
1354 params.name = (char *)name;
1355 params.appname = (char *)appname;
1356 params.devclass = devclass;
1359 return meshlink_open_ex(¶ms);
1362 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1363 // Validate arguments provided by the application
1364 bool usingname = false;
1366 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1368 if(!params->appname || !*params->appname) {
1369 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1370 meshlink_errno = MESHLINK_EINVAL;
1374 if(strchr(params->appname, ' ')) {
1375 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1376 meshlink_errno = MESHLINK_EINVAL;
1380 if(!params->name || !*params->name) {
1381 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1383 } else { //check name only if there is a name != NULL
1385 if(!check_id(params->name)) {
1386 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1387 meshlink_errno = MESHLINK_EINVAL;
1394 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1395 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1396 meshlink_errno = MESHLINK_EINVAL;
1400 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1401 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1402 meshlink_errno = MESHLINK_EINVAL;
1406 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1408 if(params->confbase) {
1409 mesh->confbase = xstrdup(params->confbase);
1412 mesh->appname = xstrdup(params->appname);
1413 mesh->devclass = params->devclass;
1414 mesh->discovery = true;
1415 mesh->invitation_timeout = 604800; // 1 week
1416 mesh->netns = params->netns;
1417 mesh->submeshes = NULL;
1418 mesh->log_cb = global_log_cb;
1419 mesh->log_level = global_log_level;
1420 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1422 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1425 randomize(&mesh->session_id, sizeof(mesh->session_id));
1426 } while(mesh->session_id == 0);
1428 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1431 mesh->name = xstrdup(params->name);
1436 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1438 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1439 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1440 meshlink_close(mesh);
1441 meshlink_errno = MESHLINK_EINTERNAL;
1447 pthread_mutexattr_t attr;
1448 pthread_mutexattr_init(&attr);
1449 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1450 pthread_mutex_init(&mesh->mutex, &attr);
1452 mesh->threadstarted = false;
1453 event_loop_init(&mesh->loop);
1454 mesh->loop.data = mesh;
1456 meshlink_queue_init(&mesh->outpacketqueue);
1458 // Atomically lock the configuration directory.
1459 if(!main_config_lock(mesh)) {
1460 meshlink_close(mesh);
1464 // If no configuration exists yet, create it.
1466 if(!meshlink_confbase_exists(mesh)) {
1467 if(!meshlink_setup(mesh)) {
1468 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1469 meshlink_close(mesh);
1473 if(!meshlink_read_config(mesh)) {
1474 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1475 meshlink_close(mesh);
1481 struct WSAData wsa_state;
1482 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1485 // Setup up everything
1486 // TODO: we should not open listening sockets yet
1488 bool success = false;
1490 if(mesh->netns != -1) {
1494 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1495 void *retval = NULL;
1496 success = pthread_join(thr, &retval) == 0 && retval;
1500 meshlink_errno = MESHLINK_EINTERNAL;
1503 #endif // HAVE_SETNS
1505 success = setup_network(mesh);
1509 meshlink_close(mesh);
1510 meshlink_errno = MESHLINK_ENETWORK;
1514 add_local_addresses(mesh);
1516 if(!node_write_config(mesh, mesh->self)) {
1517 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1521 idle_set(&mesh->loop, idle, mesh);
1523 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1527 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1528 meshlink_submesh_t *s = NULL;
1531 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1532 meshlink_errno = MESHLINK_EINVAL;
1536 if(!submesh || !*submesh) {
1537 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1538 meshlink_errno = MESHLINK_EINVAL;
1543 pthread_mutex_lock(&mesh->mutex);
1545 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1547 pthread_mutex_unlock(&mesh->mutex);
1552 static void *meshlink_main_loop(void *arg) {
1553 meshlink_handle_t *mesh = arg;
1555 if(mesh->netns != -1) {
1558 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1559 pthread_cond_signal(&mesh->cond);
1564 pthread_cond_signal(&mesh->cond);
1566 #endif // HAVE_SETNS
1571 if(mesh->discovery) {
1572 discovery_start(mesh);
1577 pthread_mutex_lock(&mesh->mutex);
1579 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1580 pthread_cond_broadcast(&mesh->cond);
1582 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1584 pthread_mutex_unlock(&mesh->mutex);
1589 if(mesh->discovery) {
1590 discovery_stop(mesh);
1598 bool meshlink_start(meshlink_handle_t *mesh) {
1600 meshlink_errno = MESHLINK_EINVAL;
1604 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1606 pthread_mutex_lock(&mesh->mutex);
1609 assert(mesh->private_key);
1610 assert(mesh->self->ecdsa);
1611 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1613 if(mesh->threadstarted) {
1614 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1615 pthread_mutex_unlock(&mesh->mutex);
1619 if(mesh->listen_socket[0].tcp.fd < 0) {
1620 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1621 meshlink_errno = MESHLINK_ENETWORK;
1625 // TODO: open listening sockets first
1627 //Check that a valid name is set
1629 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1630 meshlink_errno = MESHLINK_EINVAL;
1631 pthread_mutex_unlock(&mesh->mutex);
1635 init_outgoings(mesh);
1638 // Start the main thread
1640 event_loop_start(&mesh->loop);
1642 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1643 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1644 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1645 meshlink_errno = MESHLINK_EINTERNAL;
1646 event_loop_stop(&mesh->loop);
1647 pthread_mutex_unlock(&mesh->mutex);
1651 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1652 mesh->threadstarted = true;
1654 // Ensure we are considered reachable
1657 pthread_mutex_unlock(&mesh->mutex);
1661 void meshlink_stop(meshlink_handle_t *mesh) {
1663 meshlink_errno = MESHLINK_EINVAL;
1667 pthread_mutex_lock(&mesh->mutex);
1668 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1670 // Shut down the main thread
1671 event_loop_stop(&mesh->loop);
1673 // Send ourselves a UDP packet to kick the event loop
1674 for(int i = 0; i < mesh->listen_sockets; i++) {
1676 socklen_t salen = sizeof(sa);
1678 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1679 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1683 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1684 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1688 if(mesh->threadstarted) {
1689 // Wait for the main thread to finish
1690 pthread_mutex_unlock(&mesh->mutex);
1691 pthread_join(mesh->thread, NULL);
1692 pthread_mutex_lock(&mesh->mutex);
1694 mesh->threadstarted = false;
1697 // Close all metaconnections
1698 if(mesh->connections) {
1699 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1701 connection_t *c = node->data;
1703 terminate_connection(mesh, c, false);
1708 exit_outgoings(mesh);
1710 // Ensure we are considered unreachable
1715 // Try to write out any changed node config files, ignore errors at this point.
1717 for splay_each(node_t, n, mesh->nodes) {
1718 if(n->status.dirty) {
1719 n->status.dirty = !node_write_config(mesh, n);
1724 pthread_mutex_unlock(&mesh->mutex);
1727 void meshlink_close(meshlink_handle_t *mesh) {
1729 meshlink_errno = MESHLINK_EINVAL;
1733 // stop can be called even if mesh has not been started
1734 meshlink_stop(mesh);
1736 // lock is not released after this
1737 pthread_mutex_lock(&mesh->mutex);
1739 // Close and free all resources used.
1741 close_network_connections(mesh);
1743 logger(mesh, MESHLINK_INFO, "Terminating");
1745 event_loop_exit(&mesh->loop);
1749 if(mesh->confbase) {
1755 ecdsa_free(mesh->invitation_key);
1757 if(mesh->netns != -1) {
1761 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1765 meshlink_queue_exit(&mesh->outpacketqueue);
1768 free(mesh->appname);
1769 free(mesh->confbase);
1770 free(mesh->config_key);
1771 free(mesh->external_address_url);
1773 ecdsa_free(mesh->private_key);
1775 if(mesh->invitation_addresses) {
1776 list_delete_list(mesh->invitation_addresses);
1779 main_config_unlock(mesh);
1781 pthread_mutex_unlock(&mesh->mutex);
1782 pthread_mutex_destroy(&mesh->mutex);
1784 memset(mesh, 0, sizeof(*mesh));
1789 bool meshlink_destroy(const char *confbase) {
1791 meshlink_errno = MESHLINK_EINVAL;
1795 /* Exit early if the confbase directory itself doesn't exist */
1796 if(access(confbase, F_OK) && errno == ENOENT) {
1800 /* Take the lock the same way meshlink_open() would. */
1801 char lockfilename[PATH_MAX];
1802 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1804 FILE *lockfile = fopen(lockfilename, "w+");
1807 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1808 meshlink_errno = MESHLINK_ESTORAGE;
1813 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1817 // TODO: use _locking()?
1820 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1821 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1823 meshlink_errno = MESHLINK_EBUSY;
1829 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1830 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1834 if(unlink(lockfilename)) {
1835 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1837 meshlink_errno = MESHLINK_ESTORAGE;
1843 if(!sync_path(confbase)) {
1844 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1845 meshlink_errno = MESHLINK_ESTORAGE;
1852 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1854 meshlink_errno = MESHLINK_EINVAL;
1858 pthread_mutex_lock(&mesh->mutex);
1859 mesh->receive_cb = cb;
1860 pthread_mutex_unlock(&mesh->mutex);
1863 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1865 meshlink_errno = MESHLINK_EINVAL;
1869 pthread_mutex_lock(&mesh->mutex);
1870 mesh->connection_try_cb = cb;
1871 pthread_mutex_unlock(&mesh->mutex);
1874 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1876 meshlink_errno = MESHLINK_EINVAL;
1880 pthread_mutex_lock(&mesh->mutex);
1881 mesh->node_status_cb = cb;
1882 pthread_mutex_unlock(&mesh->mutex);
1885 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1887 meshlink_errno = MESHLINK_EINVAL;
1891 pthread_mutex_lock(&mesh->mutex);
1892 mesh->node_pmtu_cb = cb;
1893 pthread_mutex_unlock(&mesh->mutex);
1896 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1898 meshlink_errno = MESHLINK_EINVAL;
1902 pthread_mutex_lock(&mesh->mutex);
1903 mesh->node_duplicate_cb = cb;
1904 pthread_mutex_unlock(&mesh->mutex);
1907 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1909 pthread_mutex_lock(&mesh->mutex);
1911 mesh->log_level = cb ? level : 0;
1912 pthread_mutex_unlock(&mesh->mutex);
1915 global_log_level = cb ? level : 0;
1919 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1921 meshlink_errno = MESHLINK_EINVAL;
1925 pthread_mutex_lock(&mesh->mutex);
1926 mesh->error_cb = cb;
1927 pthread_mutex_unlock(&mesh->mutex);
1930 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1931 meshlink_packethdr_t *hdr;
1933 if(len >= MAXSIZE - sizeof(*hdr)) {
1934 meshlink_errno = MESHLINK_EINVAL;
1938 node_t *n = (node_t *)destination;
1940 if(n->status.blacklisted) {
1941 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1942 meshlink_errno = MESHLINK_EBLACKLISTED;
1946 // Prepare the packet
1947 packet->probe = false;
1948 packet->tcp = false;
1949 packet->len = len + sizeof(*hdr);
1951 hdr = (meshlink_packethdr_t *)packet->data;
1952 memset(hdr, 0, sizeof(*hdr));
1953 // leave the last byte as 0 to make sure strings are always
1954 // null-terminated if they are longer than the buffer
1955 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1956 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1958 memcpy(packet->data + sizeof(*hdr), data, len);
1963 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1965 assert(destination);
1969 // Prepare the packet
1970 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
1974 // Send it immediately
1975 route(mesh, mesh->self, mesh->packet);
1980 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1981 // Validate arguments
1982 if(!mesh || !destination) {
1983 meshlink_errno = MESHLINK_EINVAL;
1992 meshlink_errno = MESHLINK_EINVAL;
1996 // Prepare the packet
1997 vpn_packet_t *packet = malloc(sizeof(*packet));
2000 meshlink_errno = MESHLINK_ENOMEM;
2004 if(!prepare_packet(mesh, destination, data, len, packet)) {
2009 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2011 meshlink_errno = MESHLINK_ENOMEM;
2015 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2017 // Notify event loop
2018 signal_trigger(&mesh->loop, &mesh->datafromapp);
2023 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2025 meshlink_handle_t *mesh = data;
2027 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2029 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2030 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2031 mesh->self->in_packets++;
2032 mesh->self->in_bytes += packet->len;
2033 route(mesh, mesh->self, packet);
2038 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2039 if(!mesh || !destination) {
2040 meshlink_errno = MESHLINK_EINVAL;
2044 pthread_mutex_lock(&mesh->mutex);
2046 node_t *n = (node_t *)destination;
2048 if(!n->status.reachable) {
2049 pthread_mutex_unlock(&mesh->mutex);
2052 } else if(n->mtuprobes > 30 && n->minmtu) {
2053 pthread_mutex_unlock(&mesh->mutex);
2056 pthread_mutex_unlock(&mesh->mutex);
2061 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2062 if(!mesh || !node) {
2063 meshlink_errno = MESHLINK_EINVAL;
2067 pthread_mutex_lock(&mesh->mutex);
2069 node_t *n = (node_t *)node;
2071 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2072 meshlink_errno = MESHLINK_EINTERNAL;
2073 pthread_mutex_unlock(&mesh->mutex);
2077 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2080 meshlink_errno = MESHLINK_EINTERNAL;
2083 pthread_mutex_unlock(&mesh->mutex);
2087 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2089 meshlink_errno = MESHLINK_EINVAL;
2093 return (meshlink_node_t *)mesh->self;
2096 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2097 if(!mesh || !name) {
2098 meshlink_errno = MESHLINK_EINVAL;
2104 pthread_mutex_lock(&mesh->mutex);
2105 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2106 pthread_mutex_unlock(&mesh->mutex);
2109 meshlink_errno = MESHLINK_ENOENT;
2112 return (meshlink_node_t *)n;
2115 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2116 if(!mesh || !name) {
2117 meshlink_errno = MESHLINK_EINVAL;
2121 meshlink_submesh_t *submesh = NULL;
2123 pthread_mutex_lock(&mesh->mutex);
2124 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2125 pthread_mutex_unlock(&mesh->mutex);
2128 meshlink_errno = MESHLINK_ENOENT;
2134 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2135 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2136 meshlink_errno = MESHLINK_EINVAL;
2140 meshlink_node_t **result;
2143 pthread_mutex_lock(&mesh->mutex);
2145 *nmemb = mesh->nodes->count;
2146 result = realloc(nodes, *nmemb * sizeof(*nodes));
2149 meshlink_node_t **p = result;
2151 for splay_each(node_t, n, mesh->nodes) {
2152 *p++ = (meshlink_node_t *)n;
2157 meshlink_errno = MESHLINK_ENOMEM;
2160 pthread_mutex_unlock(&mesh->mutex);
2165 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) {
2166 meshlink_node_t **result;
2168 pthread_mutex_lock(&mesh->mutex);
2172 for splay_each(node_t, n, mesh->nodes) {
2173 if(search_node(n, condition)) {
2180 pthread_mutex_unlock(&mesh->mutex);
2184 result = realloc(nodes, *nmemb * sizeof(*nodes));
2187 meshlink_node_t **p = result;
2189 for splay_each(node_t, n, mesh->nodes) {
2190 if(search_node(n, condition)) {
2191 *p++ = (meshlink_node_t *)n;
2197 meshlink_errno = MESHLINK_ENOMEM;
2200 pthread_mutex_unlock(&mesh->mutex);
2205 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2206 dev_class_t *devclass = (dev_class_t *)condition;
2208 if(*devclass == (dev_class_t)node->devclass) {
2215 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2216 if(condition == node->submesh) {
2228 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2229 const struct time_range *range = condition;
2230 time_t start = node->last_reachable;
2231 time_t end = node->last_unreachable;
2241 if(range->end >= range->start) {
2242 return start <= range->end && end >= range->start;
2244 return start > range->start || end < range->end;
2248 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) {
2249 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2250 meshlink_errno = MESHLINK_EINVAL;
2254 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2257 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2258 if(!mesh || !submesh || !nmemb) {
2259 meshlink_errno = MESHLINK_EINVAL;
2263 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2266 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) {
2267 if(!mesh || !nmemb) {
2268 meshlink_errno = MESHLINK_EINVAL;
2272 struct time_range range = {start, end};
2274 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2277 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2278 if(!mesh || !node) {
2279 meshlink_errno = MESHLINK_EINVAL;
2283 dev_class_t devclass;
2285 pthread_mutex_lock(&mesh->mutex);
2287 devclass = ((node_t *)node)->devclass;
2289 pthread_mutex_unlock(&mesh->mutex);
2294 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2295 if(!mesh || !node) {
2296 meshlink_errno = MESHLINK_EINVAL;
2300 node_t *n = (node_t *)node;
2302 meshlink_submesh_t *s;
2304 s = (meshlink_submesh_t *)n->submesh;
2309 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2310 if(!mesh || !node) {
2311 meshlink_errno = MESHLINK_EINVAL;
2315 node_t *n = (node_t *)node;
2318 pthread_mutex_lock(&mesh->mutex);
2319 reachable = n->status.reachable && !n->status.blacklisted;
2321 if(last_reachable) {
2322 *last_reachable = n->last_reachable;
2325 if(last_unreachable) {
2326 *last_unreachable = n->last_unreachable;
2329 pthread_mutex_unlock(&mesh->mutex);
2334 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2335 if(!mesh || !data || !len || !signature || !siglen) {
2336 meshlink_errno = MESHLINK_EINVAL;
2340 if(*siglen < MESHLINK_SIGLEN) {
2341 meshlink_errno = MESHLINK_EINVAL;
2345 pthread_mutex_lock(&mesh->mutex);
2347 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2348 meshlink_errno = MESHLINK_EINTERNAL;
2349 pthread_mutex_unlock(&mesh->mutex);
2353 *siglen = MESHLINK_SIGLEN;
2354 pthread_mutex_unlock(&mesh->mutex);
2358 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2359 if(!mesh || !source || !data || !len || !signature) {
2360 meshlink_errno = MESHLINK_EINVAL;
2364 if(siglen != MESHLINK_SIGLEN) {
2365 meshlink_errno = MESHLINK_EINVAL;
2369 pthread_mutex_lock(&mesh->mutex);
2373 struct node_t *n = (struct node_t *)source;
2375 if(!node_read_public_key(mesh, n)) {
2376 meshlink_errno = MESHLINK_EINTERNAL;
2379 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2382 pthread_mutex_unlock(&mesh->mutex);
2386 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2387 pthread_mutex_lock(&mesh->mutex);
2389 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2392 // TODO: Update invitation key if necessary?
2395 pthread_mutex_unlock(&mesh->mutex);
2397 return mesh->invitation_key;
2400 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2401 if(!mesh || !node || !address) {
2402 meshlink_errno = MESHLINK_EINVAL;
2406 if(!is_valid_hostname(address)) {
2407 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2408 meshlink_errno = MESHLINK_EINVAL;
2412 if(port && !is_valid_port(port)) {
2413 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2414 meshlink_errno = MESHLINK_EINVAL;
2418 char *canonical_address;
2421 xasprintf(&canonical_address, "%s %s", address, port);
2423 canonical_address = xstrdup(address);
2426 pthread_mutex_lock(&mesh->mutex);
2428 node_t *n = (node_t *)node;
2429 free(n->canonical_address);
2430 n->canonical_address = canonical_address;
2432 if(!node_write_config(mesh, n)) {
2433 pthread_mutex_unlock(&mesh->mutex);
2437 pthread_mutex_unlock(&mesh->mutex);
2439 return config_sync(mesh, "current");
2442 bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
2443 if(!mesh || !address) {
2444 meshlink_errno = MESHLINK_EINVAL;
2448 if(!is_valid_hostname(address)) {
2449 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2450 meshlink_errno = MESHLINK_EINVAL;
2454 if(port && !is_valid_port(port)) {
2455 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2456 meshlink_errno = MESHLINK_EINVAL;
2463 xasprintf(&combo, "%s/%s", address, port);
2465 combo = xstrdup(address);
2468 pthread_mutex_lock(&mesh->mutex);
2470 if(!mesh->invitation_addresses) {
2471 mesh->invitation_addresses = list_alloc((list_action_t)free);
2474 list_insert_tail(mesh->invitation_addresses, combo);
2475 pthread_mutex_unlock(&mesh->mutex);
2480 void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
2482 meshlink_errno = MESHLINK_EINVAL;
2486 pthread_mutex_lock(&mesh->mutex);
2488 if(mesh->invitation_addresses) {
2489 list_delete_list(mesh->invitation_addresses);
2490 mesh->invitation_addresses = NULL;
2493 pthread_mutex_unlock(&mesh->mutex);
2496 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2497 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2500 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2502 meshlink_errno = MESHLINK_EINVAL;
2506 char *address = meshlink_get_external_address(mesh);
2512 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2518 int meshlink_get_port(meshlink_handle_t *mesh) {
2520 meshlink_errno = MESHLINK_EINVAL;
2525 meshlink_errno = MESHLINK_EINTERNAL;
2531 pthread_mutex_lock(&mesh->mutex);
2532 port = atoi(mesh->myport);
2533 pthread_mutex_unlock(&mesh->mutex);
2538 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2539 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2540 meshlink_errno = MESHLINK_EINVAL;
2544 if(mesh->myport && port == atoi(mesh->myport)) {
2548 if(!try_bind(mesh, port)) {
2549 meshlink_errno = MESHLINK_ENETWORK;
2553 devtool_trybind_probe();
2557 pthread_mutex_lock(&mesh->mutex);
2559 if(mesh->threadstarted) {
2560 meshlink_errno = MESHLINK_EINVAL;
2565 xasprintf(&mesh->myport, "%d", port);
2567 /* Close down the network. This also deletes mesh->self. */
2568 close_network_connections(mesh);
2570 /* Recreate mesh->self. */
2571 mesh->self = new_node();
2572 mesh->self->name = xstrdup(mesh->name);
2573 mesh->self->devclass = mesh->devclass;
2574 mesh->self->session_id = mesh->session_id;
2575 xasprintf(&mesh->myport, "%d", port);
2577 if(!node_read_public_key(mesh, mesh->self)) {
2578 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2579 meshlink_errno = MESHLINK_ESTORAGE;
2580 free_node(mesh->self);
2583 } else if(!setup_network(mesh)) {
2584 meshlink_errno = MESHLINK_ENETWORK;
2588 /* Rebuild our own list of recent addresses */
2589 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2590 add_local_addresses(mesh);
2592 /* Write meshlink.conf with the updated port number */
2593 write_main_config_files(mesh);
2595 rval = config_sync(mesh, "current");
2598 pthread_mutex_unlock(&mesh->mutex);
2600 return rval && meshlink_get_port(mesh) == port;
2603 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2604 mesh->invitation_timeout = timeout;
2607 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2608 meshlink_submesh_t *s = NULL;
2611 meshlink_errno = MESHLINK_EINVAL;
2616 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2619 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2620 meshlink_errno = MESHLINK_EINVAL;
2624 s = (meshlink_submesh_t *)mesh->self->submesh;
2627 pthread_mutex_lock(&mesh->mutex);
2629 // Check validity of the new node's name
2630 if(!check_id(name)) {
2631 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2632 meshlink_errno = MESHLINK_EINVAL;
2633 pthread_mutex_unlock(&mesh->mutex);
2637 // Ensure no host configuration file with that name exists
2638 if(config_exists(mesh, "current", name)) {
2639 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2640 meshlink_errno = MESHLINK_EEXIST;
2641 pthread_mutex_unlock(&mesh->mutex);
2645 // Ensure no other nodes know about this name
2646 if(lookup_node(mesh, name)) {
2647 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2648 meshlink_errno = MESHLINK_EEXIST;
2649 pthread_mutex_unlock(&mesh->mutex);
2653 // Get the local address
2654 char *address = get_my_hostname(mesh, flags);
2657 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2658 meshlink_errno = MESHLINK_ERESOLV;
2659 pthread_mutex_unlock(&mesh->mutex);
2663 if(!refresh_invitation_key(mesh)) {
2664 meshlink_errno = MESHLINK_EINTERNAL;
2665 pthread_mutex_unlock(&mesh->mutex);
2669 // If we changed our own host config file, write it out now
2670 if(mesh->self->status.dirty) {
2671 if(!node_write_config(mesh, mesh->self)) {
2672 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2673 pthread_mutex_unlock(&mesh->mutex);
2680 // Create a hash of the key.
2681 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2682 sha512(fingerprint, strlen(fingerprint), hash);
2683 b64encode_urlsafe(hash, hash, 18);
2685 // Create a random cookie for this invitation.
2687 randomize(cookie, 18);
2689 // Create a filename that doesn't reveal the cookie itself
2690 char buf[18 + strlen(fingerprint)];
2691 char cookiehash[64];
2692 memcpy(buf, cookie, 18);
2693 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2694 sha512(buf, sizeof(buf), cookiehash);
2695 b64encode_urlsafe(cookiehash, cookiehash, 18);
2697 b64encode_urlsafe(cookie, cookie, 18);
2701 /* Construct the invitation file */
2702 uint8_t outbuf[4096];
2703 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2705 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2706 packmsg_add_str(&inv, name);
2707 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2708 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2710 /* TODO: Add several host config files to bootstrap connections.
2711 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2712 * and are not blacklisted.
2714 config_t configs[5];
2715 memset(configs, 0, sizeof(configs));
2718 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2722 /* Append host config files to the invitation file */
2723 packmsg_add_array(&inv, count);
2725 for(int i = 0; i < count; i++) {
2726 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2727 config_free(&configs[i]);
2730 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2732 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2733 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2734 meshlink_errno = MESHLINK_ESTORAGE;
2735 pthread_mutex_unlock(&mesh->mutex);
2739 // Create an URL from the local address, key hash and cookie
2741 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2744 pthread_mutex_unlock(&mesh->mutex);
2748 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2749 return meshlink_invite_ex(mesh, submesh, name, 0);
2752 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2753 if(!mesh || !invitation) {
2754 meshlink_errno = MESHLINK_EINVAL;
2758 join_state_t state = {
2763 ecdsa_t *key = NULL;
2764 ecdsa_t *hiskey = NULL;
2766 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2767 char copy[strlen(invitation) + 1];
2769 pthread_mutex_lock(&mesh->mutex);
2771 //Before doing meshlink_join make sure we are not connected to another mesh
2772 if(mesh->threadstarted) {
2773 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2774 meshlink_errno = MESHLINK_EINVAL;
2778 // 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.
2779 if(mesh->nodes->count > 1) {
2780 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2781 meshlink_errno = MESHLINK_EINVAL;
2785 strcpy(copy, invitation);
2787 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2789 char *slash = strchr(copy, '/');
2797 if(strlen(slash) != 48) {
2801 char *address = copy;
2804 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2808 if(mesh->inviter_commits_first) {
2809 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2812 // Generate a throw-away key for the invitation.
2813 key = ecdsa_generate();
2816 meshlink_errno = MESHLINK_EINTERNAL;
2820 char *b64key = ecdsa_get_base64_public_key(key);
2823 while(address && *address) {
2824 // We allow commas in the address part to support multiple addresses in one invitation URL.
2825 comma = strchr(address, ',');
2831 // Split of the port
2832 port = strrchr(address, ':');
2840 // IPv6 address are enclosed in brackets, per RFC 3986
2841 if(*address == '[') {
2843 char *bracket = strchr(address, ']');
2856 // Connect to the meshlink daemon mentioned in the URL.
2857 struct addrinfo *ai = adns_blocking_request(mesh, xstrdup(address), xstrdup(port), 5);
2860 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2861 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2863 if(state.sock == -1) {
2864 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2865 meshlink_errno = MESHLINK_ENETWORK;
2869 set_timeout(state.sock, 5000);
2871 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2872 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2873 meshlink_errno = MESHLINK_ENETWORK;
2874 closesocket(state.sock);
2884 meshlink_errno = MESHLINK_ERESOLV;
2887 if(state.sock != -1 || !comma) {
2894 if(state.sock == -1) {
2898 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2900 // Tell him we have an invitation, and give him our throw-away key.
2904 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2905 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2906 meshlink_errno = MESHLINK_ENETWORK;
2912 char hisname[4096] = "";
2913 int code, hismajor, hisminor = 0;
2915 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) {
2916 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2917 meshlink_errno = MESHLINK_ENETWORK;
2921 // Check if the hash of the key he gave us matches the hash in the URL.
2922 char *fingerprint = state.line + 2;
2925 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2926 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2927 meshlink_errno = MESHLINK_EINTERNAL;
2931 if(memcmp(hishash, state.hash, 18)) {
2932 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2933 meshlink_errno = MESHLINK_EPEER;
2937 hiskey = ecdsa_set_base64_public_key(fingerprint);
2940 meshlink_errno = MESHLINK_EINTERNAL;
2944 // Start an SPTPS session
2945 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2946 meshlink_errno = MESHLINK_EINTERNAL;
2950 // Feed rest of input buffer to SPTPS
2951 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2952 meshlink_errno = MESHLINK_EPEER;
2957 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
2959 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
2961 if(errno == EINTR) {
2965 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2966 meshlink_errno = MESHLINK_ENETWORK;
2970 if(!sptps_receive_data(&state.sptps, state.line, len)) {
2971 meshlink_errno = MESHLINK_EPEER;
2976 if(!state.success) {
2977 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2978 meshlink_errno = MESHLINK_EPEER;
2982 sptps_stop(&state.sptps);
2985 closesocket(state.sock);
2987 pthread_mutex_unlock(&mesh->mutex);
2991 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2992 meshlink_errno = MESHLINK_EINVAL;
2994 sptps_stop(&state.sptps);
2998 if(state.sock != -1) {
2999 closesocket(state.sock);
3002 pthread_mutex_unlock(&mesh->mutex);
3006 char *meshlink_export(meshlink_handle_t *mesh) {
3008 meshlink_errno = MESHLINK_EINVAL;
3012 // Create a config file on the fly.
3015 packmsg_output_t out = {buf, sizeof(buf)};
3016 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
3017 packmsg_add_str(&out, mesh->name);
3018 packmsg_add_str(&out, CORE_MESH);
3020 pthread_mutex_lock(&mesh->mutex);
3022 packmsg_add_int32(&out, mesh->self->devclass);
3023 packmsg_add_bool(&out, mesh->self->status.blacklisted);
3024 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
3025 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3029 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3030 if(mesh->self->recent[i].sa.sa_family) {
3037 packmsg_add_array(&out, count);
3039 for(uint32_t i = 0; i < count; i++) {
3040 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3043 packmsg_add_int64(&out, 0);
3044 packmsg_add_int64(&out, 0);
3046 pthread_mutex_unlock(&mesh->mutex);
3048 if(!packmsg_output_ok(&out)) {
3049 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3050 meshlink_errno = MESHLINK_EINTERNAL;
3054 // Prepare a base64-encoded packmsg array containing our config file
3056 uint32_t len = packmsg_output_size(&out, buf);
3057 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3058 uint8_t *buf2 = xmalloc(len2);
3059 packmsg_output_t out2 = {buf2, len2};
3060 packmsg_add_array(&out2, 1);
3061 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3063 if(!packmsg_output_ok(&out2)) {
3064 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3065 meshlink_errno = MESHLINK_EINTERNAL;
3070 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3072 return (char *)buf2;
3075 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3076 if(!mesh || !data) {
3077 meshlink_errno = MESHLINK_EINVAL;
3081 size_t datalen = strlen(data);
3082 uint8_t *buf = xmalloc(datalen);
3083 int buflen = b64decode(data, buf, datalen);
3086 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3087 meshlink_errno = MESHLINK_EPEER;
3091 packmsg_input_t in = {buf, buflen};
3092 uint32_t count = packmsg_get_array(&in);
3095 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3096 meshlink_errno = MESHLINK_EPEER;
3100 pthread_mutex_lock(&mesh->mutex);
3104 uint32_t len = packmsg_get_bin_raw(&in, &data);
3110 packmsg_input_t in2 = {data, len};
3111 uint32_t version = packmsg_get_uint32(&in2);
3112 char *name = packmsg_get_str_dup(&in2);
3114 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3116 packmsg_input_invalidate(&in);
3120 if(!check_id(name)) {
3125 node_t *n = lookup_node(mesh, name);
3128 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3136 config_t config = {data, len};
3138 if(!node_read_from_config(mesh, n, &config)) {
3140 packmsg_input_invalidate(&in);
3144 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3145 n->last_reachable = 0;
3146 n->last_unreachable = 0;
3148 if(!node_write_config(mesh, n)) {
3156 pthread_mutex_unlock(&mesh->mutex);
3160 if(!packmsg_done(&in)) {
3161 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3162 meshlink_errno = MESHLINK_EPEER;
3166 if(!config_sync(mesh, "current")) {
3173 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3174 if(n == mesh->self) {
3175 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3176 meshlink_errno = MESHLINK_EINVAL;
3180 if(n->status.blacklisted) {
3181 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3185 n->status.blacklisted = true;
3187 /* Immediately shut down any connections we have with the blacklisted node.
3188 * We can't call terminate_connection(), because we might be called from a callback function.
3190 for list_each(connection_t, c, mesh->connections) {
3192 shutdown(c->socket, SHUT_RDWR);
3196 utcp_abort_all_connections(n->utcp);
3202 n->status.udp_confirmed = false;
3204 if(n->status.reachable) {
3205 n->last_unreachable = time(NULL);
3208 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3209 * manually call the status callback if necessary.
3211 if(n->status.reachable && mesh->node_status_cb) {
3212 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3215 return node_write_config(mesh, n) && config_sync(mesh, "current");
3218 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3219 if(!mesh || !node) {
3220 meshlink_errno = MESHLINK_EINVAL;
3224 pthread_mutex_lock(&mesh->mutex);
3226 if(!blacklist(mesh, (node_t *)node)) {
3227 pthread_mutex_unlock(&mesh->mutex);
3231 pthread_mutex_unlock(&mesh->mutex);
3233 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3237 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3238 if(!mesh || !name) {
3239 meshlink_errno = MESHLINK_EINVAL;
3243 pthread_mutex_lock(&mesh->mutex);
3245 node_t *n = lookup_node(mesh, (char *)name);
3249 n->name = xstrdup(name);
3253 if(!blacklist(mesh, (node_t *)n)) {
3254 pthread_mutex_unlock(&mesh->mutex);
3258 pthread_mutex_unlock(&mesh->mutex);
3260 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3264 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3265 if(n == mesh->self) {
3266 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3267 meshlink_errno = MESHLINK_EINVAL;
3271 if(!n->status.blacklisted) {
3272 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3276 n->status.blacklisted = false;
3278 if(n->status.reachable) {
3279 n->last_reachable = time(NULL);
3280 update_node_status(mesh, n);
3283 return node_write_config(mesh, n) && config_sync(mesh, "current");
3286 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3287 if(!mesh || !node) {
3288 meshlink_errno = MESHLINK_EINVAL;
3292 pthread_mutex_lock(&mesh->mutex);
3294 if(!whitelist(mesh, (node_t *)node)) {
3295 pthread_mutex_unlock(&mesh->mutex);
3299 pthread_mutex_unlock(&mesh->mutex);
3301 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3305 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3306 if(!mesh || !name) {
3307 meshlink_errno = MESHLINK_EINVAL;
3311 pthread_mutex_lock(&mesh->mutex);
3313 node_t *n = lookup_node(mesh, (char *)name);
3317 n->name = xstrdup(name);
3321 if(!whitelist(mesh, (node_t *)n)) {
3322 pthread_mutex_unlock(&mesh->mutex);
3326 pthread_mutex_unlock(&mesh->mutex);
3328 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3332 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3333 mesh->default_blacklist = blacklist;
3336 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3337 if(!mesh || !node) {
3338 meshlink_errno = MESHLINK_EINVAL;
3342 node_t *n = (node_t *)node;
3344 pthread_mutex_lock(&mesh->mutex);
3346 /* Check that the node is not reachable */
3347 if(n->status.reachable || n->connection) {
3348 pthread_mutex_unlock(&mesh->mutex);
3349 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3353 /* Check that we don't have any active UTCP connections */
3354 if(n->utcp && utcp_is_active(n->utcp)) {
3355 pthread_mutex_unlock(&mesh->mutex);
3356 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3360 /* Check that we have no active connections to this node */
3361 for list_each(connection_t, c, mesh->connections) {
3363 pthread_mutex_unlock(&mesh->mutex);
3364 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3369 /* Remove any pending outgoings to this node */
3370 if(mesh->outgoings) {
3371 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3372 if(outgoing->node == n) {
3373 list_delete_node(mesh->outgoings, node);
3378 /* Delete the config file for this node */
3379 if(!config_delete(mesh, "current", n->name)) {
3380 pthread_mutex_unlock(&mesh->mutex);
3384 /* Delete the node struct and any remaining edges referencing this node */
3387 pthread_mutex_unlock(&mesh->mutex);
3389 return config_sync(mesh, "current");
3392 /* Hint that a hostname may be found at an address
3393 * See header file for detailed comment.
3395 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3396 if(!mesh || !node || !addr) {
3397 meshlink_errno = EINVAL;
3401 pthread_mutex_lock(&mesh->mutex);
3403 node_t *n = (node_t *)node;
3405 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3406 if(!node_write_config(mesh, n)) {
3407 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3411 pthread_mutex_unlock(&mesh->mutex);
3412 // @TODO do we want to fire off a connection attempt right away?
3415 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3417 node_t *n = utcp->priv;
3418 meshlink_handle_t *mesh = n->mesh;
3419 return mesh->channel_accept_cb;
3422 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3424 if(aio->cb.buffer) {
3425 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3429 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3434 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3435 meshlink_channel_t *channel = connection->priv;
3441 node_t *n = channel->node;
3442 meshlink_handle_t *mesh = n->mesh;
3444 if(n->status.destroyed) {
3445 meshlink_channel_close(mesh, channel);
3449 const char *p = data;
3452 while(channel->aio_receive) {
3453 meshlink_aio_buffer_t *aio = channel->aio_receive;
3454 size_t todo = aio->len - aio->done;
3461 memcpy((char *)aio->data + aio->done, p, todo);
3463 ssize_t result = write(aio->fd, p, todo);
3472 if(aio->done == aio->len) {
3473 channel->aio_receive = aio->next;
3474 aio_signal(mesh, channel, aio);
3486 if(channel->receive_cb) {
3487 channel->receive_cb(mesh, channel, p, left);
3493 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3494 node_t *n = utcp_connection->utcp->priv;
3500 meshlink_handle_t *mesh = n->mesh;
3502 if(!mesh->channel_accept_cb) {
3506 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3508 channel->c = utcp_connection;
3510 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3511 utcp_accept(utcp_connection, channel_recv, channel);
3517 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3518 node_t *n = utcp->priv;
3520 if(n->status.destroyed) {
3524 meshlink_handle_t *mesh = n->mesh;
3525 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3528 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3529 if(!mesh || !channel) {
3530 meshlink_errno = MESHLINK_EINVAL;
3534 channel->receive_cb = cb;
3537 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3539 node_t *n = (node_t *)source;
3545 utcp_recv(n->utcp, data, len);
3548 static void channel_poll(struct utcp_connection *connection, size_t len) {
3549 meshlink_channel_t *channel = connection->priv;
3555 node_t *n = channel->node;
3556 meshlink_handle_t *mesh = n->mesh;
3557 meshlink_aio_buffer_t *aio = channel->aio_send;
3560 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3561 size_t left = aio->len - aio->done;
3569 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3572 size_t todo = utcp_get_sndbuf_free(connection);
3578 if(todo > sizeof(buf)) {
3582 ssize_t result = read(aio->fd, buf, todo);
3585 sent = utcp_send(connection, buf, result);
3595 /* If the buffer is now completely sent, call the callback and dispose of it. */
3596 if(aio->done >= aio->len) {
3597 channel->aio_send = aio->next;
3598 aio_signal(mesh, channel, aio);
3602 if(channel->poll_cb) {
3603 channel->poll_cb(mesh, channel, len);
3605 utcp_set_poll_cb(connection, NULL);
3610 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3611 if(!mesh || !channel) {
3612 meshlink_errno = MESHLINK_EINVAL;
3616 pthread_mutex_lock(&mesh->mutex);
3617 channel->poll_cb = cb;
3618 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3619 pthread_mutex_unlock(&mesh->mutex);
3622 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3624 meshlink_errno = MESHLINK_EINVAL;
3628 pthread_mutex_lock(&mesh->mutex);
3629 mesh->channel_accept_cb = cb;
3630 mesh->receive_cb = channel_receive;
3632 for splay_each(node_t, n, mesh->nodes) {
3633 if(!n->utcp && n != mesh->self) {
3634 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3635 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3639 pthread_mutex_unlock(&mesh->mutex);
3642 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3646 meshlink_errno = MESHLINK_EINVAL;
3650 pthread_mutex_lock(&mesh->mutex);
3651 utcp_set_sndbuf(channel->c, size);
3652 pthread_mutex_unlock(&mesh->mutex);
3655 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3659 meshlink_errno = MESHLINK_EINVAL;
3663 pthread_mutex_lock(&mesh->mutex);
3664 utcp_set_rcvbuf(channel->c, size);
3665 pthread_mutex_unlock(&mesh->mutex);
3668 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) {
3670 abort(); // TODO: handle non-NULL data
3673 if(!mesh || !node) {
3674 meshlink_errno = MESHLINK_EINVAL;
3678 pthread_mutex_lock(&mesh->mutex);
3680 node_t *n = (node_t *)node;
3683 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3684 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3685 mesh->receive_cb = channel_receive;
3688 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3689 pthread_mutex_unlock(&mesh->mutex);
3694 if(n->status.blacklisted) {
3695 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3696 meshlink_errno = MESHLINK_EBLACKLISTED;
3697 pthread_mutex_unlock(&mesh->mutex);
3701 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3703 channel->receive_cb = cb;
3706 channel->priv = (void *)data;
3709 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3711 pthread_mutex_unlock(&mesh->mutex);
3714 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3722 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) {
3723 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3726 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3727 if(!mesh || !channel) {
3728 meshlink_errno = MESHLINK_EINVAL;
3732 pthread_mutex_lock(&mesh->mutex);
3733 utcp_shutdown(channel->c, direction);
3734 pthread_mutex_unlock(&mesh->mutex);
3737 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3738 if(!mesh || !channel) {
3739 meshlink_errno = MESHLINK_EINVAL;
3743 pthread_mutex_lock(&mesh->mutex);
3745 utcp_close(channel->c);
3747 /* Clean up any outstanding AIO buffers. */
3748 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3750 aio_signal(mesh, channel, aio);
3754 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3756 aio_signal(mesh, channel, aio);
3760 pthread_mutex_unlock(&mesh->mutex);
3765 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3766 if(!mesh || !channel) {
3767 meshlink_errno = MESHLINK_EINVAL;
3776 meshlink_errno = MESHLINK_EINVAL;
3780 // TODO: more finegrained locking.
3781 // Ideally we want to put the data into the UTCP connection's send buffer.
3782 // Then, preferably only if there is room in the receiver window,
3783 // kick the meshlink thread to go send packets.
3787 pthread_mutex_lock(&mesh->mutex);
3789 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3790 if(channel->aio_send) {
3793 retval = utcp_send(channel->c, data, len);
3796 pthread_mutex_unlock(&mesh->mutex);
3799 meshlink_errno = MESHLINK_ENETWORK;
3805 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) {
3806 if(!mesh || !channel) {
3807 meshlink_errno = MESHLINK_EINVAL;
3812 meshlink_errno = MESHLINK_EINVAL;
3816 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3819 aio->cb.buffer = cb;
3822 pthread_mutex_lock(&mesh->mutex);
3824 /* Append the AIO buffer descriptor to the end of the chain */
3825 meshlink_aio_buffer_t **p = &channel->aio_send;
3833 /* Ensure the poll callback is set, and call it right now to push data if possible */
3834 utcp_set_poll_cb(channel->c, channel_poll);
3835 channel_poll(channel->c, len);
3837 pthread_mutex_unlock(&mesh->mutex);
3842 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) {
3843 if(!mesh || !channel) {
3844 meshlink_errno = MESHLINK_EINVAL;
3848 if(!len || fd == -1) {
3849 meshlink_errno = MESHLINK_EINVAL;
3853 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3859 pthread_mutex_lock(&mesh->mutex);
3861 /* Append the AIO buffer descriptor to the end of the chain */
3862 meshlink_aio_buffer_t **p = &channel->aio_send;
3870 /* Ensure the poll callback is set, and call it right now to push data if possible */
3871 utcp_set_poll_cb(channel->c, channel_poll);
3872 channel_poll(channel->c, len);
3874 pthread_mutex_unlock(&mesh->mutex);
3879 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) {
3880 if(!mesh || !channel) {
3881 meshlink_errno = MESHLINK_EINVAL;
3886 meshlink_errno = MESHLINK_EINVAL;
3890 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3893 aio->cb.buffer = cb;
3896 pthread_mutex_lock(&mesh->mutex);
3898 /* Append the AIO buffer descriptor to the end of the chain */
3899 meshlink_aio_buffer_t **p = &channel->aio_receive;
3907 pthread_mutex_unlock(&mesh->mutex);
3912 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) {
3913 if(!mesh || !channel) {
3914 meshlink_errno = MESHLINK_EINVAL;
3918 if(!len || fd == -1) {
3919 meshlink_errno = MESHLINK_EINVAL;
3923 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3929 pthread_mutex_lock(&mesh->mutex);
3931 /* Append the AIO buffer descriptor to the end of the chain */
3932 meshlink_aio_buffer_t **p = &channel->aio_receive;
3940 pthread_mutex_unlock(&mesh->mutex);
3945 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3946 if(!mesh || !channel) {
3947 meshlink_errno = MESHLINK_EINVAL;
3951 return channel->c->flags;
3954 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3955 if(!mesh || !channel) {
3956 meshlink_errno = MESHLINK_EINVAL;
3960 return utcp_get_sendq(channel->c);
3963 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3964 if(!mesh || !channel) {
3965 meshlink_errno = MESHLINK_EINVAL;
3969 return utcp_get_recvq(channel->c);
3972 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3973 if(!mesh || !channel) {
3974 meshlink_errno = MESHLINK_EINVAL;
3978 return utcp_get_mss(channel->node->utcp);
3981 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3982 if(!mesh || !node) {
3983 meshlink_errno = MESHLINK_EINVAL;
3987 node_t *n = (node_t *)node;
3989 pthread_mutex_lock(&mesh->mutex);
3992 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3993 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3996 utcp_set_user_timeout(n->utcp, timeout);
3998 pthread_mutex_unlock(&mesh->mutex);
4001 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4002 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4003 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4004 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4007 if(mesh->node_status_cb) {
4008 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4011 if(mesh->node_pmtu_cb) {
4012 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4016 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4017 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4019 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4020 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4024 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4025 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4029 n->status.duplicate = true;
4030 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4033 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4037 meshlink_errno = MESHLINK_EINVAL;
4041 pthread_mutex_lock(&mesh->mutex);
4043 if(mesh->discovery == enable) {
4047 if(mesh->threadstarted) {
4049 discovery_start(mesh);
4051 discovery_stop(mesh);
4055 mesh->discovery = enable;
4058 pthread_mutex_unlock(&mesh->mutex);
4062 meshlink_errno = MESHLINK_ENOTSUP;
4066 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4067 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4068 meshlink_errno = EINVAL;
4072 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4073 meshlink_errno = EINVAL;
4077 pthread_mutex_lock(&mesh->mutex);
4078 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4079 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4080 pthread_mutex_unlock(&mesh->mutex);
4083 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4084 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4085 meshlink_errno = EINVAL;
4089 if(fast_retry_period < 0) {
4090 meshlink_errno = EINVAL;
4094 pthread_mutex_lock(&mesh->mutex);
4095 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4096 pthread_mutex_unlock(&mesh->mutex);
4099 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4101 meshlink_errno = EINVAL;
4105 pthread_mutex_lock(&mesh->mutex);
4106 mesh->inviter_commits_first = inviter_commits_first;
4107 pthread_mutex_unlock(&mesh->mutex);
4110 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4112 meshlink_errno = EINVAL;
4116 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4117 meshlink_errno = EINVAL;
4121 pthread_mutex_lock(&mesh->mutex);
4122 free(mesh->external_address_url);
4123 mesh->external_address_url = url ? xstrdup(url) : NULL;
4124 pthread_mutex_unlock(&mesh->mutex);
4127 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4128 if(!mesh || granularity < 0) {
4129 meshlink_errno = EINVAL;
4133 utcp_set_clock_granularity(granularity);
4136 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4139 if(!mesh->connections || !mesh->loop.running) {
4146 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
4147 // We should only call the callback function if we are in the background thread.
4148 if(!mesh->error_cb) {
4152 if(!mesh->threadstarted) {
4156 if(mesh->thread == pthread_self()) {
4157 mesh->error_cb(mesh, meshlink_errno);
4161 static void __attribute__((constructor)) meshlink_init(void) {
4163 utcp_set_clock_granularity(10000);
4166 static void __attribute__((destructor)) meshlink_exit(void) {