2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2018 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "meshlink_internal.h"
37 #include "ed25519/sha512.h"
38 #include "discovery.h"
42 #define MSG_NOSIGNAL 0
44 __thread meshlink_errno_t meshlink_errno;
45 meshlink_log_cb_t global_log_cb;
46 meshlink_log_level_t global_log_level;
48 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
50 static int rstrip(char *value) {
51 int len = strlen(value);
53 while(len && strchr("\t\r\n ", value[len - 1])) {
60 static void get_canonical_address(node_t *n, char **hostname, char **port) {
61 if(!n->canonical_address) {
65 *hostname = xstrdup(n->canonical_address);
66 char *space = strchr(*hostname, ' ');
70 *port = xstrdup(space);
74 static bool is_valid_hostname(const char *hostname) {
79 for(const char *p = hostname; *p; p++) {
80 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
88 static bool is_valid_port(const char *port) {
95 unsigned long int result = strtoul(port, &end, 10);
96 return result && result < 65536 && !*end;
99 for(const char *p = port; *p; p++) {
100 if(!(isalnum(*p) || *p == '-')) {
108 static void set_timeout(int sock, int timeout) {
113 tv.tv_sec = timeout / 1000;
114 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
116 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
117 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
120 struct socket_in_netns_params {
129 static void *socket_in_netns_thread(void *arg) {
130 struct socket_in_netns_params *params = arg;
132 if(setns(params->netns, CLONE_NEWNET) == -1) {
133 meshlink_errno = MESHLINK_EINVAL;
137 params->fd = socket(params->domain, params->type, params->protocol);
143 static int socket_in_netns(int domain, int type, int protocol, int netns) {
145 return socket(domain, type, protocol);
149 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
153 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
154 pthread_join(thr, NULL);
164 // Find out what local address a socket would use if we connect to the given address.
165 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
166 // of both endpoints, but this will actually not send any UDP packet.
167 static bool getlocaladdr(char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
168 struct addrinfo *rai = NULL;
169 const struct addrinfo hint = {
170 .ai_family = AF_UNSPEC,
171 .ai_socktype = SOCK_DGRAM,
172 .ai_protocol = IPPROTO_UDP,
175 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
179 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
186 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
194 if(getsockname(sock, &sa->sa, salen)) {
203 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
205 socklen_t salen = sizeof(sa);
207 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
211 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
218 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
219 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
222 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
223 char *hostname = NULL;
225 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
226 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
227 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
230 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
231 if(family != AF_UNSPEC && aip->ai_family != family) {
235 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
238 set_timeout(s, 5000);
240 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
247 send(s, request, sizeof(request) - 1, 0);
248 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
253 if(line[len - 1] == '\n') {
257 char *p = strrchr(line, '\n');
260 hostname = xstrdup(p + 1);
276 // Check that the hostname is reasonable
277 if(hostname && !is_valid_hostname(hostname)) {
283 meshlink_errno = MESHLINK_ERESOLV;
289 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
292 // Determine address of the local interface used for outgoing connections.
293 char localaddr[NI_MAXHOST];
294 bool success = false;
296 if(family == AF_INET) {
297 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
298 } else if(family == AF_INET6) {
299 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
303 meshlink_errno = MESHLINK_ENETWORK;
307 return xstrdup(localaddr);
310 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
311 for(int i = 0; i < n; i++) {
316 // Ignore duplicate hostnames
319 for(int j = 0; j < i; j++) {
324 if(strcmp(host[i], host[j])) {
328 if(strcmp(port[i], port[j])) {
336 if(found || !is_valid_hostname(host[i])) {
346 // This gets the hostname part for use in invitation URLs
347 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
348 char *hostname[4] = {NULL};
349 char *port[4] = {NULL};
350 char *hostport = NULL;
352 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
353 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
356 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
357 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
360 // Add local addresses if requested
361 if(flags & MESHLINK_INVITE_LOCAL) {
362 if(flags & MESHLINK_INVITE_IPV4) {
363 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
366 if(flags & MESHLINK_INVITE_IPV6) {
367 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
371 // Add public/canonical addresses if requested
372 if(flags & MESHLINK_INVITE_PUBLIC) {
373 // Try the CanonicalAddress first
374 get_canonical_address(mesh->self, &hostname[2], &port[2]);
377 if(flags & MESHLINK_INVITE_IPV4) {
378 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
381 if(flags & MESHLINK_INVITE_IPV6) {
382 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
387 for(int i = 0; i < 4; i++) {
388 // Ensure we always have a port number
389 if(hostname[i] && !port[i]) {
390 port[i] = xstrdup(mesh->myport);
394 remove_duplicate_hostnames(hostname, port, 4);
396 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
397 for(int i = 0; i < 4; i++) {
402 // Convert what we have to a sockaddr
403 struct addrinfo *ai_in, *ai_out;
404 struct addrinfo hint = {
405 .ai_family = AF_UNSPEC,
406 .ai_flags = AI_NUMERICSERV,
407 .ai_socktype = SOCK_STREAM,
409 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
415 // Convert it to a hostname
416 char resolved_host[NI_MAXHOST];
417 char resolved_port[NI_MAXSERV];
418 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
420 if(err || !is_valid_hostname(resolved_host)) {
425 // Convert the hostname back to a sockaddr
426 hint.ai_family = ai_in->ai_family;
427 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
434 // Check if it's still the same sockaddr
435 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
437 freeaddrinfo(ai_out);
441 // Yes: replace the hostname with the resolved one
443 hostname[i] = xstrdup(resolved_host);
446 freeaddrinfo(ai_out);
450 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
451 remove_duplicate_hostnames(hostname, port, 4);
453 // Concatenate all unique address to the hostport string
454 for(int i = 0; i < 4; i++) {
459 // Ensure we have the same addresses in our own host config file.
461 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
463 //config_add_string(&mesh->config, "Address", tmphostport);
466 // Append the address to the hostport string
468 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
470 hostport = newhostport;
479 static bool try_bind(int port) {
480 struct addrinfo *ai = NULL;
481 struct addrinfo hint = {
482 .ai_flags = AI_PASSIVE,
483 .ai_family = AF_UNSPEC,
484 .ai_socktype = SOCK_STREAM,
485 .ai_protocol = IPPROTO_TCP,
489 snprintf(portstr, sizeof(portstr), "%d", port);
491 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
496 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
497 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
504 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
517 static int check_port(meshlink_handle_t *mesh) {
518 for(int i = 0; i < 1000; i++) {
519 int port = 0x1000 + prng(mesh, 0x8000);
523 xasprintf(&mesh->myport, "%d", port);
528 meshlink_errno = MESHLINK_ENETWORK;
529 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
533 static bool write_main_config_files(meshlink_handle_t *mesh) {
534 if(!mesh->confbase) {
540 /* Write the main config file */
541 packmsg_output_t out = {buf, sizeof buf};
543 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
544 packmsg_add_str(&out, mesh->name);
545 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
546 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
547 packmsg_add_uint16(&out, atoi(mesh->myport));
549 if(!packmsg_output_ok(&out)) {
553 config_t config = {buf, packmsg_output_size(&out, buf)};
555 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
559 /* Write our own host config file */
560 if(!node_write_config(mesh, mesh->self)) {
567 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
568 packmsg_input_t in = {buf, len};
569 uint32_t version = packmsg_get_uint32(&in);
571 if(version != MESHLINK_INVITATION_VERSION) {
572 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
576 char *name = packmsg_get_str_dup(&in);
577 packmsg_skip_element(&in); /* submesh */
578 dev_class_t devclass = packmsg_get_int32(&in);
579 uint32_t count = packmsg_get_array(&in);
582 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
586 if(!check_id(name)) {
587 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
593 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
599 free(mesh->self->name);
601 mesh->self->name = xstrdup(name);
602 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
604 // Initialize configuration directory
605 if(!config_init(mesh, "current")) {
609 if(!write_main_config_files(mesh)) {
613 // Write host config files
616 uint32_t len = packmsg_get_bin_raw(&in, &data);
619 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
623 packmsg_input_t in2 = {data, len};
624 uint32_t version = packmsg_get_uint32(&in2);
625 char *name = packmsg_get_str_dup(&in2);
627 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
629 packmsg_input_invalidate(&in);
633 if(!check_id(name)) {
638 if(!strcmp(name, mesh->name)) {
639 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
641 meshlink_errno = MESHLINK_EPEER;
645 node_t *n = new_node();
648 config_t config = {data, len};
650 if(!node_read_from_config(mesh, n, &config)) {
652 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
653 meshlink_errno = MESHLINK_EPEER;
659 if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
664 /* Ensure the configuration directory metadata is on disk */
665 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
669 sptps_send_record(&mesh->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
671 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
676 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
678 meshlink_handle_t *mesh = handle;
679 const char *ptr = data;
682 int result = send(mesh->sock, ptr, len, 0);
684 if(result == -1 && errno == EINTR) {
686 } else if(result <= 0) {
697 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
698 meshlink_handle_t *mesh = handle;
701 case SPTPS_HANDSHAKE:
702 return sptps_send_record(&mesh->sptps, 0, mesh->cookie, sizeof(mesh)->cookie);
705 return finalize_join(mesh, msg, len);
708 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
709 shutdown(mesh->sock, SHUT_RDWR);
710 mesh->success = true;
720 static bool recvline(meshlink_handle_t *mesh, size_t len) {
721 char *newline = NULL;
727 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
728 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
730 if(result == -1 && errno == EINTR) {
732 } else if(result <= 0) {
736 mesh->blen += result;
739 if((size_t)(newline - mesh->buffer) >= len) {
743 len = newline - mesh->buffer;
745 memcpy(mesh->line, mesh->buffer, len);
747 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
748 mesh->blen -= len + 1;
753 static bool sendline(int fd, char *format, ...) {
759 va_start(ap, format);
760 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
763 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
771 int result = send(fd, p, blen, MSG_NOSIGNAL);
773 if(result == -1 && errno == EINTR) {
775 } else if(result <= 0) {
786 static const char *errstr[] = {
787 [MESHLINK_OK] = "No error",
788 [MESHLINK_EINVAL] = "Invalid argument",
789 [MESHLINK_ENOMEM] = "Out of memory",
790 [MESHLINK_ENOENT] = "No such node",
791 [MESHLINK_EEXIST] = "Node already exists",
792 [MESHLINK_EINTERNAL] = "Internal error",
793 [MESHLINK_ERESOLV] = "Could not resolve hostname",
794 [MESHLINK_ESTORAGE] = "Storage error",
795 [MESHLINK_ENETWORK] = "Network error",
796 [MESHLINK_EPEER] = "Error communicating with peer",
797 [MESHLINK_ENOTSUP] = "Operation not supported",
798 [MESHLINK_EBUSY] = "MeshLink instance already in use",
799 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
802 const char *meshlink_strerror(meshlink_errno_t err) {
803 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
804 return "Invalid error code";
810 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
811 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
813 mesh->private_key = ecdsa_generate();
814 mesh->invitation_key = ecdsa_generate();
816 if(!mesh->private_key || !mesh->invitation_key) {
817 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
818 meshlink_errno = MESHLINK_EINTERNAL;
822 logger(mesh, MESHLINK_DEBUG, "Done.\n");
827 static struct timeval idle(event_loop_t *loop, void *data) {
829 meshlink_handle_t *mesh = data;
830 struct timeval t, tmin = {3600, 0};
832 for splay_each(node_t, n, mesh->nodes) {
837 t = utcp_timeout(n->utcp);
839 if(timercmp(&t, &tmin, <)) {
847 // Get our local address(es) by simulating connecting to an Internet host.
848 static void add_local_addresses(meshlink_handle_t *mesh) {
850 sa.storage.ss_family = AF_UNKNOWN;
851 socklen_t salen = sizeof(sa);
855 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
856 sa.in.sin_port = ntohs(atoi(mesh->myport));
857 node_add_recent_address(mesh, mesh->self, &sa);
864 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
865 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
866 node_add_recent_address(mesh, mesh->self, &sa);
870 static bool meshlink_setup(meshlink_handle_t *mesh) {
871 if(!config_destroy(mesh->confbase, "new")) {
872 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
873 meshlink_errno = MESHLINK_ESTORAGE;
877 if(!config_destroy(mesh->confbase, "old")) {
878 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
879 meshlink_errno = MESHLINK_ESTORAGE;
883 if(!config_init(mesh, "current")) {
884 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
885 meshlink_errno = MESHLINK_ESTORAGE;
889 if(!ecdsa_keygen(mesh)) {
890 meshlink_errno = MESHLINK_EINTERNAL;
894 if(check_port(mesh) == 0) {
895 meshlink_errno = MESHLINK_ENETWORK;
899 /* Create a node for ourself */
901 mesh->self = new_node();
902 mesh->self->name = xstrdup(mesh->name);
903 mesh->self->devclass = mesh->devclass;
904 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
905 mesh->self->session_id = mesh->session_id;
907 if(!write_main_config_files(mesh)) {
908 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
909 meshlink_errno = MESHLINK_ESTORAGE;
913 /* Ensure the configuration directory metadata is on disk */
914 if(!config_sync(mesh, "current")) {
921 static bool meshlink_read_config(meshlink_handle_t *mesh) {
924 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
925 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
929 packmsg_input_t in = {config.buf, config.len};
930 const void *private_key;
931 const void *invitation_key;
933 uint32_t version = packmsg_get_uint32(&in);
934 char *name = packmsg_get_str_dup(&in);
935 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
936 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
937 uint16_t myport = packmsg_get_uint16(&in);
939 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
940 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
942 config_free(&config);
949 if(mesh->name && strcmp(mesh->name, name)) {
950 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
951 meshlink_errno = MESHLINK_ESTORAGE;
953 config_free(&config);
961 xasprintf(&mesh->myport, "%u", myport);
962 mesh->private_key = ecdsa_set_private_key(private_key);
963 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
964 config_free(&config);
966 /* Create a node for ourself and read our host configuration file */
968 mesh->self = new_node();
969 mesh->self->name = xstrdup(name);
970 mesh->self->devclass = mesh->devclass;
971 mesh->self->session_id = mesh->session_id;
973 if(!node_read_public_key(mesh, mesh->self)) {
974 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
975 meshlink_errno = MESHLINK_ESTORAGE;
976 free_node(mesh->self);
985 static void *setup_network_in_netns_thread(void *arg) {
986 meshlink_handle_t *mesh = arg;
988 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
992 bool success = setup_network(mesh);
993 add_local_addresses(mesh);
994 return success ? arg : NULL;
998 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
999 if(!confbase || !*confbase) {
1000 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1001 meshlink_errno = MESHLINK_EINVAL;
1005 if(!appname || !*appname) {
1006 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1007 meshlink_errno = MESHLINK_EINVAL;
1011 if(strchr(appname, ' ')) {
1012 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1013 meshlink_errno = MESHLINK_EINVAL;
1017 if(!name || !*name) {
1018 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1019 meshlink_errno = MESHLINK_EINVAL;
1023 if(!check_id(name)) {
1024 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1025 meshlink_errno = MESHLINK_EINVAL;
1029 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1030 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1031 meshlink_errno = MESHLINK_EINVAL;
1035 meshlink_open_params_t *params = xzalloc(sizeof * params);
1037 params->confbase = xstrdup(confbase);
1038 params->name = xstrdup(name);
1039 params->appname = xstrdup(appname);
1040 params->devclass = devclass;
1046 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1048 meshlink_errno = MESHLINK_EINVAL;
1052 params->netns = netns;
1057 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1059 meshlink_errno = MESHLINK_EINVAL;
1063 if((!key && keylen) || (key && !keylen)) {
1064 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1065 meshlink_errno = MESHLINK_EINVAL;
1070 params->keylen = keylen;
1075 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1076 if(!mesh || !new_key || !new_keylen) {
1077 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1078 meshlink_errno = MESHLINK_EINVAL;
1082 pthread_mutex_lock(&mesh->mutex);
1084 // Create hash for the new key
1085 void *new_config_key;
1086 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1088 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1089 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1090 meshlink_errno = MESHLINK_EINTERNAL;
1091 pthread_mutex_unlock(&mesh->mutex);
1095 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1097 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1098 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1099 meshlink_errno = MESHLINK_ESTORAGE;
1100 pthread_mutex_unlock(&mesh->mutex);
1104 devtool_keyrotate_probe(1);
1106 // Rename confbase/current/ to confbase/old
1108 if(!config_rename(mesh, "current", "old")) {
1109 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1110 meshlink_errno = MESHLINK_ESTORAGE;
1111 pthread_mutex_unlock(&mesh->mutex);
1115 devtool_keyrotate_probe(2);
1117 // Rename confbase/new/ to confbase/current
1119 if(!config_rename(mesh, "new", "current")) {
1120 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1121 meshlink_errno = MESHLINK_ESTORAGE;
1122 pthread_mutex_unlock(&mesh->mutex);
1126 devtool_keyrotate_probe(3);
1128 // Cleanup the "old" confbase sub-directory
1130 if(!config_destroy(mesh->confbase, "old")) {
1131 pthread_mutex_unlock(&mesh->mutex);
1135 // Change the mesh handle key with new key
1137 free(mesh->config_key);
1138 mesh->config_key = new_config_key;
1140 pthread_mutex_unlock(&mesh->mutex);
1145 void meshlink_open_params_free(meshlink_open_params_t *params) {
1147 meshlink_errno = MESHLINK_EINVAL;
1151 free(params->confbase);
1153 free(params->appname);
1158 /// Device class traits
1159 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1160 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1161 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1162 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1163 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1166 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1167 if(!confbase || !*confbase) {
1168 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1169 meshlink_errno = MESHLINK_EINVAL;
1173 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1174 meshlink_open_params_t params;
1175 memset(¶ms, 0, sizeof(params));
1177 params.confbase = (char *)confbase;
1178 params.name = (char *)name;
1179 params.appname = (char *)appname;
1180 params.devclass = devclass;
1183 return meshlink_open_ex(¶ms);
1186 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) {
1187 if(!confbase || !*confbase) {
1188 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1189 meshlink_errno = MESHLINK_EINVAL;
1193 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1194 meshlink_open_params_t params;
1195 memset(¶ms, 0, sizeof(params));
1197 params.confbase = (char *)confbase;
1198 params.name = (char *)name;
1199 params.appname = (char *)appname;
1200 params.devclass = devclass;
1203 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1207 return meshlink_open_ex(¶ms);
1210 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1211 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1212 meshlink_open_params_t params;
1213 memset(¶ms, 0, sizeof(params));
1215 params.name = (char *)name;
1216 params.appname = (char *)appname;
1217 params.devclass = devclass;
1220 return meshlink_open_ex(¶ms);
1223 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1224 // Validate arguments provided by the application
1225 bool usingname = false;
1227 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1229 if(!params->appname || !*params->appname) {
1230 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1231 meshlink_errno = MESHLINK_EINVAL;
1235 if(strchr(params->appname, ' ')) {
1236 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1237 meshlink_errno = MESHLINK_EINVAL;
1241 if(!params->name || !*params->name) {
1242 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1244 } else { //check name only if there is a name != NULL
1246 if(!check_id(params->name)) {
1247 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1248 meshlink_errno = MESHLINK_EINVAL;
1255 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1256 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1257 meshlink_errno = MESHLINK_EINVAL;
1261 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1262 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1263 meshlink_errno = MESHLINK_EINVAL;
1267 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1269 if(params->confbase) {
1270 mesh->confbase = xstrdup(params->confbase);
1273 mesh->appname = xstrdup(params->appname);
1274 mesh->devclass = params->devclass;
1275 mesh->discovery = true;
1276 mesh->invitation_timeout = 604800; // 1 week
1277 mesh->netns = params->netns;
1278 mesh->submeshes = NULL;
1279 mesh->log_cb = global_log_cb;
1280 mesh->log_level = global_log_level;
1282 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1285 randomize(&mesh->session_id, sizeof(mesh->session_id));
1286 } while(mesh->session_id == 0);
1288 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1291 mesh->name = xstrdup(params->name);
1296 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1298 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1299 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1300 meshlink_close(mesh);
1301 meshlink_errno = MESHLINK_EINTERNAL;
1307 pthread_mutexattr_t attr;
1308 pthread_mutexattr_init(&attr);
1309 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1310 pthread_mutex_init(&mesh->mutex, &attr);
1312 mesh->threadstarted = false;
1313 event_loop_init(&mesh->loop);
1314 mesh->loop.data = mesh;
1316 meshlink_queue_init(&mesh->outpacketqueue);
1318 // Atomically lock the configuration directory.
1319 if(!main_config_lock(mesh)) {
1320 meshlink_close(mesh);
1324 // If no configuration exists yet, create it.
1326 if(!meshlink_confbase_exists(mesh)) {
1327 if(!meshlink_setup(mesh)) {
1328 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1329 meshlink_close(mesh);
1333 if(!meshlink_read_config(mesh)) {
1334 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1335 meshlink_close(mesh);
1341 struct WSAData wsa_state;
1342 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1345 // Setup up everything
1346 // TODO: we should not open listening sockets yet
1348 bool success = false;
1350 if(mesh->netns != -1) {
1354 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1355 void *retval = NULL;
1356 success = pthread_join(thr, &retval) == 0 && retval;
1360 meshlink_errno = MESHLINK_EINTERNAL;
1363 #endif // HAVE_SETNS
1365 success = setup_network(mesh);
1366 add_local_addresses(mesh);
1370 meshlink_close(mesh);
1371 meshlink_errno = MESHLINK_ENETWORK;
1375 add_local_addresses(mesh);
1377 if(!node_write_config(mesh, mesh->self)) {
1378 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1382 idle_set(&mesh->loop, idle, mesh);
1384 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1388 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1389 meshlink_submesh_t *s = NULL;
1392 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1393 meshlink_errno = MESHLINK_EINVAL;
1397 if(!submesh || !*submesh) {
1398 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1399 meshlink_errno = MESHLINK_EINVAL;
1404 pthread_mutex_lock(&mesh->mutex);
1406 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1408 pthread_mutex_unlock(&mesh->mutex);
1413 static void *meshlink_main_loop(void *arg) {
1414 meshlink_handle_t *mesh = arg;
1416 if(mesh->netns != -1) {
1419 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1420 pthread_cond_signal(&mesh->cond);
1425 pthread_cond_signal(&mesh->cond);
1427 #endif // HAVE_SETNS
1432 if(mesh->discovery) {
1433 discovery_start(mesh);
1438 pthread_mutex_lock(&mesh->mutex);
1440 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1441 pthread_cond_broadcast(&mesh->cond);
1443 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1445 pthread_mutex_unlock(&mesh->mutex);
1450 if(mesh->discovery) {
1451 discovery_stop(mesh);
1459 bool meshlink_start(meshlink_handle_t *mesh) {
1461 assert(mesh->private_key);
1464 meshlink_errno = MESHLINK_EINVAL;
1468 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1470 pthread_mutex_lock(&mesh->mutex);
1472 assert(mesh->self->ecdsa);
1473 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1475 if(mesh->threadstarted) {
1476 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1477 pthread_mutex_unlock(&mesh->mutex);
1481 if(mesh->listen_socket[0].tcp.fd < 0) {
1482 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1483 meshlink_errno = MESHLINK_ENETWORK;
1487 mesh->thedatalen = 0;
1489 // TODO: open listening sockets first
1491 //Check that a valid name is set
1493 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1494 meshlink_errno = MESHLINK_EINVAL;
1495 pthread_mutex_unlock(&mesh->mutex);
1499 init_outgoings(mesh);
1501 // Start the main thread
1503 event_loop_start(&mesh->loop);
1505 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1506 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1507 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1508 meshlink_errno = MESHLINK_EINTERNAL;
1509 event_loop_stop(&mesh->loop);
1510 pthread_mutex_unlock(&mesh->mutex);
1514 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1515 mesh->threadstarted = true;
1516 mesh->self->last_reachable = time(NULL);
1517 mesh->self->status.dirty = true;
1519 pthread_mutex_unlock(&mesh->mutex);
1523 void meshlink_stop(meshlink_handle_t *mesh) {
1525 meshlink_errno = MESHLINK_EINVAL;
1529 pthread_mutex_lock(&mesh->mutex);
1530 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1533 mesh->self->last_unreachable = time(NULL);
1534 mesh->self->status.dirty = true;
1537 // Shut down the main thread
1538 event_loop_stop(&mesh->loop);
1540 // Send ourselves a UDP packet to kick the event loop
1541 for(int i = 0; i < mesh->listen_sockets; i++) {
1543 socklen_t salen = sizeof(sa);
1545 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1546 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1550 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1551 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1555 if(mesh->threadstarted) {
1556 // Wait for the main thread to finish
1557 pthread_mutex_unlock(&mesh->mutex);
1558 pthread_join(mesh->thread, NULL);
1559 pthread_mutex_lock(&mesh->mutex);
1561 mesh->threadstarted = false;
1564 // Close all metaconnections
1565 if(mesh->connections) {
1566 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1568 connection_t *c = node->data;
1570 terminate_connection(mesh, c, false);
1574 exit_outgoings(mesh);
1576 // Try to write out any changed node config files, ignore errors at this point.
1578 for splay_each(node_t, n, mesh->nodes) {
1579 if(n->status.dirty) {
1580 n->status.dirty = !node_write_config(mesh, n);
1585 pthread_mutex_unlock(&mesh->mutex);
1588 void meshlink_close(meshlink_handle_t *mesh) {
1590 meshlink_errno = MESHLINK_EINVAL;
1594 // stop can be called even if mesh has not been started
1595 meshlink_stop(mesh);
1597 // lock is not released after this
1598 pthread_mutex_lock(&mesh->mutex);
1600 // Close and free all resources used.
1602 close_network_connections(mesh);
1604 logger(mesh, MESHLINK_INFO, "Terminating");
1606 event_loop_exit(&mesh->loop);
1610 if(mesh->confbase) {
1616 ecdsa_free(mesh->invitation_key);
1618 if(mesh->netns != -1) {
1622 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1626 meshlink_queue_exit(&mesh->outpacketqueue);
1629 free(mesh->appname);
1630 free(mesh->confbase);
1631 free(mesh->config_key);
1632 ecdsa_free(mesh->private_key);
1634 main_config_unlock(mesh);
1636 pthread_mutex_unlock(&mesh->mutex);
1637 pthread_mutex_destroy(&mesh->mutex);
1639 memset(mesh, 0, sizeof(*mesh));
1644 bool meshlink_destroy(const char *confbase) {
1646 meshlink_errno = MESHLINK_EINVAL;
1650 /* Exit early if the confbase directory itself doesn't exist */
1651 if(access(confbase, F_OK) && errno == ENOENT) {
1655 /* Take the lock the same way meshlink_open() would. */
1656 char lockfilename[PATH_MAX];
1657 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1659 FILE *lockfile = fopen(lockfilename, "w+");
1662 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1663 meshlink_errno = MESHLINK_ESTORAGE;
1668 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1672 // TODO: use _locking()?
1675 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1676 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1678 meshlink_errno = MESHLINK_EBUSY;
1684 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1685 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1689 if(unlink(lockfilename)) {
1690 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1692 meshlink_errno = MESHLINK_ESTORAGE;
1698 if(!sync_path(confbase)) {
1699 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1700 meshlink_errno = MESHLINK_ESTORAGE;
1707 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1709 meshlink_errno = MESHLINK_EINVAL;
1713 pthread_mutex_lock(&mesh->mutex);
1714 mesh->receive_cb = cb;
1715 pthread_mutex_unlock(&mesh->mutex);
1718 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1720 meshlink_errno = MESHLINK_EINVAL;
1724 pthread_mutex_lock(&mesh->mutex);
1725 mesh->connection_try_cb = cb;
1726 pthread_mutex_unlock(&mesh->mutex);
1729 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1731 meshlink_errno = MESHLINK_EINVAL;
1735 pthread_mutex_lock(&mesh->mutex);
1736 mesh->node_status_cb = cb;
1737 pthread_mutex_unlock(&mesh->mutex);
1740 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1742 meshlink_errno = MESHLINK_EINVAL;
1746 pthread_mutex_lock(&mesh->mutex);
1747 mesh->node_pmtu_cb = cb;
1748 pthread_mutex_unlock(&mesh->mutex);
1751 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1753 meshlink_errno = MESHLINK_EINVAL;
1757 pthread_mutex_lock(&mesh->mutex);
1758 mesh->node_duplicate_cb = cb;
1759 pthread_mutex_unlock(&mesh->mutex);
1762 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1764 pthread_mutex_lock(&mesh->mutex);
1766 mesh->log_level = cb ? level : 0;
1767 pthread_mutex_unlock(&mesh->mutex);
1770 global_log_level = cb ? level : 0;
1774 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1776 meshlink_errno = MESHLINK_EINVAL;
1780 pthread_mutex_lock(&mesh->mutex);
1781 mesh->error_cb = cb;
1782 pthread_mutex_unlock(&mesh->mutex);
1785 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1786 meshlink_packethdr_t *hdr;
1788 // Validate arguments
1789 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1790 meshlink_errno = MESHLINK_EINVAL;
1799 meshlink_errno = MESHLINK_EINVAL;
1803 node_t *n = (node_t *)destination;
1805 if(n->status.blacklisted) {
1806 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1807 meshlink_errno = MESHLINK_EBLACKLISTED;
1811 // Prepare the packet
1812 vpn_packet_t *packet = malloc(sizeof(*packet));
1815 meshlink_errno = MESHLINK_ENOMEM;
1819 packet->probe = false;
1820 packet->tcp = false;
1821 packet->len = len + sizeof(*hdr);
1823 hdr = (meshlink_packethdr_t *)packet->data;
1824 memset(hdr, 0, sizeof(*hdr));
1825 // leave the last byte as 0 to make sure strings are always
1826 // null-terminated if they are longer than the buffer
1827 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1828 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1830 memcpy(packet->data + sizeof(*hdr), data, len);
1833 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1835 meshlink_errno = MESHLINK_ENOMEM;
1839 // Notify event loop
1840 signal_trigger(&mesh->loop, &mesh->datafromapp);
1845 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1847 meshlink_handle_t *mesh = data;
1848 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1854 mesh->self->in_packets++;
1855 mesh->self->in_bytes += packet->len;
1856 route(mesh, mesh->self, packet);
1861 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1862 if(!mesh || !destination) {
1863 meshlink_errno = MESHLINK_EINVAL;
1867 pthread_mutex_lock(&mesh->mutex);
1869 node_t *n = (node_t *)destination;
1871 if(!n->status.reachable) {
1872 pthread_mutex_unlock(&mesh->mutex);
1875 } else if(n->mtuprobes > 30 && n->minmtu) {
1876 pthread_mutex_unlock(&mesh->mutex);
1879 pthread_mutex_unlock(&mesh->mutex);
1884 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1885 if(!mesh || !node) {
1886 meshlink_errno = MESHLINK_EINVAL;
1890 pthread_mutex_lock(&mesh->mutex);
1892 node_t *n = (node_t *)node;
1894 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1895 meshlink_errno = MESHLINK_EINTERNAL;
1896 pthread_mutex_unlock(&mesh->mutex);
1900 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1903 meshlink_errno = MESHLINK_EINTERNAL;
1906 pthread_mutex_unlock(&mesh->mutex);
1910 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1912 meshlink_errno = MESHLINK_EINVAL;
1916 return (meshlink_node_t *)mesh->self;
1919 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1920 if(!mesh || !name) {
1921 meshlink_errno = MESHLINK_EINVAL;
1927 pthread_mutex_lock(&mesh->mutex);
1928 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1929 pthread_mutex_unlock(&mesh->mutex);
1932 meshlink_errno = MESHLINK_ENOENT;
1935 return (meshlink_node_t *)n;
1938 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1939 if(!mesh || !name) {
1940 meshlink_errno = MESHLINK_EINVAL;
1944 meshlink_submesh_t *submesh = NULL;
1946 pthread_mutex_lock(&mesh->mutex);
1947 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1948 pthread_mutex_unlock(&mesh->mutex);
1951 meshlink_errno = MESHLINK_ENOENT;
1957 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1958 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1959 meshlink_errno = MESHLINK_EINVAL;
1963 meshlink_node_t **result;
1966 pthread_mutex_lock(&mesh->mutex);
1968 *nmemb = mesh->nodes->count;
1969 result = realloc(nodes, *nmemb * sizeof(*nodes));
1972 meshlink_node_t **p = result;
1974 for splay_each(node_t, n, mesh->nodes) {
1975 *p++ = (meshlink_node_t *)n;
1980 meshlink_errno = MESHLINK_ENOMEM;
1983 pthread_mutex_unlock(&mesh->mutex);
1988 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) {
1989 meshlink_node_t **result;
1991 pthread_mutex_lock(&mesh->mutex);
1995 for splay_each(node_t, n, mesh->nodes) {
1996 if(search_node(n, condition)) {
2003 pthread_mutex_unlock(&mesh->mutex);
2007 result = realloc(nodes, *nmemb * sizeof(*nodes));
2010 meshlink_node_t **p = result;
2012 for splay_each(node_t, n, mesh->nodes) {
2013 if(search_node(n, condition)) {
2014 *p++ = (meshlink_node_t *)n;
2020 meshlink_errno = MESHLINK_ENOMEM;
2023 pthread_mutex_unlock(&mesh->mutex);
2028 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2029 dev_class_t *devclass = (dev_class_t *)condition;
2031 if(*devclass == (dev_class_t)node->devclass) {
2038 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2039 if(condition == node->submesh) {
2051 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2052 const struct time_range *range = condition;
2053 time_t start = node->last_reachable;
2054 time_t end = node->last_unreachable;
2064 if(range->end >= range->start) {
2065 return start <= range->end && end >= range->start;
2067 return start > range->start || end < range->end;
2071 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) {
2072 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2073 meshlink_errno = MESHLINK_EINVAL;
2077 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2080 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2081 if(!mesh || !submesh || !nmemb) {
2082 meshlink_errno = MESHLINK_EINVAL;
2086 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2089 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) {
2090 if(!mesh || !nmemb) {
2091 meshlink_errno = MESHLINK_EINVAL;
2095 struct time_range range = {start, end};
2097 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2100 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2101 if(!mesh || !node) {
2102 meshlink_errno = MESHLINK_EINVAL;
2106 dev_class_t devclass;
2108 pthread_mutex_lock(&mesh->mutex);
2110 devclass = ((node_t *)node)->devclass;
2112 pthread_mutex_unlock(&mesh->mutex);
2117 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2118 if(!mesh || !node) {
2119 meshlink_errno = MESHLINK_EINVAL;
2123 node_t *n = (node_t *)node;
2125 meshlink_submesh_t *s;
2127 s = (meshlink_submesh_t *)n->submesh;
2132 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2133 if(!mesh || !data || !len || !signature || !siglen) {
2134 meshlink_errno = MESHLINK_EINVAL;
2138 if(*siglen < MESHLINK_SIGLEN) {
2139 meshlink_errno = MESHLINK_EINVAL;
2143 pthread_mutex_lock(&mesh->mutex);
2145 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2146 meshlink_errno = MESHLINK_EINTERNAL;
2147 pthread_mutex_unlock(&mesh->mutex);
2151 *siglen = MESHLINK_SIGLEN;
2152 pthread_mutex_unlock(&mesh->mutex);
2156 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2157 if(!mesh || !data || !len || !signature) {
2158 meshlink_errno = MESHLINK_EINVAL;
2162 if(siglen != MESHLINK_SIGLEN) {
2163 meshlink_errno = MESHLINK_EINVAL;
2167 pthread_mutex_lock(&mesh->mutex);
2171 struct node_t *n = (struct node_t *)source;
2173 if(!node_read_public_key(mesh, n)) {
2174 meshlink_errno = MESHLINK_EINTERNAL;
2177 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2180 pthread_mutex_unlock(&mesh->mutex);
2184 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2185 pthread_mutex_lock(&mesh->mutex);
2187 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2190 // TODO: Update invitation key if necessary?
2193 pthread_mutex_unlock(&mesh->mutex);
2195 return mesh->invitation_key;
2198 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2199 if(!mesh || !node || !address) {
2200 meshlink_errno = MESHLINK_EINVAL;
2204 if(!is_valid_hostname(address)) {
2205 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2206 meshlink_errno = MESHLINK_EINVAL;
2210 if(port && !is_valid_port(port)) {
2211 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2212 meshlink_errno = MESHLINK_EINVAL;
2216 char *canonical_address;
2219 xasprintf(&canonical_address, "%s %s", address, port);
2221 canonical_address = xstrdup(address);
2224 pthread_mutex_lock(&mesh->mutex);
2226 node_t *n = (node_t *)node;
2227 free(n->canonical_address);
2228 n->canonical_address = canonical_address;
2230 if(!node_write_config(mesh, n)) {
2231 pthread_mutex_unlock(&mesh->mutex);
2235 pthread_mutex_unlock(&mesh->mutex);
2237 return config_sync(mesh, "current");
2240 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2241 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2244 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2246 meshlink_errno = MESHLINK_EINVAL;
2250 char *address = meshlink_get_external_address(mesh);
2256 bool rval = meshlink_add_address(mesh, address);
2262 int meshlink_get_port(meshlink_handle_t *mesh) {
2264 meshlink_errno = MESHLINK_EINVAL;
2269 meshlink_errno = MESHLINK_EINTERNAL;
2275 pthread_mutex_lock(&mesh->mutex);
2276 port = atoi(mesh->myport);
2277 pthread_mutex_unlock(&mesh->mutex);
2282 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2283 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2284 meshlink_errno = MESHLINK_EINVAL;
2288 if(mesh->myport && port == atoi(mesh->myport)) {
2292 if(!try_bind(port)) {
2293 meshlink_errno = MESHLINK_ENETWORK;
2297 devtool_trybind_probe();
2301 pthread_mutex_lock(&mesh->mutex);
2303 if(mesh->threadstarted) {
2304 meshlink_errno = MESHLINK_EINVAL;
2309 xasprintf(&mesh->myport, "%d", port);
2311 /* Close down the network. This also deletes mesh->self. */
2312 close_network_connections(mesh);
2314 /* Recreate mesh->self. */
2315 mesh->self = new_node();
2316 mesh->self->name = xstrdup(mesh->name);
2317 mesh->self->devclass = mesh->devclass;
2318 mesh->self->session_id = mesh->session_id;
2319 xasprintf(&mesh->myport, "%d", port);
2321 if(!node_read_public_key(mesh, mesh->self)) {
2322 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2323 meshlink_errno = MESHLINK_ESTORAGE;
2324 free_node(mesh->self);
2327 } else if(!setup_network(mesh)) {
2328 meshlink_errno = MESHLINK_ENETWORK;
2332 /* Rebuild our own list of recent addresses */
2333 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2334 add_local_addresses(mesh);
2336 /* Write meshlink.conf with the updated port number */
2337 write_main_config_files(mesh);
2339 rval = config_sync(mesh, "current");
2342 pthread_mutex_unlock(&mesh->mutex);
2344 return rval && meshlink_get_port(mesh) == port;
2347 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2348 mesh->invitation_timeout = timeout;
2351 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2352 meshlink_submesh_t *s = NULL;
2355 meshlink_errno = MESHLINK_EINVAL;
2360 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2363 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2364 meshlink_errno = MESHLINK_EINVAL;
2368 s = (meshlink_submesh_t *)mesh->self->submesh;
2371 pthread_mutex_lock(&mesh->mutex);
2373 // Check validity of the new node's name
2374 if(!check_id(name)) {
2375 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2376 meshlink_errno = MESHLINK_EINVAL;
2377 pthread_mutex_unlock(&mesh->mutex);
2381 // Ensure no host configuration file with that name exists
2382 if(config_exists(mesh, "current", name)) {
2383 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2384 meshlink_errno = MESHLINK_EEXIST;
2385 pthread_mutex_unlock(&mesh->mutex);
2389 // Ensure no other nodes know about this name
2390 if(meshlink_get_node(mesh, name)) {
2391 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2392 meshlink_errno = MESHLINK_EEXIST;
2393 pthread_mutex_unlock(&mesh->mutex);
2397 // Get the local address
2398 char *address = get_my_hostname(mesh, flags);
2401 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2402 meshlink_errno = MESHLINK_ERESOLV;
2403 pthread_mutex_unlock(&mesh->mutex);
2407 if(!refresh_invitation_key(mesh)) {
2408 meshlink_errno = MESHLINK_EINTERNAL;
2409 pthread_mutex_unlock(&mesh->mutex);
2415 // Create a hash of the key.
2416 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2417 sha512(fingerprint, strlen(fingerprint), hash);
2418 b64encode_urlsafe(hash, hash, 18);
2420 // Create a random cookie for this invitation.
2422 randomize(cookie, 18);
2424 // Create a filename that doesn't reveal the cookie itself
2425 char buf[18 + strlen(fingerprint)];
2426 char cookiehash[64];
2427 memcpy(buf, cookie, 18);
2428 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2429 sha512(buf, sizeof(buf), cookiehash);
2430 b64encode_urlsafe(cookiehash, cookiehash, 18);
2432 b64encode_urlsafe(cookie, cookie, 18);
2436 /* Construct the invitation file */
2437 uint8_t outbuf[4096];
2438 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2440 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2441 packmsg_add_str(&inv, name);
2442 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2443 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2445 /* TODO: Add several host config files to bootstrap connections.
2446 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2447 * and are not blacklisted.
2449 config_t configs[5];
2450 memset(configs, 0, sizeof(configs));
2453 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2457 /* Append host config files to the invitation file */
2458 packmsg_add_array(&inv, count);
2460 for(int i = 0; i < count; i++) {
2461 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2462 config_free(&configs[i]);
2465 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2467 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2468 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2469 meshlink_errno = MESHLINK_ESTORAGE;
2470 pthread_mutex_unlock(&mesh->mutex);
2474 // Create an URL from the local address, key hash and cookie
2476 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2479 pthread_mutex_unlock(&mesh->mutex);
2483 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2484 return meshlink_invite_ex(mesh, submesh, name, 0);
2487 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2488 if(!mesh || !invitation) {
2489 meshlink_errno = MESHLINK_EINVAL;
2493 pthread_mutex_lock(&mesh->mutex);
2495 //Before doing meshlink_join make sure we are not connected to another mesh
2496 if(mesh->threadstarted) {
2497 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2498 meshlink_errno = MESHLINK_EINVAL;
2499 pthread_mutex_unlock(&mesh->mutex);
2503 // 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.
2504 if(mesh->nodes->count > 1) {
2505 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2506 meshlink_errno = MESHLINK_EINVAL;
2507 pthread_mutex_unlock(&mesh->mutex);
2511 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2512 char copy[strlen(invitation) + 1];
2513 strcpy(copy, invitation);
2515 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2517 char *slash = strchr(copy, '/');
2525 if(strlen(slash) != 48) {
2529 char *address = copy;
2532 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2536 // Generate a throw-away key for the invitation.
2537 ecdsa_t *key = ecdsa_generate();
2540 meshlink_errno = MESHLINK_EINTERNAL;
2541 pthread_mutex_unlock(&mesh->mutex);
2545 char *b64key = ecdsa_get_base64_public_key(key);
2549 while(address && *address) {
2550 // We allow commas in the address part to support multiple addresses in one invitation URL.
2551 comma = strchr(address, ',');
2557 // Split of the port
2558 port = strrchr(address, ':');
2566 // IPv6 address are enclosed in brackets, per RFC 3986
2567 if(*address == '[') {
2569 char *bracket = strchr(address, ']');
2582 // Connect to the meshlink daemon mentioned in the URL.
2583 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2586 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2587 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2589 if(mesh->sock == -1) {
2590 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2591 meshlink_errno = MESHLINK_ENETWORK;
2595 set_timeout(mesh->sock, 5000);
2597 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2598 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2599 meshlink_errno = MESHLINK_ENETWORK;
2600 closesocket(mesh->sock);
2608 meshlink_errno = MESHLINK_ERESOLV;
2611 if(mesh->sock != -1 || !comma) {
2618 if(mesh->sock == -1) {
2619 pthread_mutex_unlock(&mesh->mutex);
2623 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2625 // Tell him we have an invitation, and give him our throw-away key.
2629 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2630 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2631 closesocket(mesh->sock);
2632 meshlink_errno = MESHLINK_ENETWORK;
2633 pthread_mutex_unlock(&mesh->mutex);
2639 char hisname[4096] = "";
2640 int code, hismajor, hisminor = 0;
2642 if(!recvline(mesh, sizeof(mesh)->line) || sscanf(mesh->line, "%d %s %d.%d", &code, hisname, &hismajor, &hisminor) < 3 || code != 0 || hismajor != PROT_MAJOR || !check_id(hisname) || !recvline(mesh, sizeof(mesh)->line) || !rstrip(mesh->line) || sscanf(mesh->line, "%d ", &code) != 1 || code != ACK || strlen(mesh->line) < 3) {
2643 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2644 closesocket(mesh->sock);
2645 meshlink_errno = MESHLINK_ENETWORK;
2646 pthread_mutex_unlock(&mesh->mutex);
2650 // Check if the hash of the key he gave us matches the hash in the URL.
2651 char *fingerprint = mesh->line + 2;
2654 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2655 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2656 meshlink_errno = MESHLINK_EINTERNAL;
2657 pthread_mutex_unlock(&mesh->mutex);
2661 if(memcmp(hishash, mesh->hash, 18)) {
2662 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2663 meshlink_errno = MESHLINK_EPEER;
2664 pthread_mutex_unlock(&mesh->mutex);
2669 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2672 meshlink_errno = MESHLINK_EINTERNAL;
2673 pthread_mutex_unlock(&mesh->mutex);
2677 // Start an SPTPS session
2678 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2679 meshlink_errno = MESHLINK_EINTERNAL;
2680 pthread_mutex_unlock(&mesh->mutex);
2684 // Feed rest of input buffer to SPTPS
2685 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2686 meshlink_errno = MESHLINK_EPEER;
2687 pthread_mutex_unlock(&mesh->mutex);
2693 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2695 if(errno == EINTR) {
2699 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2700 meshlink_errno = MESHLINK_ENETWORK;
2701 pthread_mutex_unlock(&mesh->mutex);
2705 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2706 meshlink_errno = MESHLINK_EPEER;
2707 pthread_mutex_unlock(&mesh->mutex);
2712 sptps_stop(&mesh->sptps);
2715 closesocket(mesh->sock);
2717 if(!mesh->success) {
2718 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2719 meshlink_errno = MESHLINK_EPEER;
2720 pthread_mutex_unlock(&mesh->mutex);
2724 pthread_mutex_unlock(&mesh->mutex);
2728 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2729 meshlink_errno = MESHLINK_EINVAL;
2730 pthread_mutex_unlock(&mesh->mutex);
2734 char *meshlink_export(meshlink_handle_t *mesh) {
2736 meshlink_errno = MESHLINK_EINVAL;
2740 // Create a config file on the fly.
2743 packmsg_output_t out = {buf, sizeof(buf)};
2744 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2745 packmsg_add_str(&out, mesh->name);
2746 packmsg_add_str(&out, CORE_MESH);
2748 pthread_mutex_lock(&mesh->mutex);
2750 packmsg_add_int32(&out, mesh->self->devclass);
2751 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2752 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2753 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2757 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2758 if(mesh->self->recent[i].sa.sa_family) {
2765 packmsg_add_array(&out, count);
2767 for(uint32_t i = 0; i < count; i++) {
2768 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2771 packmsg_add_int64(&out, 0);
2772 packmsg_add_int64(&out, 0);
2774 pthread_mutex_unlock(&mesh->mutex);
2776 if(!packmsg_output_ok(&out)) {
2777 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2778 meshlink_errno = MESHLINK_EINTERNAL;
2782 // Prepare a base64-encoded packmsg array containing our config file
2784 uint32_t len = packmsg_output_size(&out, buf);
2785 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2786 uint8_t *buf2 = xmalloc(len2);
2787 packmsg_output_t out2 = {buf2, len2};
2788 packmsg_add_array(&out2, 1);
2789 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2791 if(!packmsg_output_ok(&out2)) {
2792 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2793 meshlink_errno = MESHLINK_EINTERNAL;
2798 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2800 return (char *)buf2;
2803 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2804 if(!mesh || !data) {
2805 meshlink_errno = MESHLINK_EINVAL;
2809 size_t datalen = strlen(data);
2810 uint8_t *buf = xmalloc(datalen);
2811 int buflen = b64decode(data, buf, datalen);
2814 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2815 meshlink_errno = MESHLINK_EPEER;
2819 packmsg_input_t in = {buf, buflen};
2820 uint32_t count = packmsg_get_array(&in);
2823 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2824 meshlink_errno = MESHLINK_EPEER;
2828 pthread_mutex_lock(&mesh->mutex);
2832 uint32_t len = packmsg_get_bin_raw(&in, &data);
2838 packmsg_input_t in2 = {data, len};
2839 uint32_t version = packmsg_get_uint32(&in2);
2840 char *name = packmsg_get_str_dup(&in2);
2842 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2844 packmsg_input_invalidate(&in);
2848 if(!check_id(name)) {
2853 node_t *n = lookup_node(mesh, name);
2856 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2864 config_t config = {data, len};
2866 if(!node_read_from_config(mesh, n, &config)) {
2868 packmsg_input_invalidate(&in);
2872 if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
2880 pthread_mutex_unlock(&mesh->mutex);
2884 if(!packmsg_done(&in)) {
2885 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2886 meshlink_errno = MESHLINK_EPEER;
2890 if(!config_sync(mesh, "current")) {
2897 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
2898 if(n == mesh->self) {
2899 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
2900 meshlink_errno = MESHLINK_EINVAL;
2904 if(n->status.blacklisted) {
2905 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
2909 n->status.blacklisted = true;
2911 /* Immediately shut down any connections we have with the blacklisted node.
2912 * We can't call terminate_connection(), because we might be called from a callback function.
2914 for list_each(connection_t, c, mesh->connections) {
2916 shutdown(c->socket, SHUT_RDWR);
2920 utcp_abort_all_connections(n->utcp);
2926 n->status.udp_confirmed = false;
2928 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
2929 * manually call the status callback if necessary.
2931 if(n->status.reachable && mesh->node_status_cb) {
2932 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
2935 return node_write_config(mesh, n) && config_sync(mesh, "current");
2938 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2939 if(!mesh || !node) {
2940 meshlink_errno = MESHLINK_EINVAL;
2944 pthread_mutex_lock(&mesh->mutex);
2946 if(!blacklist(mesh, (node_t *)node)) {
2947 pthread_mutex_unlock(&mesh->mutex);
2951 pthread_mutex_unlock(&mesh->mutex);
2953 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2957 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
2958 if(!mesh || !name) {
2959 meshlink_errno = MESHLINK_EINVAL;
2963 pthread_mutex_lock(&mesh->mutex);
2965 node_t *n = lookup_node(mesh, (char *)name);
2969 n->name = xstrdup(name);
2973 if(!blacklist(mesh, (node_t *)n)) {
2974 pthread_mutex_unlock(&mesh->mutex);
2978 pthread_mutex_unlock(&mesh->mutex);
2980 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
2984 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
2985 if(n == mesh->self) {
2986 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
2987 meshlink_errno = MESHLINK_EINVAL;
2991 if(!n->status.blacklisted) {
2992 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
2996 n->status.blacklisted = false;
2998 if(n->status.reachable) {
2999 update_node_status(mesh, n);
3002 return node_write_config(mesh, n) && config_sync(mesh, "current");
3005 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3006 if(!mesh || !node) {
3007 meshlink_errno = MESHLINK_EINVAL;
3011 pthread_mutex_lock(&mesh->mutex);
3013 if(!whitelist(mesh, (node_t *)node)) {
3014 pthread_mutex_unlock(&mesh->mutex);
3018 pthread_mutex_unlock(&mesh->mutex);
3020 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3024 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3025 if(!mesh || !name) {
3026 meshlink_errno = MESHLINK_EINVAL;
3030 pthread_mutex_lock(&mesh->mutex);
3032 node_t *n = lookup_node(mesh, (char *)name);
3036 n->name = xstrdup(name);
3040 if(!whitelist(mesh, (node_t *)n)) {
3041 pthread_mutex_unlock(&mesh->mutex);
3045 pthread_mutex_unlock(&mesh->mutex);
3047 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3051 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3052 mesh->default_blacklist = blacklist;
3055 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3056 if(!mesh || !node) {
3057 meshlink_errno = MESHLINK_EINVAL;
3061 node_t *n = (node_t *)node;
3063 pthread_mutex_lock(&mesh->mutex);
3065 /* Check that the node is not reachable */
3066 if(n->status.reachable || n->connection) {
3067 pthread_mutex_unlock(&mesh->mutex);
3068 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3072 /* Check that we don't have any active UTCP connections */
3073 if(n->utcp && utcp_is_active(n->utcp)) {
3074 pthread_mutex_unlock(&mesh->mutex);
3075 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3079 /* Check that we have no active connections to this node */
3080 for list_each(connection_t, c, mesh->connections) {
3082 pthread_mutex_unlock(&mesh->mutex);
3083 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3088 /* Remove any pending outgoings to this node */
3089 if(mesh->outgoings) {
3090 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3091 if(outgoing->node == n) {
3092 list_delete_node(mesh->outgoings, node);
3097 /* Delete the config file for this node */
3098 if(!config_delete(mesh, "current", n->name)) {
3099 pthread_mutex_unlock(&mesh->mutex);
3103 /* Delete the node struct and any remaining edges referencing this node */
3106 pthread_mutex_unlock(&mesh->mutex);
3108 return config_sync(mesh, "current");
3111 /* Hint that a hostname may be found at an address
3112 * See header file for detailed comment.
3114 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3115 if(!mesh || !node || !addr) {
3116 meshlink_errno = EINVAL;
3120 pthread_mutex_lock(&mesh->mutex);
3122 node_t *n = (node_t *)node;
3124 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3125 if(!node_write_config(mesh, n)) {
3126 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3130 pthread_mutex_unlock(&mesh->mutex);
3131 // @TODO do we want to fire off a connection attempt right away?
3134 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3136 node_t *n = utcp->priv;
3137 meshlink_handle_t *mesh = n->mesh;
3138 return mesh->channel_accept_cb;
3141 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3143 if(aio->cb.buffer) {
3144 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3148 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3153 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3154 meshlink_channel_t *channel = connection->priv;
3160 node_t *n = channel->node;
3161 meshlink_handle_t *mesh = n->mesh;
3163 if(n->status.destroyed) {
3164 meshlink_channel_close(mesh, channel);
3168 const char *p = data;
3171 while(channel->aio_receive) {
3172 meshlink_aio_buffer_t *aio = channel->aio_receive;
3173 size_t todo = aio->len - aio->done;
3180 memcpy((char *)aio->data + aio->done, p, todo);
3182 ssize_t result = write(aio->fd, p, todo);
3191 if(aio->done == aio->len) {
3192 channel->aio_receive = aio->next;
3193 aio_signal(mesh, channel, aio);
3205 if(channel->receive_cb) {
3206 channel->receive_cb(mesh, channel, p, left);
3212 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3213 node_t *n = utcp_connection->utcp->priv;
3219 meshlink_handle_t *mesh = n->mesh;
3221 if(!mesh->channel_accept_cb) {
3225 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3227 channel->c = utcp_connection;
3229 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3230 utcp_accept(utcp_connection, channel_recv, channel);
3236 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3237 node_t *n = utcp->priv;
3239 if(n->status.destroyed) {
3243 meshlink_handle_t *mesh = n->mesh;
3244 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3247 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3248 if(!mesh || !channel) {
3249 meshlink_errno = MESHLINK_EINVAL;
3253 channel->receive_cb = cb;
3256 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3258 node_t *n = (node_t *)source;
3264 utcp_recv(n->utcp, data, len);
3267 static void channel_poll(struct utcp_connection *connection, size_t len) {
3268 meshlink_channel_t *channel = connection->priv;
3274 node_t *n = channel->node;
3275 meshlink_handle_t *mesh = n->mesh;
3276 meshlink_aio_buffer_t *aio = channel->aio_send;
3279 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3280 size_t left = aio->len - aio->done;
3288 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3291 size_t todo = utcp_get_sndbuf_free(connection);
3297 if(todo > sizeof(buf)) {
3301 ssize_t result = read(aio->fd, buf, todo);
3304 sent = utcp_send(connection, buf, result);
3314 /* If the buffer is now completely sent, call the callback and dispose of it. */
3315 if(aio->done >= aio->len) {
3316 channel->aio_send = aio->next;
3317 aio_signal(mesh, channel, aio);
3321 if(channel->poll_cb) {
3322 channel->poll_cb(mesh, channel, len);
3324 utcp_set_poll_cb(connection, NULL);
3329 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3330 if(!mesh || !channel) {
3331 meshlink_errno = MESHLINK_EINVAL;
3335 pthread_mutex_lock(&mesh->mutex);
3336 channel->poll_cb = cb;
3337 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3338 pthread_mutex_unlock(&mesh->mutex);
3341 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3343 meshlink_errno = MESHLINK_EINVAL;
3347 pthread_mutex_lock(&mesh->mutex);
3348 mesh->channel_accept_cb = cb;
3349 mesh->receive_cb = channel_receive;
3351 for splay_each(node_t, n, mesh->nodes) {
3352 if(!n->utcp && n != mesh->self) {
3353 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3357 pthread_mutex_unlock(&mesh->mutex);
3360 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3364 meshlink_errno = MESHLINK_EINVAL;
3368 pthread_mutex_lock(&mesh->mutex);
3369 utcp_set_sndbuf(channel->c, size);
3370 pthread_mutex_unlock(&mesh->mutex);
3373 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3377 meshlink_errno = MESHLINK_EINVAL;
3381 pthread_mutex_lock(&mesh->mutex);
3382 utcp_set_rcvbuf(channel->c, size);
3383 pthread_mutex_unlock(&mesh->mutex);
3386 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) {
3388 abort(); // TODO: handle non-NULL data
3391 if(!mesh || !node) {
3392 meshlink_errno = MESHLINK_EINVAL;
3396 pthread_mutex_lock(&mesh->mutex);
3398 node_t *n = (node_t *)node;
3401 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3402 mesh->receive_cb = channel_receive;
3405 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3406 pthread_mutex_unlock(&mesh->mutex);
3411 if(n->status.blacklisted) {
3412 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3413 meshlink_errno = MESHLINK_EBLACKLISTED;
3414 pthread_mutex_unlock(&mesh->mutex);
3418 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3420 channel->receive_cb = cb;
3423 channel->priv = (void *)data;
3426 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3428 pthread_mutex_unlock(&mesh->mutex);
3431 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3439 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) {
3440 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3443 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3444 if(!mesh || !channel) {
3445 meshlink_errno = MESHLINK_EINVAL;
3449 pthread_mutex_lock(&mesh->mutex);
3450 utcp_shutdown(channel->c, direction);
3451 pthread_mutex_unlock(&mesh->mutex);
3454 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3455 if(!mesh || !channel) {
3456 meshlink_errno = MESHLINK_EINVAL;
3460 pthread_mutex_lock(&mesh->mutex);
3462 utcp_close(channel->c);
3464 /* Clean up any outstanding AIO buffers. */
3465 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3467 aio_signal(mesh, channel, aio);
3471 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3473 aio_signal(mesh, channel, aio);
3477 pthread_mutex_unlock(&mesh->mutex);
3482 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3483 if(!mesh || !channel) {
3484 meshlink_errno = MESHLINK_EINVAL;
3493 meshlink_errno = MESHLINK_EINVAL;
3497 // TODO: more finegrained locking.
3498 // Ideally we want to put the data into the UTCP connection's send buffer.
3499 // Then, preferably only if there is room in the receiver window,
3500 // kick the meshlink thread to go send packets.
3504 pthread_mutex_lock(&mesh->mutex);
3506 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3507 if(channel->aio_send) {
3510 retval = utcp_send(channel->c, data, len);
3513 pthread_mutex_unlock(&mesh->mutex);
3516 meshlink_errno = MESHLINK_ENETWORK;
3522 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) {
3523 if(!mesh || !channel) {
3524 meshlink_errno = MESHLINK_EINVAL;
3529 meshlink_errno = MESHLINK_EINVAL;
3533 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3536 aio->cb.buffer = cb;
3539 pthread_mutex_lock(&mesh->mutex);
3541 /* Append the AIO buffer descriptor to the end of the chain */
3542 meshlink_aio_buffer_t **p = &channel->aio_send;
3550 /* Ensure the poll callback is set, and call it right now to push data if possible */
3551 utcp_set_poll_cb(channel->c, channel_poll);
3552 channel_poll(channel->c, len);
3554 pthread_mutex_unlock(&mesh->mutex);
3559 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) {
3560 if(!mesh || !channel) {
3561 meshlink_errno = MESHLINK_EINVAL;
3565 if(!len || fd == -1) {
3566 meshlink_errno = MESHLINK_EINVAL;
3570 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3576 pthread_mutex_lock(&mesh->mutex);
3578 /* Append the AIO buffer descriptor to the end of the chain */
3579 meshlink_aio_buffer_t **p = &channel->aio_send;
3587 /* Ensure the poll callback is set, and call it right now to push data if possible */
3588 utcp_set_poll_cb(channel->c, channel_poll);
3589 channel_poll(channel->c, len);
3591 pthread_mutex_unlock(&mesh->mutex);
3596 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) {
3597 if(!mesh || !channel) {
3598 meshlink_errno = MESHLINK_EINVAL;
3603 meshlink_errno = MESHLINK_EINVAL;
3607 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3610 aio->cb.buffer = cb;
3613 pthread_mutex_lock(&mesh->mutex);
3615 /* Append the AIO buffer descriptor to the end of the chain */
3616 meshlink_aio_buffer_t **p = &channel->aio_receive;
3624 pthread_mutex_unlock(&mesh->mutex);
3629 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) {
3630 if(!mesh || !channel) {
3631 meshlink_errno = MESHLINK_EINVAL;
3635 if(!len || fd == -1) {
3636 meshlink_errno = MESHLINK_EINVAL;
3640 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3646 pthread_mutex_lock(&mesh->mutex);
3648 /* Append the AIO buffer descriptor to the end of the chain */
3649 meshlink_aio_buffer_t **p = &channel->aio_receive;
3657 pthread_mutex_unlock(&mesh->mutex);
3662 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3663 if(!mesh || !channel) {
3664 meshlink_errno = MESHLINK_EINVAL;
3668 return channel->c->flags;
3671 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3672 if(!mesh || !channel) {
3673 meshlink_errno = MESHLINK_EINVAL;
3677 return utcp_get_sendq(channel->c);
3680 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3681 if(!mesh || !channel) {
3682 meshlink_errno = MESHLINK_EINVAL;
3686 return utcp_get_recvq(channel->c);
3689 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3690 if(!mesh || !node) {
3691 meshlink_errno = MESHLINK_EINVAL;
3695 node_t *n = (node_t *)node;
3697 pthread_mutex_lock(&mesh->mutex);
3700 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3703 utcp_set_user_timeout(n->utcp, timeout);
3705 pthread_mutex_unlock(&mesh->mutex);
3708 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3709 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3710 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3713 if(mesh->node_status_cb) {
3714 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3717 if(mesh->node_pmtu_cb) {
3718 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3722 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3723 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3724 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3728 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3729 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3733 n->status.duplicate = true;
3734 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3737 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3741 meshlink_errno = MESHLINK_EINVAL;
3745 pthread_mutex_lock(&mesh->mutex);
3747 if(mesh->discovery == enable) {
3751 if(mesh->threadstarted) {
3753 discovery_start(mesh);
3755 discovery_stop(mesh);
3759 mesh->discovery = enable;
3762 pthread_mutex_unlock(&mesh->mutex);
3766 meshlink_errno = MESHLINK_ENOTSUP;
3770 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3771 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3772 meshlink_errno = EINVAL;
3776 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3777 meshlink_errno = EINVAL;
3781 pthread_mutex_lock(&mesh->mutex);
3782 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3783 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3784 pthread_mutex_unlock(&mesh->mutex);
3787 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3790 if(!mesh->connections || !mesh->loop.running) {
3797 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3798 // We should only call the callback function if we are in the background thread.
3799 if(!mesh->error_cb) {
3803 if(!mesh->threadstarted) {
3807 if(mesh->thread == pthread_self()) {
3808 mesh->error_cb(mesh, meshlink_errno);
3813 static void __attribute__((constructor)) meshlink_init(void) {
3817 static void __attribute__((destructor)) meshlink_exit(void) {