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,
178 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
182 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
189 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
197 if(getsockname(sock, &sa->sa, salen)) {
206 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
208 socklen_t salen = sizeof(sa);
210 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
214 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
221 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
222 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
225 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
226 const char *url = mesh->external_address_url;
229 url = "http://meshlink.io/host.cgi";
232 /* Find the hostname part between the slashes */
233 if(strncmp(url, "http://", 7)) {
235 meshlink_errno = MESHLINK_EINTERNAL;
239 const char *begin = url + 7;
241 const char *end = strchr(begin, '/');
244 end = begin + strlen(begin);
248 char host[end - begin + 1];
249 strncpy(host, begin, end - begin);
250 host[end - begin] = 0;
252 char *port = strchr(host, ':');
258 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
259 struct addrinfo *ai = str2addrinfo(host, port ? port : "80", SOCK_STREAM);
261 char *hostname = NULL;
263 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
264 if(family != AF_UNSPEC && aip->ai_family != family) {
268 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
271 set_timeout(s, 5000);
273 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
280 send(s, "GET ", 4, 0);
281 send(s, url, strlen(url), 0);
282 send(s, " HTTP/1.0\r\n\r\n", 13, 0);
283 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
288 if(line[len - 1] == '\n') {
292 char *p = strrchr(line, '\n');
295 hostname = xstrdup(p + 1);
311 // Check that the hostname is reasonable
312 if(hostname && !is_valid_hostname(hostname)) {
318 meshlink_errno = MESHLINK_ERESOLV;
324 static bool is_localaddr(sockaddr_t *sa) {
325 switch(sa->sa.sa_family) {
327 return *(uint8_t *)(&sa->in.sin_addr.s_addr) == 127;
330 uint16_t first = sa->in6.sin6_addr.s6_addr[0] << 8 | sa->in6.sin6_addr.s6_addr[1];
331 return first == 0 || (first & 0xffc0) == 0xfe80;
339 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
342 // Determine address of the local interface used for outgoing connections.
343 char localaddr[NI_MAXHOST];
344 bool success = false;
346 if(family == AF_INET) {
347 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
348 } else if(family == AF_INET6) {
349 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
352 #ifdef HAVE_GETIFADDRS
355 struct ifaddrs *ifa = NULL;
358 for(struct ifaddrs *ifap = ifa; ifap; ifap = ifap->ifa_next) {
359 sockaddr_t *sa = (sockaddr_t *)ifap->ifa_addr;
361 if(sa->sa.sa_family != family) {
365 if(is_localaddr(sa)) {
369 if(!getnameinfo(&sa->sa, SALEN(sa->sa), localaddr, sizeof(localaddr), NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
381 meshlink_errno = MESHLINK_ENETWORK;
385 return xstrdup(localaddr);
388 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
389 for(int i = 0; i < n; i++) {
394 // Ignore duplicate hostnames
397 for(int j = 0; j < i; j++) {
402 if(strcmp(host[i], host[j])) {
406 if(strcmp(port[i], port[j])) {
414 if(found || !is_valid_hostname(host[i])) {
424 // This gets the hostname part for use in invitation URLs
425 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
426 int count = 4 + (mesh->invitation_addresses ? mesh->invitation_addresses->count : 0);
428 char *hostname[count];
430 char *hostport = NULL;
432 memset(hostname, 0, sizeof(hostname));
433 memset(port, 0, sizeof(port));
435 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
436 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
439 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
440 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
443 // Add all explicitly set invitation addresses
444 if(mesh->invitation_addresses) {
445 for list_each(char, combo, mesh->invitation_addresses) {
446 hostname[n] = xstrdup(combo);
447 char *slash = strrchr(hostname[n], '/');
451 port[n] = xstrdup(slash + 1);
458 // Add local addresses if requested
459 if(flags & MESHLINK_INVITE_LOCAL) {
460 if(flags & MESHLINK_INVITE_IPV4) {
461 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET);
464 if(flags & MESHLINK_INVITE_IPV6) {
465 hostname[n++] = meshlink_get_local_address_for_family(mesh, AF_INET6);
469 // Add public/canonical addresses if requested
470 if(flags & MESHLINK_INVITE_PUBLIC) {
471 // Try the CanonicalAddress first
472 get_canonical_address(mesh->self, &hostname[n], &port[n]);
474 if(!hostname[n] && count == 4) {
475 if(flags & MESHLINK_INVITE_IPV4) {
476 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET);
479 if(flags & MESHLINK_INVITE_IPV6) {
480 hostname[n++] = meshlink_get_external_address_for_family(mesh, AF_INET6);
487 for(int i = 0; i < n; i++) {
488 // Ensure we always have a port number
489 if(hostname[i] && !port[i]) {
490 port[i] = xstrdup(mesh->myport);
494 remove_duplicate_hostnames(hostname, port, n);
496 // Resolve the hostnames
497 for(int i = 0; i < n; i++) {
502 // Convert what we have to a sockaddr
503 struct addrinfo *ai_in, *ai_out;
504 struct addrinfo hint = {
505 .ai_family = AF_UNSPEC,
506 .ai_flags = AI_NUMERICSERV,
507 .ai_socktype = SOCK_STREAM,
509 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
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);
520 if(flags & MESHLINK_INVITE_NUMERIC) {
521 // We don't need to do any further conversion
526 // Convert it to a hostname
527 char resolved_host[NI_MAXHOST];
528 char resolved_port[NI_MAXSERV];
529 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
531 if(err || !is_valid_hostname(resolved_host)) {
536 // Convert the hostname back to a sockaddr
537 hint.ai_family = ai_in->ai_family;
538 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
545 // Check if it's still the same sockaddr
546 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
548 freeaddrinfo(ai_out);
552 // Yes: replace the hostname with the resolved one
554 hostname[i] = xstrdup(resolved_host);
557 freeaddrinfo(ai_out);
560 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
561 remove_duplicate_hostnames(hostname, port, n);
563 // Concatenate all unique address to the hostport string
564 for(int i = 0; i < n; i++) {
569 // Append the address to the hostport string
571 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
573 hostport = newhostport;
582 static bool try_bind(meshlink_handle_t *mesh, int port) {
583 struct addrinfo *ai = NULL;
584 struct addrinfo hint = {
585 .ai_flags = AI_PASSIVE,
586 .ai_family = AF_UNSPEC,
587 .ai_socktype = SOCK_STREAM,
588 .ai_protocol = IPPROTO_TCP,
592 snprintf(portstr, sizeof(portstr), "%d", port);
594 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
598 bool success = false;
600 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
601 /* Try to bind to TCP. */
603 int tcp_fd = setup_tcp_listen_socket(mesh, aip);
606 if(errno == EADDRINUSE) {
607 /* If this port is in use for any address family, avoid it. */
615 /* If TCP worked, then we require that UDP works as well. */
617 int udp_fd = setup_udp_listen_socket(mesh, aip);
634 int check_port(meshlink_handle_t *mesh) {
635 for(int i = 0; i < 1000; i++) {
636 int port = 0x1000 + prng(mesh, 0x8000);
638 if(try_bind(mesh, port)) {
640 xasprintf(&mesh->myport, "%d", port);
645 meshlink_errno = MESHLINK_ENETWORK;
646 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
650 static bool write_main_config_files(meshlink_handle_t *mesh) {
651 if(!mesh->confbase) {
657 /* Write the main config file */
658 packmsg_output_t out = {buf, sizeof buf};
660 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
661 packmsg_add_str(&out, mesh->name);
662 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
663 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
664 packmsg_add_uint16(&out, atoi(mesh->myport));
666 if(!packmsg_output_ok(&out)) {
670 config_t config = {buf, packmsg_output_size(&out, buf)};
672 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
676 /* Write our own host config file */
677 if(!node_write_config(mesh, mesh->self)) {
685 meshlink_handle_t *mesh;
687 char cookie[18 + 32];
698 static bool finalize_join(join_state_t *state, const void *buf, uint16_t len) {
699 meshlink_handle_t *mesh = state->mesh;
700 packmsg_input_t in = {buf, len};
701 uint32_t version = packmsg_get_uint32(&in);
703 if(version != MESHLINK_INVITATION_VERSION) {
704 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
708 char *name = packmsg_get_str_dup(&in);
709 packmsg_skip_element(&in); /* submesh */
710 dev_class_t devclass = packmsg_get_int32(&in);
711 uint32_t count = packmsg_get_array(&in);
714 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
718 if(!check_id(name)) {
719 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
725 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
731 free(mesh->self->name);
733 mesh->self->name = xstrdup(name);
734 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
736 // Initialize configuration directory
737 if(!config_init(mesh, "current")) {
741 if(!write_main_config_files(mesh)) {
745 // Write host config files
746 for(uint32_t i = 0; i < count; i++) {
748 uint32_t len = packmsg_get_bin_raw(&in, &data);
751 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
755 packmsg_input_t in2 = {data, len};
756 uint32_t version = packmsg_get_uint32(&in2);
757 char *name = packmsg_get_str_dup(&in2);
759 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
761 packmsg_input_invalidate(&in);
765 if(!check_id(name)) {
770 if(!strcmp(name, mesh->name)) {
771 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
773 meshlink_errno = MESHLINK_EPEER;
777 node_t *n = new_node();
780 config_t config = {data, len};
782 if(!node_read_from_config(mesh, n, &config)) {
784 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
785 meshlink_errno = MESHLINK_EPEER;
790 /* The first host config file is of the inviter itself;
791 * remember the address we are currently using for the invitation connection.
794 socklen_t salen = sizeof(sa);
796 if(getpeername(state->sock, &sa.sa, &salen) == 0) {
797 node_add_recent_address(mesh, n, &sa);
801 /* Clear the reachability times, since we ourself have never seen these nodes yet */
802 n->last_reachable = 0;
803 n->last_unreachable = 0;
805 if(!node_write_config(mesh, n)) {
813 /* Ensure the configuration directory metadata is on disk */
814 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
818 if(!mesh->inviter_commits_first) {
819 devtool_set_inviter_commits_first(false);
822 sptps_send_record(&state->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
824 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
829 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
831 join_state_t *state = handle;
832 const char *ptr = data;
835 int result = send(state->sock, ptr, len, 0);
837 if(result == -1 && errno == EINTR) {
839 } else if(result <= 0) {
850 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
851 join_state_t *state = handle;
852 meshlink_handle_t *mesh = state->mesh;
854 if(mesh->inviter_commits_first) {
856 case SPTPS_HANDSHAKE:
857 return sptps_send_record(&state->sptps, 2, state->cookie, 18 + 32);
863 if(!finalize_join(state, msg, len)) {
867 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
868 shutdown(state->sock, SHUT_RDWR);
869 state->success = true;
877 case SPTPS_HANDSHAKE:
878 return sptps_send_record(&state->sptps, 0, state->cookie, 18);
881 return finalize_join(state, msg, len);
884 logger(mesh, MESHLINK_DEBUG, "Invitation successfully accepted.\n");
885 shutdown(state->sock, SHUT_RDWR);
886 state->success = true;
897 static bool recvline(join_state_t *state) {
898 char *newline = NULL;
900 while(!(newline = memchr(state->buffer, '\n', state->blen))) {
901 int result = recv(state->sock, state->buffer + state->blen, sizeof(state)->buffer - state->blen, 0);
903 if(result == -1 && errno == EINTR) {
905 } else if(result <= 0) {
909 state->blen += result;
912 if((size_t)(newline - state->buffer) >= sizeof(state->line)) {
916 size_t len = newline - state->buffer;
918 memcpy(state->line, state->buffer, len);
919 state->line[len] = 0;
920 memmove(state->buffer, newline + 1, state->blen - len - 1);
921 state->blen -= len + 1;
926 static bool sendline(int fd, char *format, ...) {
932 va_start(ap, format);
933 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
936 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
944 int result = send(fd, p, blen, MSG_NOSIGNAL);
946 if(result == -1 && errno == EINTR) {
948 } else if(result <= 0) {
959 static const char *errstr[] = {
960 [MESHLINK_OK] = "No error",
961 [MESHLINK_EINVAL] = "Invalid argument",
962 [MESHLINK_ENOMEM] = "Out of memory",
963 [MESHLINK_ENOENT] = "No such node",
964 [MESHLINK_EEXIST] = "Node already exists",
965 [MESHLINK_EINTERNAL] = "Internal error",
966 [MESHLINK_ERESOLV] = "Could not resolve hostname",
967 [MESHLINK_ESTORAGE] = "Storage error",
968 [MESHLINK_ENETWORK] = "Network error",
969 [MESHLINK_EPEER] = "Error communicating with peer",
970 [MESHLINK_ENOTSUP] = "Operation not supported",
971 [MESHLINK_EBUSY] = "MeshLink instance already in use",
972 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
975 const char *meshlink_strerror(meshlink_errno_t err) {
976 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
977 return "Invalid error code";
983 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
984 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
986 mesh->private_key = ecdsa_generate();
987 mesh->invitation_key = ecdsa_generate();
989 if(!mesh->private_key || !mesh->invitation_key) {
990 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
991 meshlink_errno = MESHLINK_EINTERNAL;
995 logger(mesh, MESHLINK_DEBUG, "Done.\n");
1000 static bool timespec_lt(const struct timespec *a, const struct timespec *b) {
1001 if(a->tv_sec == b->tv_sec) {
1002 return a->tv_nsec < b->tv_nsec;
1004 return a->tv_sec < b->tv_sec;
1008 static struct timespec idle(event_loop_t *loop, void *data) {
1010 meshlink_handle_t *mesh = data;
1011 struct timespec t, tmin = {3600, 0};
1013 for splay_each(node_t, n, mesh->nodes) {
1018 t = utcp_timeout(n->utcp);
1020 if(timespec_lt(&t, &tmin)) {
1028 // Get our local address(es) by simulating connecting to an Internet host.
1029 static void add_local_addresses(meshlink_handle_t *mesh) {
1031 sa.storage.ss_family = AF_UNKNOWN;
1032 socklen_t salen = sizeof(sa);
1036 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
1037 sa.in.sin_port = ntohs(atoi(mesh->myport));
1038 node_add_recent_address(mesh, mesh->self, &sa);
1045 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
1046 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
1047 node_add_recent_address(mesh, mesh->self, &sa);
1051 static bool meshlink_setup(meshlink_handle_t *mesh) {
1052 if(!config_destroy(mesh->confbase, "new")) {
1053 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
1054 meshlink_errno = MESHLINK_ESTORAGE;
1058 if(!config_destroy(mesh->confbase, "old")) {
1059 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1060 meshlink_errno = MESHLINK_ESTORAGE;
1064 if(!config_init(mesh, "current")) {
1065 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
1066 meshlink_errno = MESHLINK_ESTORAGE;
1070 if(!ecdsa_keygen(mesh)) {
1071 meshlink_errno = MESHLINK_EINTERNAL;
1075 if(check_port(mesh) == 0) {
1076 meshlink_errno = MESHLINK_ENETWORK;
1080 /* Create a node for ourself */
1082 mesh->self = new_node();
1083 mesh->self->name = xstrdup(mesh->name);
1084 mesh->self->devclass = mesh->devclass;
1085 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
1086 mesh->self->session_id = mesh->session_id;
1088 if(!write_main_config_files(mesh)) {
1089 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
1090 meshlink_errno = MESHLINK_ESTORAGE;
1094 /* Ensure the configuration directory metadata is on disk */
1095 if(!config_sync(mesh, "current")) {
1102 static bool meshlink_read_config(meshlink_handle_t *mesh) {
1105 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
1106 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
1110 packmsg_input_t in = {config.buf, config.len};
1111 const void *private_key;
1112 const void *invitation_key;
1114 uint32_t version = packmsg_get_uint32(&in);
1115 char *name = packmsg_get_str_dup(&in);
1116 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
1117 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
1118 uint16_t myport = packmsg_get_uint16(&in);
1120 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
1121 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
1123 config_free(&config);
1129 // TODO: check this?
1130 if(mesh->name && strcmp(mesh->name, name)) {
1131 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
1132 meshlink_errno = MESHLINK_ESTORAGE;
1134 config_free(&config);
1142 xasprintf(&mesh->myport, "%u", myport);
1143 mesh->private_key = ecdsa_set_private_key(private_key);
1144 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
1145 config_free(&config);
1147 /* Create a node for ourself and read our host configuration file */
1149 mesh->self = new_node();
1150 mesh->self->name = xstrdup(name);
1151 mesh->self->devclass = mesh->devclass;
1152 mesh->self->session_id = mesh->session_id;
1154 if(!node_read_public_key(mesh, mesh->self)) {
1155 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
1156 meshlink_errno = MESHLINK_ESTORAGE;
1157 free_node(mesh->self);
1166 static void *setup_network_in_netns_thread(void *arg) {
1167 meshlink_handle_t *mesh = arg;
1169 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1173 bool success = setup_network(mesh);
1174 return success ? arg : NULL;
1176 #endif // HAVE_SETNS
1178 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1179 if(!confbase || !*confbase) {
1180 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1181 meshlink_errno = MESHLINK_EINVAL;
1185 if(!appname || !*appname) {
1186 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1187 meshlink_errno = MESHLINK_EINVAL;
1191 if(strchr(appname, ' ')) {
1192 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1193 meshlink_errno = MESHLINK_EINVAL;
1197 if(!name || !*name) {
1198 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1199 meshlink_errno = MESHLINK_EINVAL;
1203 if(!check_id(name)) {
1204 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1205 meshlink_errno = MESHLINK_EINVAL;
1209 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1210 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1211 meshlink_errno = MESHLINK_EINVAL;
1215 meshlink_open_params_t *params = xzalloc(sizeof * params);
1217 params->confbase = xstrdup(confbase);
1218 params->name = xstrdup(name);
1219 params->appname = xstrdup(appname);
1220 params->devclass = devclass;
1226 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1228 meshlink_errno = MESHLINK_EINVAL;
1232 params->netns = netns;
1237 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1239 meshlink_errno = MESHLINK_EINVAL;
1243 if((!key && keylen) || (key && !keylen)) {
1244 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1245 meshlink_errno = MESHLINK_EINVAL;
1250 params->keylen = keylen;
1255 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1256 if(!mesh || !new_key || !new_keylen) {
1257 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1258 meshlink_errno = MESHLINK_EINVAL;
1262 pthread_mutex_lock(&mesh->mutex);
1264 // Create hash for the new key
1265 void *new_config_key;
1266 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1268 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1269 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1270 meshlink_errno = MESHLINK_EINTERNAL;
1271 pthread_mutex_unlock(&mesh->mutex);
1275 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1277 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1278 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1279 meshlink_errno = MESHLINK_ESTORAGE;
1280 pthread_mutex_unlock(&mesh->mutex);
1284 devtool_keyrotate_probe(1);
1286 // Rename confbase/current/ to confbase/old
1288 if(!config_rename(mesh, "current", "old")) {
1289 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1290 meshlink_errno = MESHLINK_ESTORAGE;
1291 pthread_mutex_unlock(&mesh->mutex);
1295 devtool_keyrotate_probe(2);
1297 // Rename confbase/new/ to confbase/current
1299 if(!config_rename(mesh, "new", "current")) {
1300 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1301 meshlink_errno = MESHLINK_ESTORAGE;
1302 pthread_mutex_unlock(&mesh->mutex);
1306 devtool_keyrotate_probe(3);
1308 // Cleanup the "old" confbase sub-directory
1310 if(!config_destroy(mesh->confbase, "old")) {
1311 pthread_mutex_unlock(&mesh->mutex);
1315 // Change the mesh handle key with new key
1317 free(mesh->config_key);
1318 mesh->config_key = new_config_key;
1320 pthread_mutex_unlock(&mesh->mutex);
1325 void meshlink_open_params_free(meshlink_open_params_t *params) {
1327 meshlink_errno = MESHLINK_EINVAL;
1331 free(params->confbase);
1333 free(params->appname);
1338 /// Device class traits
1339 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1340 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1341 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1342 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1343 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1346 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1347 if(!confbase || !*confbase) {
1348 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1349 meshlink_errno = MESHLINK_EINVAL;
1353 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1354 meshlink_open_params_t params;
1355 memset(¶ms, 0, sizeof(params));
1357 params.confbase = (char *)confbase;
1358 params.name = (char *)name;
1359 params.appname = (char *)appname;
1360 params.devclass = devclass;
1363 return meshlink_open_ex(¶ms);
1366 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) {
1367 if(!confbase || !*confbase) {
1368 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1369 meshlink_errno = MESHLINK_EINVAL;
1373 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1374 meshlink_open_params_t params;
1375 memset(¶ms, 0, sizeof(params));
1377 params.confbase = (char *)confbase;
1378 params.name = (char *)name;
1379 params.appname = (char *)appname;
1380 params.devclass = devclass;
1383 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1387 return meshlink_open_ex(¶ms);
1390 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1391 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1392 meshlink_open_params_t params;
1393 memset(¶ms, 0, sizeof(params));
1395 params.name = (char *)name;
1396 params.appname = (char *)appname;
1397 params.devclass = devclass;
1400 return meshlink_open_ex(¶ms);
1403 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1404 // Validate arguments provided by the application
1405 bool usingname = false;
1407 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1409 if(!params->appname || !*params->appname) {
1410 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1411 meshlink_errno = MESHLINK_EINVAL;
1415 if(strchr(params->appname, ' ')) {
1416 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1417 meshlink_errno = MESHLINK_EINVAL;
1421 if(!params->name || !*params->name) {
1422 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1424 } else { //check name only if there is a name != NULL
1426 if(!check_id(params->name)) {
1427 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1428 meshlink_errno = MESHLINK_EINVAL;
1435 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1436 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1437 meshlink_errno = MESHLINK_EINVAL;
1441 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1442 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1443 meshlink_errno = MESHLINK_EINVAL;
1447 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1449 if(params->confbase) {
1450 mesh->confbase = xstrdup(params->confbase);
1453 mesh->appname = xstrdup(params->appname);
1454 mesh->devclass = params->devclass;
1455 mesh->discovery = true;
1456 mesh->invitation_timeout = 604800; // 1 week
1457 mesh->netns = params->netns;
1458 mesh->submeshes = NULL;
1459 mesh->log_cb = global_log_cb;
1460 mesh->log_level = global_log_level;
1461 mesh->packet = xmalloc(sizeof(vpn_packet_t));
1463 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1466 randomize(&mesh->session_id, sizeof(mesh->session_id));
1467 } while(mesh->session_id == 0);
1469 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1472 mesh->name = xstrdup(params->name);
1477 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1479 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1480 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1481 meshlink_close(mesh);
1482 meshlink_errno = MESHLINK_EINTERNAL;
1488 pthread_mutexattr_t attr;
1489 pthread_mutexattr_init(&attr);
1490 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1491 pthread_mutex_init(&mesh->mutex, &attr);
1493 mesh->threadstarted = false;
1494 event_loop_init(&mesh->loop);
1495 mesh->loop.data = mesh;
1497 meshlink_queue_init(&mesh->outpacketqueue);
1499 // Atomically lock the configuration directory.
1500 if(!main_config_lock(mesh)) {
1501 meshlink_close(mesh);
1505 // If no configuration exists yet, create it.
1507 if(!meshlink_confbase_exists(mesh)) {
1508 if(!meshlink_setup(mesh)) {
1509 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1510 meshlink_close(mesh);
1514 if(!meshlink_read_config(mesh)) {
1515 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1516 meshlink_close(mesh);
1522 struct WSAData wsa_state;
1523 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1526 // Setup up everything
1527 // TODO: we should not open listening sockets yet
1529 bool success = false;
1531 if(mesh->netns != -1) {
1535 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1536 void *retval = NULL;
1537 success = pthread_join(thr, &retval) == 0 && retval;
1541 meshlink_errno = MESHLINK_EINTERNAL;
1544 #endif // HAVE_SETNS
1546 success = setup_network(mesh);
1550 meshlink_close(mesh);
1551 meshlink_errno = MESHLINK_ENETWORK;
1555 add_local_addresses(mesh);
1557 if(!node_write_config(mesh, mesh->self)) {
1558 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1562 idle_set(&mesh->loop, idle, mesh);
1564 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1568 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1569 meshlink_submesh_t *s = NULL;
1572 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1573 meshlink_errno = MESHLINK_EINVAL;
1577 if(!submesh || !*submesh) {
1578 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1579 meshlink_errno = MESHLINK_EINVAL;
1584 pthread_mutex_lock(&mesh->mutex);
1586 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1588 pthread_mutex_unlock(&mesh->mutex);
1593 static void *meshlink_main_loop(void *arg) {
1594 meshlink_handle_t *mesh = arg;
1596 if(mesh->netns != -1) {
1599 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1600 pthread_cond_signal(&mesh->cond);
1605 pthread_cond_signal(&mesh->cond);
1607 #endif // HAVE_SETNS
1612 if(mesh->discovery) {
1613 discovery_start(mesh);
1618 pthread_mutex_lock(&mesh->mutex);
1620 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1621 pthread_cond_broadcast(&mesh->cond);
1623 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1625 pthread_mutex_unlock(&mesh->mutex);
1630 if(mesh->discovery) {
1631 discovery_stop(mesh);
1639 bool meshlink_start(meshlink_handle_t *mesh) {
1641 meshlink_errno = MESHLINK_EINVAL;
1645 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1647 pthread_mutex_lock(&mesh->mutex);
1650 assert(mesh->private_key);
1651 assert(mesh->self->ecdsa);
1652 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1654 if(mesh->threadstarted) {
1655 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1656 pthread_mutex_unlock(&mesh->mutex);
1660 if(mesh->listen_socket[0].tcp.fd < 0) {
1661 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1662 meshlink_errno = MESHLINK_ENETWORK;
1666 // TODO: open listening sockets first
1668 //Check that a valid name is set
1670 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1671 meshlink_errno = MESHLINK_EINVAL;
1672 pthread_mutex_unlock(&mesh->mutex);
1676 init_outgoings(mesh);
1679 // Start the main thread
1681 event_loop_start(&mesh->loop);
1683 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1684 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1685 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1686 meshlink_errno = MESHLINK_EINTERNAL;
1687 event_loop_stop(&mesh->loop);
1688 pthread_mutex_unlock(&mesh->mutex);
1692 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1693 mesh->threadstarted = true;
1695 // Ensure we are considered reachable
1698 pthread_mutex_unlock(&mesh->mutex);
1702 void meshlink_stop(meshlink_handle_t *mesh) {
1704 meshlink_errno = MESHLINK_EINVAL;
1708 pthread_mutex_lock(&mesh->mutex);
1709 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1711 // Shut down the main thread
1712 event_loop_stop(&mesh->loop);
1714 // Send ourselves a UDP packet to kick the event loop
1715 for(int i = 0; i < mesh->listen_sockets; i++) {
1717 socklen_t salen = sizeof(sa);
1719 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1720 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1724 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1725 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1729 if(mesh->threadstarted) {
1730 // Wait for the main thread to finish
1731 pthread_mutex_unlock(&mesh->mutex);
1732 pthread_join(mesh->thread, NULL);
1733 pthread_mutex_lock(&mesh->mutex);
1735 mesh->threadstarted = false;
1738 // Close all metaconnections
1739 if(mesh->connections) {
1740 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1742 connection_t *c = node->data;
1744 terminate_connection(mesh, c, false);
1749 exit_outgoings(mesh);
1751 // Ensure we are considered unreachable
1756 // Try to write out any changed node config files, ignore errors at this point.
1758 for splay_each(node_t, n, mesh->nodes) {
1759 if(n->status.dirty) {
1760 n->status.dirty = !node_write_config(mesh, n);
1765 pthread_mutex_unlock(&mesh->mutex);
1768 void meshlink_close(meshlink_handle_t *mesh) {
1770 meshlink_errno = MESHLINK_EINVAL;
1774 // stop can be called even if mesh has not been started
1775 meshlink_stop(mesh);
1777 // lock is not released after this
1778 pthread_mutex_lock(&mesh->mutex);
1780 // Close and free all resources used.
1782 close_network_connections(mesh);
1784 logger(mesh, MESHLINK_INFO, "Terminating");
1786 event_loop_exit(&mesh->loop);
1790 if(mesh->confbase) {
1796 ecdsa_free(mesh->invitation_key);
1798 if(mesh->netns != -1) {
1802 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1806 meshlink_queue_exit(&mesh->outpacketqueue);
1809 free(mesh->appname);
1810 free(mesh->confbase);
1811 free(mesh->config_key);
1812 free(mesh->external_address_url);
1814 ecdsa_free(mesh->private_key);
1816 if(mesh->invitation_addresses) {
1817 list_delete_list(mesh->invitation_addresses);
1820 main_config_unlock(mesh);
1822 pthread_mutex_unlock(&mesh->mutex);
1823 pthread_mutex_destroy(&mesh->mutex);
1825 memset(mesh, 0, sizeof(*mesh));
1830 bool meshlink_destroy(const char *confbase) {
1832 meshlink_errno = MESHLINK_EINVAL;
1836 /* Exit early if the confbase directory itself doesn't exist */
1837 if(access(confbase, F_OK) && errno == ENOENT) {
1841 /* Take the lock the same way meshlink_open() would. */
1842 char lockfilename[PATH_MAX];
1843 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1845 FILE *lockfile = fopen(lockfilename, "w+");
1848 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1849 meshlink_errno = MESHLINK_ESTORAGE;
1854 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1858 // TODO: use _locking()?
1861 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1862 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1864 meshlink_errno = MESHLINK_EBUSY;
1870 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1871 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1875 if(unlink(lockfilename)) {
1876 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1878 meshlink_errno = MESHLINK_ESTORAGE;
1884 if(!sync_path(confbase)) {
1885 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1886 meshlink_errno = MESHLINK_ESTORAGE;
1893 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1895 meshlink_errno = MESHLINK_EINVAL;
1899 pthread_mutex_lock(&mesh->mutex);
1900 mesh->receive_cb = cb;
1901 pthread_mutex_unlock(&mesh->mutex);
1904 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1906 meshlink_errno = MESHLINK_EINVAL;
1910 pthread_mutex_lock(&mesh->mutex);
1911 mesh->connection_try_cb = cb;
1912 pthread_mutex_unlock(&mesh->mutex);
1915 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1917 meshlink_errno = MESHLINK_EINVAL;
1921 pthread_mutex_lock(&mesh->mutex);
1922 mesh->node_status_cb = cb;
1923 pthread_mutex_unlock(&mesh->mutex);
1926 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1928 meshlink_errno = MESHLINK_EINVAL;
1932 pthread_mutex_lock(&mesh->mutex);
1933 mesh->node_pmtu_cb = cb;
1934 pthread_mutex_unlock(&mesh->mutex);
1937 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1939 meshlink_errno = MESHLINK_EINVAL;
1943 pthread_mutex_lock(&mesh->mutex);
1944 mesh->node_duplicate_cb = cb;
1945 pthread_mutex_unlock(&mesh->mutex);
1948 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1950 pthread_mutex_lock(&mesh->mutex);
1952 mesh->log_level = cb ? level : 0;
1953 pthread_mutex_unlock(&mesh->mutex);
1956 global_log_level = cb ? level : 0;
1960 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1962 meshlink_errno = MESHLINK_EINVAL;
1966 pthread_mutex_lock(&mesh->mutex);
1967 mesh->error_cb = cb;
1968 pthread_mutex_unlock(&mesh->mutex);
1971 static bool prepare_packet(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len, vpn_packet_t *packet) {
1972 meshlink_packethdr_t *hdr;
1974 if(len >= MAXSIZE - sizeof(*hdr)) {
1975 meshlink_errno = MESHLINK_EINVAL;
1979 node_t *n = (node_t *)destination;
1981 if(n->status.blacklisted) {
1982 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1983 meshlink_errno = MESHLINK_EBLACKLISTED;
1987 // Prepare the packet
1988 packet->probe = false;
1989 packet->tcp = false;
1990 packet->len = len + sizeof(*hdr);
1992 hdr = (meshlink_packethdr_t *)packet->data;
1993 memset(hdr, 0, sizeof(*hdr));
1994 // leave the last byte as 0 to make sure strings are always
1995 // null-terminated if they are longer than the buffer
1996 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1997 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1999 memcpy(packet->data + sizeof(*hdr), data, len);
2004 static bool meshlink_send_immediate(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2006 assert(destination);
2010 // Prepare the packet
2011 if(!prepare_packet(mesh, destination, data, len, mesh->packet)) {
2015 // Send it immediately
2016 route(mesh, mesh->self, mesh->packet);
2021 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
2022 // Validate arguments
2023 if(!mesh || !destination) {
2024 meshlink_errno = MESHLINK_EINVAL;
2033 meshlink_errno = MESHLINK_EINVAL;
2037 // Prepare the packet
2038 vpn_packet_t *packet = malloc(sizeof(*packet));
2041 meshlink_errno = MESHLINK_ENOMEM;
2045 if(!prepare_packet(mesh, destination, data, len, packet)) {
2050 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
2052 meshlink_errno = MESHLINK_ENOMEM;
2056 logger(mesh, MESHLINK_DEBUG, "Adding packet of %zu bytes to packet queue", len);
2058 // Notify event loop
2059 signal_trigger(&mesh->loop, &mesh->datafromapp);
2064 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
2066 meshlink_handle_t *mesh = data;
2068 logger(mesh, MESHLINK_DEBUG, "Flushing the packet queue");
2070 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
2071 logger(mesh, MESHLINK_DEBUG, "Removing packet of %d bytes from packet queue", packet->len);
2072 mesh->self->in_packets++;
2073 mesh->self->in_bytes += packet->len;
2074 route(mesh, mesh->self, packet);
2079 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
2080 if(!mesh || !destination) {
2081 meshlink_errno = MESHLINK_EINVAL;
2085 pthread_mutex_lock(&mesh->mutex);
2087 node_t *n = (node_t *)destination;
2089 if(!n->status.reachable) {
2090 pthread_mutex_unlock(&mesh->mutex);
2093 } else if(n->mtuprobes > 30 && n->minmtu) {
2094 pthread_mutex_unlock(&mesh->mutex);
2097 pthread_mutex_unlock(&mesh->mutex);
2102 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
2103 if(!mesh || !node) {
2104 meshlink_errno = MESHLINK_EINVAL;
2108 pthread_mutex_lock(&mesh->mutex);
2110 node_t *n = (node_t *)node;
2112 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
2113 meshlink_errno = MESHLINK_EINTERNAL;
2114 pthread_mutex_unlock(&mesh->mutex);
2118 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
2121 meshlink_errno = MESHLINK_EINTERNAL;
2124 pthread_mutex_unlock(&mesh->mutex);
2128 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
2130 meshlink_errno = MESHLINK_EINVAL;
2134 return (meshlink_node_t *)mesh->self;
2137 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
2138 if(!mesh || !name) {
2139 meshlink_errno = MESHLINK_EINVAL;
2145 pthread_mutex_lock(&mesh->mutex);
2146 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
2147 pthread_mutex_unlock(&mesh->mutex);
2150 meshlink_errno = MESHLINK_ENOENT;
2153 return (meshlink_node_t *)n;
2156 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
2157 if(!mesh || !name) {
2158 meshlink_errno = MESHLINK_EINVAL;
2162 meshlink_submesh_t *submesh = NULL;
2164 pthread_mutex_lock(&mesh->mutex);
2165 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
2166 pthread_mutex_unlock(&mesh->mutex);
2169 meshlink_errno = MESHLINK_ENOENT;
2175 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
2176 if(!mesh || !nmemb || (*nmemb && !nodes)) {
2177 meshlink_errno = MESHLINK_EINVAL;
2181 meshlink_node_t **result;
2184 pthread_mutex_lock(&mesh->mutex);
2186 *nmemb = mesh->nodes->count;
2187 result = realloc(nodes, *nmemb * sizeof(*nodes));
2190 meshlink_node_t **p = result;
2192 for splay_each(node_t, n, mesh->nodes) {
2193 *p++ = (meshlink_node_t *)n;
2198 meshlink_errno = MESHLINK_ENOMEM;
2201 pthread_mutex_unlock(&mesh->mutex);
2206 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) {
2207 meshlink_node_t **result;
2209 pthread_mutex_lock(&mesh->mutex);
2213 for splay_each(node_t, n, mesh->nodes) {
2214 if(search_node(n, condition)) {
2221 pthread_mutex_unlock(&mesh->mutex);
2225 result = realloc(nodes, *nmemb * sizeof(*nodes));
2228 meshlink_node_t **p = result;
2230 for splay_each(node_t, n, mesh->nodes) {
2231 if(search_node(n, condition)) {
2232 *p++ = (meshlink_node_t *)n;
2238 meshlink_errno = MESHLINK_ENOMEM;
2241 pthread_mutex_unlock(&mesh->mutex);
2246 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2247 dev_class_t *devclass = (dev_class_t *)condition;
2249 if(*devclass == (dev_class_t)node->devclass) {
2256 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2257 if(condition == node->submesh) {
2269 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2270 const struct time_range *range = condition;
2271 time_t start = node->last_reachable;
2272 time_t end = node->last_unreachable;
2282 if(range->end >= range->start) {
2283 return start <= range->end && end >= range->start;
2285 return start > range->start || end < range->end;
2289 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) {
2290 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2291 meshlink_errno = MESHLINK_EINVAL;
2295 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2298 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2299 if(!mesh || !submesh || !nmemb) {
2300 meshlink_errno = MESHLINK_EINVAL;
2304 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2307 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) {
2308 if(!mesh || !nmemb) {
2309 meshlink_errno = MESHLINK_EINVAL;
2313 struct time_range range = {start, end};
2315 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2318 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2319 if(!mesh || !node) {
2320 meshlink_errno = MESHLINK_EINVAL;
2324 dev_class_t devclass;
2326 pthread_mutex_lock(&mesh->mutex);
2328 devclass = ((node_t *)node)->devclass;
2330 pthread_mutex_unlock(&mesh->mutex);
2335 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2336 if(!mesh || !node) {
2337 meshlink_errno = MESHLINK_EINVAL;
2341 node_t *n = (node_t *)node;
2343 meshlink_submesh_t *s;
2345 s = (meshlink_submesh_t *)n->submesh;
2350 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2351 if(!mesh || !node) {
2352 meshlink_errno = MESHLINK_EINVAL;
2356 node_t *n = (node_t *)node;
2359 pthread_mutex_lock(&mesh->mutex);
2360 reachable = n->status.reachable && !n->status.blacklisted;
2362 if(last_reachable) {
2363 *last_reachable = n->last_reachable;
2366 if(last_unreachable) {
2367 *last_unreachable = n->last_unreachable;
2370 pthread_mutex_unlock(&mesh->mutex);
2375 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2376 if(!mesh || !data || !len || !signature || !siglen) {
2377 meshlink_errno = MESHLINK_EINVAL;
2381 if(*siglen < MESHLINK_SIGLEN) {
2382 meshlink_errno = MESHLINK_EINVAL;
2386 pthread_mutex_lock(&mesh->mutex);
2388 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2389 meshlink_errno = MESHLINK_EINTERNAL;
2390 pthread_mutex_unlock(&mesh->mutex);
2394 *siglen = MESHLINK_SIGLEN;
2395 pthread_mutex_unlock(&mesh->mutex);
2399 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2400 if(!mesh || !source || !data || !len || !signature) {
2401 meshlink_errno = MESHLINK_EINVAL;
2405 if(siglen != MESHLINK_SIGLEN) {
2406 meshlink_errno = MESHLINK_EINVAL;
2410 pthread_mutex_lock(&mesh->mutex);
2414 struct node_t *n = (struct node_t *)source;
2416 if(!node_read_public_key(mesh, n)) {
2417 meshlink_errno = MESHLINK_EINTERNAL;
2420 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2423 pthread_mutex_unlock(&mesh->mutex);
2427 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2428 pthread_mutex_lock(&mesh->mutex);
2430 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2433 // TODO: Update invitation key if necessary?
2436 pthread_mutex_unlock(&mesh->mutex);
2438 return mesh->invitation_key;
2441 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2442 if(!mesh || !node || !address) {
2443 meshlink_errno = MESHLINK_EINVAL;
2447 if(!is_valid_hostname(address)) {
2448 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2449 meshlink_errno = MESHLINK_EINVAL;
2453 if(port && !is_valid_port(port)) {
2454 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2455 meshlink_errno = MESHLINK_EINVAL;
2459 char *canonical_address;
2462 xasprintf(&canonical_address, "%s %s", address, port);
2464 canonical_address = xstrdup(address);
2467 pthread_mutex_lock(&mesh->mutex);
2469 node_t *n = (node_t *)node;
2470 free(n->canonical_address);
2471 n->canonical_address = canonical_address;
2473 if(!node_write_config(mesh, n)) {
2474 pthread_mutex_unlock(&mesh->mutex);
2478 pthread_mutex_unlock(&mesh->mutex);
2480 return config_sync(mesh, "current");
2483 bool meshlink_add_invitation_address(struct meshlink_handle *mesh, const char *address, const char *port) {
2484 if(!mesh || !address) {
2485 meshlink_errno = MESHLINK_EINVAL;
2489 if(!is_valid_hostname(address)) {
2490 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2491 meshlink_errno = MESHLINK_EINVAL;
2495 if(port && !is_valid_port(port)) {
2496 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2497 meshlink_errno = MESHLINK_EINVAL;
2504 xasprintf(&combo, "%s/%s", address, port);
2506 combo = xstrdup(address);
2509 pthread_mutex_lock(&mesh->mutex);
2511 if(!mesh->invitation_addresses) {
2512 mesh->invitation_addresses = list_alloc((list_action_t)free);
2515 list_insert_tail(mesh->invitation_addresses, combo);
2516 pthread_mutex_unlock(&mesh->mutex);
2521 void meshlink_clear_invitation_addresses(struct meshlink_handle *mesh) {
2523 meshlink_errno = MESHLINK_EINVAL;
2527 pthread_mutex_lock(&mesh->mutex);
2529 if(mesh->invitation_addresses) {
2530 list_delete_list(mesh->invitation_addresses);
2531 mesh->invitation_addresses = NULL;
2534 pthread_mutex_unlock(&mesh->mutex);
2537 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2538 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2541 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2543 meshlink_errno = MESHLINK_EINVAL;
2547 char *address = meshlink_get_external_address(mesh);
2553 bool rval = meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2559 int meshlink_get_port(meshlink_handle_t *mesh) {
2561 meshlink_errno = MESHLINK_EINVAL;
2566 meshlink_errno = MESHLINK_EINTERNAL;
2572 pthread_mutex_lock(&mesh->mutex);
2573 port = atoi(mesh->myport);
2574 pthread_mutex_unlock(&mesh->mutex);
2579 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2580 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2581 meshlink_errno = MESHLINK_EINVAL;
2585 if(mesh->myport && port == atoi(mesh->myport)) {
2589 if(!try_bind(mesh, port)) {
2590 meshlink_errno = MESHLINK_ENETWORK;
2594 devtool_trybind_probe();
2598 pthread_mutex_lock(&mesh->mutex);
2600 if(mesh->threadstarted) {
2601 meshlink_errno = MESHLINK_EINVAL;
2606 xasprintf(&mesh->myport, "%d", port);
2608 /* Close down the network. This also deletes mesh->self. */
2609 close_network_connections(mesh);
2611 /* Recreate mesh->self. */
2612 mesh->self = new_node();
2613 mesh->self->name = xstrdup(mesh->name);
2614 mesh->self->devclass = mesh->devclass;
2615 mesh->self->session_id = mesh->session_id;
2616 xasprintf(&mesh->myport, "%d", port);
2618 if(!node_read_public_key(mesh, mesh->self)) {
2619 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2620 meshlink_errno = MESHLINK_ESTORAGE;
2621 free_node(mesh->self);
2624 } else if(!setup_network(mesh)) {
2625 meshlink_errno = MESHLINK_ENETWORK;
2629 /* Rebuild our own list of recent addresses */
2630 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2631 add_local_addresses(mesh);
2633 /* Write meshlink.conf with the updated port number */
2634 write_main_config_files(mesh);
2636 rval = config_sync(mesh, "current");
2639 pthread_mutex_unlock(&mesh->mutex);
2641 return rval && meshlink_get_port(mesh) == port;
2644 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2645 mesh->invitation_timeout = timeout;
2648 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2649 meshlink_submesh_t *s = NULL;
2652 meshlink_errno = MESHLINK_EINVAL;
2657 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2660 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2661 meshlink_errno = MESHLINK_EINVAL;
2665 s = (meshlink_submesh_t *)mesh->self->submesh;
2668 pthread_mutex_lock(&mesh->mutex);
2670 // Check validity of the new node's name
2671 if(!check_id(name)) {
2672 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2673 meshlink_errno = MESHLINK_EINVAL;
2674 pthread_mutex_unlock(&mesh->mutex);
2678 // Ensure no host configuration file with that name exists
2679 if(config_exists(mesh, "current", name)) {
2680 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2681 meshlink_errno = MESHLINK_EEXIST;
2682 pthread_mutex_unlock(&mesh->mutex);
2686 // Ensure no other nodes know about this name
2687 if(lookup_node(mesh, name)) {
2688 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2689 meshlink_errno = MESHLINK_EEXIST;
2690 pthread_mutex_unlock(&mesh->mutex);
2694 // Get the local address
2695 char *address = get_my_hostname(mesh, flags);
2698 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2699 meshlink_errno = MESHLINK_ERESOLV;
2700 pthread_mutex_unlock(&mesh->mutex);
2704 if(!refresh_invitation_key(mesh)) {
2705 meshlink_errno = MESHLINK_EINTERNAL;
2706 pthread_mutex_unlock(&mesh->mutex);
2710 // If we changed our own host config file, write it out now
2711 if(mesh->self->status.dirty) {
2712 if(!node_write_config(mesh, mesh->self)) {
2713 logger(mesh, MESHLINK_ERROR, "Could not write our own host config file!\n");
2714 pthread_mutex_unlock(&mesh->mutex);
2721 // Create a hash of the key.
2722 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2723 sha512(fingerprint, strlen(fingerprint), hash);
2724 b64encode_urlsafe(hash, hash, 18);
2726 // Create a random cookie for this invitation.
2728 randomize(cookie, 18);
2730 // Create a filename that doesn't reveal the cookie itself
2731 char buf[18 + strlen(fingerprint)];
2732 char cookiehash[64];
2733 memcpy(buf, cookie, 18);
2734 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2735 sha512(buf, sizeof(buf), cookiehash);
2736 b64encode_urlsafe(cookiehash, cookiehash, 18);
2738 b64encode_urlsafe(cookie, cookie, 18);
2742 /* Construct the invitation file */
2743 uint8_t outbuf[4096];
2744 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2746 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2747 packmsg_add_str(&inv, name);
2748 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2749 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2751 /* TODO: Add several host config files to bootstrap connections.
2752 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2753 * and are not blacklisted.
2755 config_t configs[5];
2756 memset(configs, 0, sizeof(configs));
2759 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2763 /* Append host config files to the invitation file */
2764 packmsg_add_array(&inv, count);
2766 for(int i = 0; i < count; i++) {
2767 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2768 config_free(&configs[i]);
2771 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2773 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2774 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2775 meshlink_errno = MESHLINK_ESTORAGE;
2776 pthread_mutex_unlock(&mesh->mutex);
2780 // Create an URL from the local address, key hash and cookie
2782 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2785 pthread_mutex_unlock(&mesh->mutex);
2789 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2790 return meshlink_invite_ex(mesh, submesh, name, 0);
2793 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2794 if(!mesh || !invitation) {
2795 meshlink_errno = MESHLINK_EINVAL;
2799 join_state_t state = {
2804 ecdsa_t *key = NULL;
2805 ecdsa_t *hiskey = NULL;
2807 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2808 char copy[strlen(invitation) + 1];
2810 pthread_mutex_lock(&mesh->mutex);
2812 //Before doing meshlink_join make sure we are not connected to another mesh
2813 if(mesh->threadstarted) {
2814 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2815 meshlink_errno = MESHLINK_EINVAL;
2819 // 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.
2820 if(mesh->nodes->count > 1) {
2821 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2822 meshlink_errno = MESHLINK_EINVAL;
2826 strcpy(copy, invitation);
2828 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2830 char *slash = strchr(copy, '/');
2838 if(strlen(slash) != 48) {
2842 char *address = copy;
2845 if(!b64decode(slash, state.hash, 18) || !b64decode(slash + 24, state.cookie, 18)) {
2849 if(mesh->inviter_commits_first) {
2850 memcpy(state.cookie + 18, ecdsa_get_public_key(mesh->private_key), 32);
2853 // Generate a throw-away key for the invitation.
2854 key = ecdsa_generate();
2857 meshlink_errno = MESHLINK_EINTERNAL;
2861 char *b64key = ecdsa_get_base64_public_key(key);
2864 while(address && *address) {
2865 // We allow commas in the address part to support multiple addresses in one invitation URL.
2866 comma = strchr(address, ',');
2872 // Split of the port
2873 port = strrchr(address, ':');
2881 // IPv6 address are enclosed in brackets, per RFC 3986
2882 if(*address == '[') {
2884 char *bracket = strchr(address, ']');
2897 // Connect to the meshlink daemon mentioned in the URL.
2898 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2901 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2902 state.sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2904 if(state.sock == -1) {
2905 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2906 meshlink_errno = MESHLINK_ENETWORK;
2910 set_timeout(state.sock, 5000);
2912 if(connect(state.sock, aip->ai_addr, aip->ai_addrlen)) {
2913 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2914 meshlink_errno = MESHLINK_ENETWORK;
2915 closesocket(state.sock);
2925 meshlink_errno = MESHLINK_ERESOLV;
2928 if(state.sock != -1 || !comma) {
2935 if(state.sock == -1) {
2939 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2941 // Tell him we have an invitation, and give him our throw-away key.
2945 if(!sendline(state.sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2946 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2947 meshlink_errno = MESHLINK_ENETWORK;
2953 char hisname[4096] = "";
2954 int code, hismajor, hisminor = 0;
2956 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) {
2957 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2958 meshlink_errno = MESHLINK_ENETWORK;
2962 // Check if the hash of the key he gave us matches the hash in the URL.
2963 char *fingerprint = state.line + 2;
2966 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2967 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", state.line + 2);
2968 meshlink_errno = MESHLINK_EINTERNAL;
2972 if(memcmp(hishash, state.hash, 18)) {
2973 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", state.line + 2);
2974 meshlink_errno = MESHLINK_EPEER;
2978 hiskey = ecdsa_set_base64_public_key(fingerprint);
2981 meshlink_errno = MESHLINK_EINTERNAL;
2985 // Start an SPTPS session
2986 if(!sptps_start(&state.sptps, &state, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2987 meshlink_errno = MESHLINK_EINTERNAL;
2991 // Feed rest of input buffer to SPTPS
2992 if(!sptps_receive_data(&state.sptps, state.buffer, state.blen)) {
2993 meshlink_errno = MESHLINK_EPEER;
2998 logger(mesh, MESHLINK_DEBUG, "Starting invitation recv loop: %d %zu\n", state.sock, sizeof(state.line));
3000 while((len = recv(state.sock, state.line, sizeof(state.line), 0))) {
3002 if(errno == EINTR) {
3006 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
3007 meshlink_errno = MESHLINK_ENETWORK;
3011 if(!sptps_receive_data(&state.sptps, state.line, len)) {
3012 meshlink_errno = MESHLINK_EPEER;
3017 if(!state.success) {
3018 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
3019 meshlink_errno = MESHLINK_EPEER;
3023 sptps_stop(&state.sptps);
3026 closesocket(state.sock);
3028 pthread_mutex_unlock(&mesh->mutex);
3032 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
3033 meshlink_errno = MESHLINK_EINVAL;
3035 sptps_stop(&state.sptps);
3039 if(state.sock != -1) {
3040 closesocket(state.sock);
3043 pthread_mutex_unlock(&mesh->mutex);
3047 char *meshlink_export(meshlink_handle_t *mesh) {
3049 meshlink_errno = MESHLINK_EINVAL;
3053 // Create a config file on the fly.
3056 packmsg_output_t out = {buf, sizeof(buf)};
3057 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
3058 packmsg_add_str(&out, mesh->name);
3059 packmsg_add_str(&out, CORE_MESH);
3061 pthread_mutex_lock(&mesh->mutex);
3063 packmsg_add_int32(&out, mesh->self->devclass);
3064 packmsg_add_bool(&out, mesh->self->status.blacklisted);
3065 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
3066 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
3070 for(uint32_t i = 0; i < MAX_RECENT; i++) {
3071 if(mesh->self->recent[i].sa.sa_family) {
3078 packmsg_add_array(&out, count);
3080 for(uint32_t i = 0; i < count; i++) {
3081 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
3084 packmsg_add_int64(&out, 0);
3085 packmsg_add_int64(&out, 0);
3087 pthread_mutex_unlock(&mesh->mutex);
3089 if(!packmsg_output_ok(&out)) {
3090 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3091 meshlink_errno = MESHLINK_EINTERNAL;
3095 // Prepare a base64-encoded packmsg array containing our config file
3097 uint32_t len = packmsg_output_size(&out, buf);
3098 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
3099 uint8_t *buf2 = xmalloc(len2);
3100 packmsg_output_t out2 = {buf2, len2};
3101 packmsg_add_array(&out2, 1);
3102 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
3104 if(!packmsg_output_ok(&out2)) {
3105 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
3106 meshlink_errno = MESHLINK_EINTERNAL;
3111 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
3113 return (char *)buf2;
3116 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
3117 if(!mesh || !data) {
3118 meshlink_errno = MESHLINK_EINVAL;
3122 size_t datalen = strlen(data);
3123 uint8_t *buf = xmalloc(datalen);
3124 int buflen = b64decode(data, buf, datalen);
3127 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3128 meshlink_errno = MESHLINK_EPEER;
3132 packmsg_input_t in = {buf, buflen};
3133 uint32_t count = packmsg_get_array(&in);
3136 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
3137 meshlink_errno = MESHLINK_EPEER;
3141 pthread_mutex_lock(&mesh->mutex);
3145 uint32_t len = packmsg_get_bin_raw(&in, &data);
3151 packmsg_input_t in2 = {data, len};
3152 uint32_t version = packmsg_get_uint32(&in2);
3153 char *name = packmsg_get_str_dup(&in2);
3155 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
3157 packmsg_input_invalidate(&in);
3161 if(!check_id(name)) {
3166 node_t *n = lookup_node(mesh, name);
3169 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
3177 config_t config = {data, len};
3179 if(!node_read_from_config(mesh, n, &config)) {
3181 packmsg_input_invalidate(&in);
3185 /* Clear the reachability times, since we ourself have never seen these nodes yet */
3186 n->last_reachable = 0;
3187 n->last_unreachable = 0;
3189 if(!node_write_config(mesh, n)) {
3197 pthread_mutex_unlock(&mesh->mutex);
3201 if(!packmsg_done(&in)) {
3202 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
3203 meshlink_errno = MESHLINK_EPEER;
3207 if(!config_sync(mesh, "current")) {
3214 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
3215 if(n == mesh->self) {
3216 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
3217 meshlink_errno = MESHLINK_EINVAL;
3221 if(n->status.blacklisted) {
3222 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
3226 n->status.blacklisted = true;
3228 /* Immediately shut down any connections we have with the blacklisted node.
3229 * We can't call terminate_connection(), because we might be called from a callback function.
3231 for list_each(connection_t, c, mesh->connections) {
3233 shutdown(c->socket, SHUT_RDWR);
3237 utcp_abort_all_connections(n->utcp);
3243 n->status.udp_confirmed = false;
3245 if(n->status.reachable) {
3246 n->last_unreachable = time(NULL);
3249 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
3250 * manually call the status callback if necessary.
3252 if(n->status.reachable && mesh->node_status_cb) {
3253 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
3256 return node_write_config(mesh, n) && config_sync(mesh, "current");
3259 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3260 if(!mesh || !node) {
3261 meshlink_errno = MESHLINK_EINVAL;
3265 pthread_mutex_lock(&mesh->mutex);
3267 if(!blacklist(mesh, (node_t *)node)) {
3268 pthread_mutex_unlock(&mesh->mutex);
3272 pthread_mutex_unlock(&mesh->mutex);
3274 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3278 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3279 if(!mesh || !name) {
3280 meshlink_errno = MESHLINK_EINVAL;
3284 pthread_mutex_lock(&mesh->mutex);
3286 node_t *n = lookup_node(mesh, (char *)name);
3290 n->name = xstrdup(name);
3294 if(!blacklist(mesh, (node_t *)n)) {
3295 pthread_mutex_unlock(&mesh->mutex);
3299 pthread_mutex_unlock(&mesh->mutex);
3301 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3305 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3306 if(n == mesh->self) {
3307 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3308 meshlink_errno = MESHLINK_EINVAL;
3312 if(!n->status.blacklisted) {
3313 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3317 n->status.blacklisted = false;
3319 if(n->status.reachable) {
3320 n->last_reachable = time(NULL);
3321 update_node_status(mesh, n);
3324 return node_write_config(mesh, n) && config_sync(mesh, "current");
3327 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3328 if(!mesh || !node) {
3329 meshlink_errno = MESHLINK_EINVAL;
3333 pthread_mutex_lock(&mesh->mutex);
3335 if(!whitelist(mesh, (node_t *)node)) {
3336 pthread_mutex_unlock(&mesh->mutex);
3340 pthread_mutex_unlock(&mesh->mutex);
3342 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3346 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3347 if(!mesh || !name) {
3348 meshlink_errno = MESHLINK_EINVAL;
3352 pthread_mutex_lock(&mesh->mutex);
3354 node_t *n = lookup_node(mesh, (char *)name);
3358 n->name = xstrdup(name);
3362 if(!whitelist(mesh, (node_t *)n)) {
3363 pthread_mutex_unlock(&mesh->mutex);
3367 pthread_mutex_unlock(&mesh->mutex);
3369 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3373 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3374 mesh->default_blacklist = blacklist;
3377 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3378 if(!mesh || !node) {
3379 meshlink_errno = MESHLINK_EINVAL;
3383 node_t *n = (node_t *)node;
3385 pthread_mutex_lock(&mesh->mutex);
3387 /* Check that the node is not reachable */
3388 if(n->status.reachable || n->connection) {
3389 pthread_mutex_unlock(&mesh->mutex);
3390 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3394 /* Check that we don't have any active UTCP connections */
3395 if(n->utcp && utcp_is_active(n->utcp)) {
3396 pthread_mutex_unlock(&mesh->mutex);
3397 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3401 /* Check that we have no active connections to this node */
3402 for list_each(connection_t, c, mesh->connections) {
3404 pthread_mutex_unlock(&mesh->mutex);
3405 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3410 /* Remove any pending outgoings to this node */
3411 if(mesh->outgoings) {
3412 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3413 if(outgoing->node == n) {
3414 list_delete_node(mesh->outgoings, node);
3419 /* Delete the config file for this node */
3420 if(!config_delete(mesh, "current", n->name)) {
3421 pthread_mutex_unlock(&mesh->mutex);
3425 /* Delete the node struct and any remaining edges referencing this node */
3428 pthread_mutex_unlock(&mesh->mutex);
3430 return config_sync(mesh, "current");
3433 /* Hint that a hostname may be found at an address
3434 * See header file for detailed comment.
3436 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3437 if(!mesh || !node || !addr) {
3438 meshlink_errno = EINVAL;
3442 pthread_mutex_lock(&mesh->mutex);
3444 node_t *n = (node_t *)node;
3446 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3447 if(!node_write_config(mesh, n)) {
3448 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3452 pthread_mutex_unlock(&mesh->mutex);
3453 // @TODO do we want to fire off a connection attempt right away?
3456 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3458 node_t *n = utcp->priv;
3459 meshlink_handle_t *mesh = n->mesh;
3460 return mesh->channel_accept_cb;
3463 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3465 if(aio->cb.buffer) {
3466 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3470 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3475 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3476 meshlink_channel_t *channel = connection->priv;
3482 node_t *n = channel->node;
3483 meshlink_handle_t *mesh = n->mesh;
3485 if(n->status.destroyed) {
3486 meshlink_channel_close(mesh, channel);
3490 const char *p = data;
3493 while(channel->aio_receive) {
3494 meshlink_aio_buffer_t *aio = channel->aio_receive;
3495 size_t todo = aio->len - aio->done;
3502 memcpy((char *)aio->data + aio->done, p, todo);
3504 ssize_t result = write(aio->fd, p, todo);
3513 if(aio->done == aio->len) {
3514 channel->aio_receive = aio->next;
3515 aio_signal(mesh, channel, aio);
3527 if(channel->receive_cb) {
3528 channel->receive_cb(mesh, channel, p, left);
3534 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3535 node_t *n = utcp_connection->utcp->priv;
3541 meshlink_handle_t *mesh = n->mesh;
3543 if(!mesh->channel_accept_cb) {
3547 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3549 channel->c = utcp_connection;
3551 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3552 utcp_accept(utcp_connection, channel_recv, channel);
3558 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3559 node_t *n = utcp->priv;
3561 if(n->status.destroyed) {
3565 meshlink_handle_t *mesh = n->mesh;
3566 return meshlink_send_immediate(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3569 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3570 if(!mesh || !channel) {
3571 meshlink_errno = MESHLINK_EINVAL;
3575 channel->receive_cb = cb;
3578 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3580 node_t *n = (node_t *)source;
3586 utcp_recv(n->utcp, data, len);
3589 static void channel_poll(struct utcp_connection *connection, size_t len) {
3590 meshlink_channel_t *channel = connection->priv;
3596 node_t *n = channel->node;
3597 meshlink_handle_t *mesh = n->mesh;
3598 meshlink_aio_buffer_t *aio = channel->aio_send;
3601 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3602 size_t left = aio->len - aio->done;
3610 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3613 size_t todo = utcp_get_sndbuf_free(connection);
3619 if(todo > sizeof(buf)) {
3623 ssize_t result = read(aio->fd, buf, todo);
3626 sent = utcp_send(connection, buf, result);
3636 /* If the buffer is now completely sent, call the callback and dispose of it. */
3637 if(aio->done >= aio->len) {
3638 channel->aio_send = aio->next;
3639 aio_signal(mesh, channel, aio);
3643 if(channel->poll_cb) {
3644 channel->poll_cb(mesh, channel, len);
3646 utcp_set_poll_cb(connection, NULL);
3651 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3652 if(!mesh || !channel) {
3653 meshlink_errno = MESHLINK_EINVAL;
3657 pthread_mutex_lock(&mesh->mutex);
3658 channel->poll_cb = cb;
3659 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3660 pthread_mutex_unlock(&mesh->mutex);
3663 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3665 meshlink_errno = MESHLINK_EINVAL;
3669 pthread_mutex_lock(&mesh->mutex);
3670 mesh->channel_accept_cb = cb;
3671 mesh->receive_cb = channel_receive;
3673 for splay_each(node_t, n, mesh->nodes) {
3674 if(!n->utcp && n != mesh->self) {
3675 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3676 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3680 pthread_mutex_unlock(&mesh->mutex);
3683 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3687 meshlink_errno = MESHLINK_EINVAL;
3691 pthread_mutex_lock(&mesh->mutex);
3692 utcp_set_sndbuf(channel->c, size);
3693 pthread_mutex_unlock(&mesh->mutex);
3696 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3700 meshlink_errno = MESHLINK_EINVAL;
3704 pthread_mutex_lock(&mesh->mutex);
3705 utcp_set_rcvbuf(channel->c, size);
3706 pthread_mutex_unlock(&mesh->mutex);
3709 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) {
3711 abort(); // TODO: handle non-NULL data
3714 if(!mesh || !node) {
3715 meshlink_errno = MESHLINK_EINVAL;
3719 pthread_mutex_lock(&mesh->mutex);
3721 node_t *n = (node_t *)node;
3724 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3725 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
3726 mesh->receive_cb = channel_receive;
3729 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3730 pthread_mutex_unlock(&mesh->mutex);
3735 if(n->status.blacklisted) {
3736 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3737 meshlink_errno = MESHLINK_EBLACKLISTED;
3738 pthread_mutex_unlock(&mesh->mutex);
3742 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3744 channel->receive_cb = cb;
3747 channel->priv = (void *)data;
3750 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3752 pthread_mutex_unlock(&mesh->mutex);
3755 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3763 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) {
3764 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3767 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3768 if(!mesh || !channel) {
3769 meshlink_errno = MESHLINK_EINVAL;
3773 pthread_mutex_lock(&mesh->mutex);
3774 utcp_shutdown(channel->c, direction);
3775 pthread_mutex_unlock(&mesh->mutex);
3778 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3779 if(!mesh || !channel) {
3780 meshlink_errno = MESHLINK_EINVAL;
3784 pthread_mutex_lock(&mesh->mutex);
3786 utcp_close(channel->c);
3788 /* Clean up any outstanding AIO buffers. */
3789 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3791 aio_signal(mesh, channel, aio);
3795 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3797 aio_signal(mesh, channel, aio);
3801 pthread_mutex_unlock(&mesh->mutex);
3806 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3807 if(!mesh || !channel) {
3808 meshlink_errno = MESHLINK_EINVAL;
3817 meshlink_errno = MESHLINK_EINVAL;
3821 // TODO: more finegrained locking.
3822 // Ideally we want to put the data into the UTCP connection's send buffer.
3823 // Then, preferably only if there is room in the receiver window,
3824 // kick the meshlink thread to go send packets.
3828 pthread_mutex_lock(&mesh->mutex);
3830 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3831 if(channel->aio_send) {
3834 retval = utcp_send(channel->c, data, len);
3837 pthread_mutex_unlock(&mesh->mutex);
3840 meshlink_errno = MESHLINK_ENETWORK;
3846 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) {
3847 if(!mesh || !channel) {
3848 meshlink_errno = MESHLINK_EINVAL;
3853 meshlink_errno = MESHLINK_EINVAL;
3857 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3860 aio->cb.buffer = cb;
3863 pthread_mutex_lock(&mesh->mutex);
3865 /* Append the AIO buffer descriptor to the end of the chain */
3866 meshlink_aio_buffer_t **p = &channel->aio_send;
3874 /* Ensure the poll callback is set, and call it right now to push data if possible */
3875 utcp_set_poll_cb(channel->c, channel_poll);
3876 channel_poll(channel->c, len);
3878 pthread_mutex_unlock(&mesh->mutex);
3883 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) {
3884 if(!mesh || !channel) {
3885 meshlink_errno = MESHLINK_EINVAL;
3889 if(!len || fd == -1) {
3890 meshlink_errno = MESHLINK_EINVAL;
3894 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3900 pthread_mutex_lock(&mesh->mutex);
3902 /* Append the AIO buffer descriptor to the end of the chain */
3903 meshlink_aio_buffer_t **p = &channel->aio_send;
3911 /* Ensure the poll callback is set, and call it right now to push data if possible */
3912 utcp_set_poll_cb(channel->c, channel_poll);
3913 channel_poll(channel->c, len);
3915 pthread_mutex_unlock(&mesh->mutex);
3920 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) {
3921 if(!mesh || !channel) {
3922 meshlink_errno = MESHLINK_EINVAL;
3927 meshlink_errno = MESHLINK_EINVAL;
3931 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3934 aio->cb.buffer = cb;
3937 pthread_mutex_lock(&mesh->mutex);
3939 /* Append the AIO buffer descriptor to the end of the chain */
3940 meshlink_aio_buffer_t **p = &channel->aio_receive;
3948 pthread_mutex_unlock(&mesh->mutex);
3953 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) {
3954 if(!mesh || !channel) {
3955 meshlink_errno = MESHLINK_EINVAL;
3959 if(!len || fd == -1) {
3960 meshlink_errno = MESHLINK_EINVAL;
3964 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3970 pthread_mutex_lock(&mesh->mutex);
3972 /* Append the AIO buffer descriptor to the end of the chain */
3973 meshlink_aio_buffer_t **p = &channel->aio_receive;
3981 pthread_mutex_unlock(&mesh->mutex);
3986 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3987 if(!mesh || !channel) {
3988 meshlink_errno = MESHLINK_EINVAL;
3992 return channel->c->flags;
3995 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3996 if(!mesh || !channel) {
3997 meshlink_errno = MESHLINK_EINVAL;
4001 return utcp_get_sendq(channel->c);
4004 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4005 if(!mesh || !channel) {
4006 meshlink_errno = MESHLINK_EINVAL;
4010 return utcp_get_recvq(channel->c);
4013 size_t meshlink_channel_get_mss(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
4014 if(!mesh || !channel) {
4015 meshlink_errno = MESHLINK_EINVAL;
4019 return utcp_get_mss(channel->node->utcp);
4022 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
4023 if(!mesh || !node) {
4024 meshlink_errno = MESHLINK_EINVAL;
4028 node_t *n = (node_t *)node;
4030 pthread_mutex_lock(&mesh->mutex);
4033 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4034 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4037 utcp_set_user_timeout(n->utcp, timeout);
4039 pthread_mutex_unlock(&mesh->mutex);
4042 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
4043 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
4044 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
4045 utcp_set_mtu(n->utcp, n->mtu - sizeof(meshlink_packethdr_t));
4048 if(mesh->node_status_cb) {
4049 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
4052 if(mesh->node_pmtu_cb) {
4053 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4057 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
4058 utcp_set_mtu(n->utcp, (n->minmtu > MINMTU ? n->minmtu : MINMTU) - sizeof(meshlink_packethdr_t));
4060 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
4061 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
4065 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
4066 if(!mesh->node_duplicate_cb || n->status.duplicate) {
4070 n->status.duplicate = true;
4071 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
4074 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
4078 meshlink_errno = MESHLINK_EINVAL;
4082 pthread_mutex_lock(&mesh->mutex);
4084 if(mesh->discovery == enable) {
4088 if(mesh->threadstarted) {
4090 discovery_start(mesh);
4092 discovery_stop(mesh);
4096 mesh->discovery = enable;
4099 pthread_mutex_unlock(&mesh->mutex);
4103 meshlink_errno = MESHLINK_ENOTSUP;
4107 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
4108 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4109 meshlink_errno = EINVAL;
4113 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
4114 meshlink_errno = EINVAL;
4118 pthread_mutex_lock(&mesh->mutex);
4119 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
4120 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
4121 pthread_mutex_unlock(&mesh->mutex);
4124 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
4125 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
4126 meshlink_errno = EINVAL;
4130 if(fast_retry_period < 0) {
4131 meshlink_errno = EINVAL;
4135 pthread_mutex_lock(&mesh->mutex);
4136 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
4137 pthread_mutex_unlock(&mesh->mutex);
4140 extern void meshlink_set_inviter_commits_first(struct meshlink_handle *mesh, bool inviter_commits_first) {
4142 meshlink_errno = EINVAL;
4146 pthread_mutex_lock(&mesh->mutex);
4147 mesh->inviter_commits_first = inviter_commits_first;
4148 pthread_mutex_unlock(&mesh->mutex);
4151 void meshlink_set_external_address_discovery_url(struct meshlink_handle *mesh, const char *url) {
4153 meshlink_errno = EINVAL;
4157 if(url && (strncmp(url, "http://", 7) || strchr(url, ' '))) {
4158 meshlink_errno = EINVAL;
4162 pthread_mutex_lock(&mesh->mutex);
4163 free(mesh->external_address_url);
4164 mesh->external_address_url = url ? xstrdup(url) : NULL;
4165 pthread_mutex_unlock(&mesh->mutex);
4168 void meshlink_set_scheduling_granularity(struct meshlink_handle *mesh, long granularity) {
4169 if(!mesh || granularity < 0) {
4170 meshlink_errno = EINVAL;
4174 utcp_set_clock_granularity(granularity);
4177 void handle_network_change(meshlink_handle_t *mesh, bool online) {
4180 if(!mesh->connections || !mesh->loop.running) {
4187 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
4188 // We should only call the callback function if we are in the background thread.
4189 if(!mesh->error_cb) {
4193 if(!mesh->threadstarted) {
4197 if(mesh->thread == pthread_self()) {
4198 mesh->error_cb(mesh, meshlink_errno);
4202 static void __attribute__((constructor)) meshlink_init(void) {
4204 utcp_set_clock_granularity(10000);
4207 static void __attribute__((destructor)) meshlink_exit(void) {