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"
43 #define MSG_NOSIGNAL 0
45 __thread meshlink_errno_t meshlink_errno;
46 meshlink_log_cb_t global_log_cb;
47 meshlink_log_level_t global_log_level;
49 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
51 static int rstrip(char *value) {
52 int len = strlen(value);
54 while(len && strchr("\t\r\n ", value[len - 1])) {
61 static void get_canonical_address(node_t *n, char **hostname, char **port) {
62 if(!n->canonical_address) {
66 *hostname = xstrdup(n->canonical_address);
67 char *space = strchr(*hostname, ' ');
71 *port = xstrdup(space);
75 static bool is_valid_hostname(const char *hostname) {
80 for(const char *p = hostname; *p; p++) {
81 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
89 static bool is_valid_port(const char *port) {
96 unsigned long int result = strtoul(port, &end, 10);
97 return result && result < 65536 && !*end;
100 for(const char *p = port; *p; p++) {
101 if(!(isalnum(*p) || *p == '-')) {
109 static void set_timeout(int sock, int timeout) {
114 tv.tv_sec = timeout / 1000;
115 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
117 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
118 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
121 struct socket_in_netns_params {
130 static void *socket_in_netns_thread(void *arg) {
131 struct socket_in_netns_params *params = arg;
133 if(setns(params->netns, CLONE_NEWNET) == -1) {
134 meshlink_errno = MESHLINK_EINVAL;
138 params->fd = socket(params->domain, params->type, params->protocol);
144 static int socket_in_netns(int domain, int type, int protocol, int netns) {
146 return socket(domain, type, protocol);
150 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
154 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
155 pthread_join(thr, NULL);
165 // Find out what local address a socket would use if we connect to the given address.
166 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
167 // of both endpoints, but this will actually not send any UDP packet.
168 static bool getlocaladdr(char *destaddr, sockaddr_t *sa, socklen_t *salen, int netns) {
169 struct addrinfo *rai = NULL;
170 const struct addrinfo hint = {
171 .ai_family = AF_UNSPEC,
172 .ai_socktype = SOCK_DGRAM,
173 .ai_protocol = IPPROTO_UDP,
176 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
180 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
187 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
195 if(getsockname(sock, &sa->sa, salen)) {
204 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
206 socklen_t salen = sizeof(sa);
208 if(!getlocaladdr(destaddr, &sa, &salen, netns)) {
212 if(getnameinfo(&sa.sa, salen, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
219 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
220 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
223 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
224 char *hostname = NULL;
226 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
227 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
228 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
231 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
232 if(family != AF_UNSPEC && aip->ai_family != family) {
236 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
239 set_timeout(s, 5000);
241 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
248 send(s, request, sizeof(request) - 1, 0);
249 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
254 if(line[len - 1] == '\n') {
258 char *p = strrchr(line, '\n');
261 hostname = xstrdup(p + 1);
277 // Check that the hostname is reasonable
278 if(hostname && !is_valid_hostname(hostname)) {
284 meshlink_errno = MESHLINK_ERESOLV;
290 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
293 // Determine address of the local interface used for outgoing connections.
294 char localaddr[NI_MAXHOST];
295 bool success = false;
297 if(family == AF_INET) {
298 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
299 } else if(family == AF_INET6) {
300 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
304 meshlink_errno = MESHLINK_ENETWORK;
308 return xstrdup(localaddr);
311 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
312 for(int i = 0; i < n; i++) {
317 // Ignore duplicate hostnames
320 for(int j = 0; j < i; j++) {
325 if(strcmp(host[i], host[j])) {
329 if(strcmp(port[i], port[j])) {
337 if(found || !is_valid_hostname(host[i])) {
347 // This gets the hostname part for use in invitation URLs
348 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
349 char *hostname[4] = {NULL};
350 char *port[4] = {NULL};
351 char *hostport = NULL;
353 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
354 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
357 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
358 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
361 // Add local addresses if requested
362 if(flags & MESHLINK_INVITE_LOCAL) {
363 if(flags & MESHLINK_INVITE_IPV4) {
364 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
367 if(flags & MESHLINK_INVITE_IPV6) {
368 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
372 // Add public/canonical addresses if requested
373 if(flags & MESHLINK_INVITE_PUBLIC) {
374 // Try the CanonicalAddress first
375 get_canonical_address(mesh->self, &hostname[2], &port[2]);
378 if(flags & MESHLINK_INVITE_IPV4) {
379 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
382 if(flags & MESHLINK_INVITE_IPV6) {
383 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
388 for(int i = 0; i < 4; i++) {
389 // Ensure we always have a port number
390 if(hostname[i] && !port[i]) {
391 port[i] = xstrdup(mesh->myport);
395 remove_duplicate_hostnames(hostname, port, 4);
397 // Resolve the hostnames
398 for(int i = 0; i < 4; i++) {
403 // Convert what we have to a sockaddr
404 struct addrinfo *ai_in, *ai_out;
405 struct addrinfo hint = {
406 .ai_family = AF_UNSPEC,
407 .ai_flags = AI_NUMERICSERV,
408 .ai_socktype = SOCK_STREAM,
410 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
416 // Remember the address
417 node_add_recent_address(mesh, mesh->self, (sockaddr_t *)ai_in->ai_addr);
419 if(flags & MESHLINK_INVITE_NUMERIC) {
420 // We don't need to do any further conversion
425 // Convert it to a hostname
426 char resolved_host[NI_MAXHOST];
427 char resolved_port[NI_MAXSERV];
428 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
430 if(err || !is_valid_hostname(resolved_host)) {
435 // Convert the hostname back to a sockaddr
436 hint.ai_family = ai_in->ai_family;
437 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
444 // Check if it's still the same sockaddr
445 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
447 freeaddrinfo(ai_out);
451 // Yes: replace the hostname with the resolved one
453 hostname[i] = xstrdup(resolved_host);
456 freeaddrinfo(ai_out);
459 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
460 remove_duplicate_hostnames(hostname, port, 4);
462 // Concatenate all unique address to the hostport string
463 for(int i = 0; i < 4; i++) {
468 // Append the address to the hostport string
470 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
472 hostport = newhostport;
481 static bool try_bind(int port) {
482 struct addrinfo *ai = NULL;
483 struct addrinfo hint = {
484 .ai_flags = AI_PASSIVE,
485 .ai_family = AF_UNSPEC,
486 .ai_socktype = SOCK_STREAM,
487 .ai_protocol = IPPROTO_TCP,
491 snprintf(portstr, sizeof(portstr), "%d", port);
493 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
498 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
499 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
506 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
519 static int check_port(meshlink_handle_t *mesh) {
520 for(int i = 0; i < 1000; i++) {
521 int port = 0x1000 + prng(mesh, 0x8000);
525 xasprintf(&mesh->myport, "%d", port);
530 meshlink_errno = MESHLINK_ENETWORK;
531 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
535 static bool write_main_config_files(meshlink_handle_t *mesh) {
536 if(!mesh->confbase) {
542 /* Write the main config file */
543 packmsg_output_t out = {buf, sizeof buf};
545 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
546 packmsg_add_str(&out, mesh->name);
547 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
548 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
549 packmsg_add_uint16(&out, atoi(mesh->myport));
551 if(!packmsg_output_ok(&out)) {
555 config_t config = {buf, packmsg_output_size(&out, buf)};
557 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
561 /* Write our own host config file */
562 if(!node_write_config(mesh, mesh->self)) {
569 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
570 packmsg_input_t in = {buf, len};
571 uint32_t version = packmsg_get_uint32(&in);
573 if(version != MESHLINK_INVITATION_VERSION) {
574 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
578 char *name = packmsg_get_str_dup(&in);
579 packmsg_skip_element(&in); /* submesh */
580 dev_class_t devclass = packmsg_get_int32(&in);
581 uint32_t count = packmsg_get_array(&in);
584 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
588 if(!check_id(name)) {
589 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
595 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
601 free(mesh->self->name);
603 mesh->self->name = xstrdup(name);
604 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
606 // Initialize configuration directory
607 if(!config_init(mesh, "current")) {
611 if(!write_main_config_files(mesh)) {
615 // Write host config files
616 for(uint32_t i = 0; i < count; i++) {
618 uint32_t len = packmsg_get_bin_raw(&in, &data);
621 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
625 packmsg_input_t in2 = {data, len};
626 uint32_t version = packmsg_get_uint32(&in2);
627 char *name = packmsg_get_str_dup(&in2);
629 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
631 packmsg_input_invalidate(&in);
635 if(!check_id(name)) {
640 if(!strcmp(name, mesh->name)) {
641 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
643 meshlink_errno = MESHLINK_EPEER;
647 node_t *n = new_node();
650 config_t config = {data, len};
652 if(!node_read_from_config(mesh, n, &config)) {
654 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
655 meshlink_errno = MESHLINK_EPEER;
660 /* The first host config file is of the inviter itself;
661 * remember the address we are currently using for the invitation connection.
664 socklen_t salen = sizeof(sa);
666 if(getpeername(mesh->sock, &sa.sa, &salen) == 0) {
667 node_add_recent_address(mesh, n, &sa);
671 if(!node_write_config(mesh, n)) {
679 /* Ensure the configuration directory metadata is on disk */
680 if(!config_sync(mesh, "current") || !sync_path(mesh->confbase)) {
684 sptps_send_record(&mesh->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
686 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
691 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
693 meshlink_handle_t *mesh = handle;
694 const char *ptr = data;
697 int result = send(mesh->sock, ptr, len, 0);
699 if(result == -1 && errno == EINTR) {
701 } else if(result <= 0) {
712 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
713 meshlink_handle_t *mesh = handle;
716 case SPTPS_HANDSHAKE:
717 return sptps_send_record(&mesh->sptps, 0, mesh->cookie, sizeof(mesh)->cookie);
720 return finalize_join(mesh, msg, len);
723 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
724 shutdown(mesh->sock, SHUT_RDWR);
725 mesh->success = true;
735 static bool recvline(meshlink_handle_t *mesh, size_t len) {
736 char *newline = NULL;
742 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
743 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
745 if(result == -1 && errno == EINTR) {
747 } else if(result <= 0) {
751 mesh->blen += result;
754 if((size_t)(newline - mesh->buffer) >= len) {
758 len = newline - mesh->buffer;
760 memcpy(mesh->line, mesh->buffer, len);
762 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
763 mesh->blen -= len + 1;
768 static bool sendline(int fd, char *format, ...) {
774 va_start(ap, format);
775 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
778 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
786 int result = send(fd, p, blen, MSG_NOSIGNAL);
788 if(result == -1 && errno == EINTR) {
790 } else if(result <= 0) {
801 static const char *errstr[] = {
802 [MESHLINK_OK] = "No error",
803 [MESHLINK_EINVAL] = "Invalid argument",
804 [MESHLINK_ENOMEM] = "Out of memory",
805 [MESHLINK_ENOENT] = "No such node",
806 [MESHLINK_EEXIST] = "Node already exists",
807 [MESHLINK_EINTERNAL] = "Internal error",
808 [MESHLINK_ERESOLV] = "Could not resolve hostname",
809 [MESHLINK_ESTORAGE] = "Storage error",
810 [MESHLINK_ENETWORK] = "Network error",
811 [MESHLINK_EPEER] = "Error communicating with peer",
812 [MESHLINK_ENOTSUP] = "Operation not supported",
813 [MESHLINK_EBUSY] = "MeshLink instance already in use",
814 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
817 const char *meshlink_strerror(meshlink_errno_t err) {
818 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
819 return "Invalid error code";
825 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
826 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
828 mesh->private_key = ecdsa_generate();
829 mesh->invitation_key = ecdsa_generate();
831 if(!mesh->private_key || !mesh->invitation_key) {
832 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
833 meshlink_errno = MESHLINK_EINTERNAL;
837 logger(mesh, MESHLINK_DEBUG, "Done.\n");
842 static struct timeval idle(event_loop_t *loop, void *data) {
844 meshlink_handle_t *mesh = data;
845 struct timeval t, tmin = {3600, 0};
847 for splay_each(node_t, n, mesh->nodes) {
852 t = utcp_timeout(n->utcp);
854 if(timercmp(&t, &tmin, <)) {
862 // Get our local address(es) by simulating connecting to an Internet host.
863 static void add_local_addresses(meshlink_handle_t *mesh) {
865 sa.storage.ss_family = AF_UNKNOWN;
866 socklen_t salen = sizeof(sa);
870 if(getlocaladdr("93.184.216.34", &sa, &salen, mesh->netns)) {
871 sa.in.sin_port = ntohs(atoi(mesh->myport));
872 node_add_recent_address(mesh, mesh->self, &sa);
879 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", &sa, &salen, mesh->netns)) {
880 sa.in6.sin6_port = ntohs(atoi(mesh->myport));
881 node_add_recent_address(mesh, mesh->self, &sa);
885 static bool meshlink_setup(meshlink_handle_t *mesh) {
886 if(!config_destroy(mesh->confbase, "new")) {
887 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/new: %s\n", mesh->confbase, strerror(errno));
888 meshlink_errno = MESHLINK_ESTORAGE;
892 if(!config_destroy(mesh->confbase, "old")) {
893 logger(mesh, MESHLINK_ERROR, "Could not delete configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
894 meshlink_errno = MESHLINK_ESTORAGE;
898 if(!config_init(mesh, "current")) {
899 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
900 meshlink_errno = MESHLINK_ESTORAGE;
904 if(!ecdsa_keygen(mesh)) {
905 meshlink_errno = MESHLINK_EINTERNAL;
909 if(check_port(mesh) == 0) {
910 meshlink_errno = MESHLINK_ENETWORK;
914 /* Create a node for ourself */
916 mesh->self = new_node();
917 mesh->self->name = xstrdup(mesh->name);
918 mesh->self->devclass = mesh->devclass;
919 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
920 mesh->self->session_id = mesh->session_id;
922 if(!write_main_config_files(mesh)) {
923 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
924 meshlink_errno = MESHLINK_ESTORAGE;
928 /* Ensure the configuration directory metadata is on disk */
929 if(!config_sync(mesh, "current")) {
936 static bool meshlink_read_config(meshlink_handle_t *mesh) {
939 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
940 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
944 packmsg_input_t in = {config.buf, config.len};
945 const void *private_key;
946 const void *invitation_key;
948 uint32_t version = packmsg_get_uint32(&in);
949 char *name = packmsg_get_str_dup(&in);
950 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
951 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
952 uint16_t myport = packmsg_get_uint16(&in);
954 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
955 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
957 config_free(&config);
964 if(mesh->name && strcmp(mesh->name, name)) {
965 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
966 meshlink_errno = MESHLINK_ESTORAGE;
968 config_free(&config);
976 xasprintf(&mesh->myport, "%u", myport);
977 mesh->private_key = ecdsa_set_private_key(private_key);
978 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
979 config_free(&config);
981 /* Create a node for ourself and read our host configuration file */
983 mesh->self = new_node();
984 mesh->self->name = xstrdup(name);
985 mesh->self->devclass = mesh->devclass;
986 mesh->self->session_id = mesh->session_id;
988 if(!node_read_public_key(mesh, mesh->self)) {
989 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
990 meshlink_errno = MESHLINK_ESTORAGE;
991 free_node(mesh->self);
1000 static void *setup_network_in_netns_thread(void *arg) {
1001 meshlink_handle_t *mesh = arg;
1003 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1007 bool success = setup_network(mesh);
1008 add_local_addresses(mesh);
1009 return success ? arg : NULL;
1011 #endif // HAVE_SETNS
1013 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1014 if(!confbase || !*confbase) {
1015 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1016 meshlink_errno = MESHLINK_EINVAL;
1020 if(!appname || !*appname) {
1021 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1022 meshlink_errno = MESHLINK_EINVAL;
1026 if(strchr(appname, ' ')) {
1027 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1028 meshlink_errno = MESHLINK_EINVAL;
1032 if(!name || !*name) {
1033 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1034 meshlink_errno = MESHLINK_EINVAL;
1038 if(!check_id(name)) {
1039 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1040 meshlink_errno = MESHLINK_EINVAL;
1044 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1045 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1046 meshlink_errno = MESHLINK_EINVAL;
1050 meshlink_open_params_t *params = xzalloc(sizeof * params);
1052 params->confbase = xstrdup(confbase);
1053 params->name = xstrdup(name);
1054 params->appname = xstrdup(appname);
1055 params->devclass = devclass;
1061 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1063 meshlink_errno = MESHLINK_EINVAL;
1067 params->netns = netns;
1072 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1074 meshlink_errno = MESHLINK_EINVAL;
1078 if((!key && keylen) || (key && !keylen)) {
1079 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1080 meshlink_errno = MESHLINK_EINVAL;
1085 params->keylen = keylen;
1090 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1091 if(!mesh || !new_key || !new_keylen) {
1092 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1093 meshlink_errno = MESHLINK_EINVAL;
1097 pthread_mutex_lock(&mesh->mutex);
1099 // Create hash for the new key
1100 void *new_config_key;
1101 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1103 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1104 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1105 meshlink_errno = MESHLINK_EINTERNAL;
1106 pthread_mutex_unlock(&mesh->mutex);
1110 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1112 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1113 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1114 meshlink_errno = MESHLINK_ESTORAGE;
1115 pthread_mutex_unlock(&mesh->mutex);
1119 devtool_keyrotate_probe(1);
1121 // Rename confbase/current/ to confbase/old
1123 if(!config_rename(mesh, "current", "old")) {
1124 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1125 meshlink_errno = MESHLINK_ESTORAGE;
1126 pthread_mutex_unlock(&mesh->mutex);
1130 devtool_keyrotate_probe(2);
1132 // Rename confbase/new/ to confbase/current
1134 if(!config_rename(mesh, "new", "current")) {
1135 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1136 meshlink_errno = MESHLINK_ESTORAGE;
1137 pthread_mutex_unlock(&mesh->mutex);
1141 devtool_keyrotate_probe(3);
1143 // Cleanup the "old" confbase sub-directory
1145 if(!config_destroy(mesh->confbase, "old")) {
1146 pthread_mutex_unlock(&mesh->mutex);
1150 // Change the mesh handle key with new key
1152 free(mesh->config_key);
1153 mesh->config_key = new_config_key;
1155 pthread_mutex_unlock(&mesh->mutex);
1160 void meshlink_open_params_free(meshlink_open_params_t *params) {
1162 meshlink_errno = MESHLINK_EINVAL;
1166 free(params->confbase);
1168 free(params->appname);
1173 /// Device class traits
1174 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1175 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1176 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1177 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1178 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1181 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1182 if(!confbase || !*confbase) {
1183 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1184 meshlink_errno = MESHLINK_EINVAL;
1188 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1189 meshlink_open_params_t params;
1190 memset(¶ms, 0, sizeof(params));
1192 params.confbase = (char *)confbase;
1193 params.name = (char *)name;
1194 params.appname = (char *)appname;
1195 params.devclass = devclass;
1198 return meshlink_open_ex(¶ms);
1201 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) {
1202 if(!confbase || !*confbase) {
1203 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1204 meshlink_errno = MESHLINK_EINVAL;
1208 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1209 meshlink_open_params_t params;
1210 memset(¶ms, 0, sizeof(params));
1212 params.confbase = (char *)confbase;
1213 params.name = (char *)name;
1214 params.appname = (char *)appname;
1215 params.devclass = devclass;
1218 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1222 return meshlink_open_ex(¶ms);
1225 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1226 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1227 meshlink_open_params_t params;
1228 memset(¶ms, 0, sizeof(params));
1230 params.name = (char *)name;
1231 params.appname = (char *)appname;
1232 params.devclass = devclass;
1235 return meshlink_open_ex(¶ms);
1238 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1239 // Validate arguments provided by the application
1240 bool usingname = false;
1242 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1244 if(!params->appname || !*params->appname) {
1245 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1246 meshlink_errno = MESHLINK_EINVAL;
1250 if(strchr(params->appname, ' ')) {
1251 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1252 meshlink_errno = MESHLINK_EINVAL;
1256 if(!params->name || !*params->name) {
1257 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1259 } else { //check name only if there is a name != NULL
1261 if(!check_id(params->name)) {
1262 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1263 meshlink_errno = MESHLINK_EINVAL;
1270 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1271 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1272 meshlink_errno = MESHLINK_EINVAL;
1276 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1277 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1278 meshlink_errno = MESHLINK_EINVAL;
1282 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1284 if(params->confbase) {
1285 mesh->confbase = xstrdup(params->confbase);
1288 mesh->appname = xstrdup(params->appname);
1289 mesh->devclass = params->devclass;
1290 mesh->discovery = true;
1291 mesh->invitation_timeout = 604800; // 1 week
1292 mesh->netns = params->netns;
1293 mesh->submeshes = NULL;
1294 mesh->log_cb = global_log_cb;
1295 mesh->log_level = global_log_level;
1297 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1300 randomize(&mesh->session_id, sizeof(mesh->session_id));
1301 } while(mesh->session_id == 0);
1303 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1306 mesh->name = xstrdup(params->name);
1311 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1313 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1314 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1315 meshlink_close(mesh);
1316 meshlink_errno = MESHLINK_EINTERNAL;
1322 pthread_mutexattr_t attr;
1323 pthread_mutexattr_init(&attr);
1324 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1325 pthread_mutex_init(&mesh->mutex, &attr);
1327 mesh->threadstarted = false;
1328 event_loop_init(&mesh->loop);
1329 mesh->loop.data = mesh;
1331 meshlink_queue_init(&mesh->outpacketqueue);
1333 // Atomically lock the configuration directory.
1334 if(!main_config_lock(mesh)) {
1335 meshlink_close(mesh);
1339 // If no configuration exists yet, create it.
1341 if(!meshlink_confbase_exists(mesh)) {
1342 if(!meshlink_setup(mesh)) {
1343 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1344 meshlink_close(mesh);
1348 if(!meshlink_read_config(mesh)) {
1349 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1350 meshlink_close(mesh);
1356 struct WSAData wsa_state;
1357 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1360 // Setup up everything
1361 // TODO: we should not open listening sockets yet
1363 bool success = false;
1365 if(mesh->netns != -1) {
1369 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1370 void *retval = NULL;
1371 success = pthread_join(thr, &retval) == 0 && retval;
1375 meshlink_errno = MESHLINK_EINTERNAL;
1378 #endif // HAVE_SETNS
1380 success = setup_network(mesh);
1381 add_local_addresses(mesh);
1385 meshlink_close(mesh);
1386 meshlink_errno = MESHLINK_ENETWORK;
1390 add_local_addresses(mesh);
1392 if(!node_write_config(mesh, mesh->self)) {
1393 logger(NULL, MESHLINK_ERROR, "Cannot update configuration\n");
1397 idle_set(&mesh->loop, idle, mesh);
1399 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1403 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1404 meshlink_submesh_t *s = NULL;
1407 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1408 meshlink_errno = MESHLINK_EINVAL;
1412 if(!submesh || !*submesh) {
1413 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1414 meshlink_errno = MESHLINK_EINVAL;
1419 pthread_mutex_lock(&mesh->mutex);
1421 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1423 pthread_mutex_unlock(&mesh->mutex);
1428 static void *meshlink_main_loop(void *arg) {
1429 meshlink_handle_t *mesh = arg;
1431 if(mesh->netns != -1) {
1434 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1435 pthread_cond_signal(&mesh->cond);
1440 pthread_cond_signal(&mesh->cond);
1442 #endif // HAVE_SETNS
1447 if(mesh->discovery) {
1448 discovery_start(mesh);
1453 pthread_mutex_lock(&mesh->mutex);
1455 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1456 pthread_cond_broadcast(&mesh->cond);
1458 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1460 pthread_mutex_unlock(&mesh->mutex);
1465 if(mesh->discovery) {
1466 discovery_stop(mesh);
1474 bool meshlink_start(meshlink_handle_t *mesh) {
1476 assert(mesh->private_key);
1479 meshlink_errno = MESHLINK_EINVAL;
1483 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1485 pthread_mutex_lock(&mesh->mutex);
1487 assert(mesh->self->ecdsa);
1488 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1490 if(mesh->threadstarted) {
1491 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1492 pthread_mutex_unlock(&mesh->mutex);
1496 if(mesh->listen_socket[0].tcp.fd < 0) {
1497 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1498 meshlink_errno = MESHLINK_ENETWORK;
1502 mesh->thedatalen = 0;
1504 // TODO: open listening sockets first
1506 //Check that a valid name is set
1508 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1509 meshlink_errno = MESHLINK_EINVAL;
1510 pthread_mutex_unlock(&mesh->mutex);
1514 init_outgoings(mesh);
1516 // Start the main thread
1518 event_loop_start(&mesh->loop);
1520 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1521 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1522 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1523 meshlink_errno = MESHLINK_EINTERNAL;
1524 event_loop_stop(&mesh->loop);
1525 pthread_mutex_unlock(&mesh->mutex);
1529 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1530 mesh->threadstarted = true;
1532 // Ensure we are considered reachable
1535 pthread_mutex_unlock(&mesh->mutex);
1539 void meshlink_stop(meshlink_handle_t *mesh) {
1541 meshlink_errno = MESHLINK_EINVAL;
1545 pthread_mutex_lock(&mesh->mutex);
1546 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1548 // Shut down the main thread
1549 event_loop_stop(&mesh->loop);
1551 // Send ourselves a UDP packet to kick the event loop
1552 for(int i = 0; i < mesh->listen_sockets; i++) {
1554 socklen_t salen = sizeof(sa);
1556 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1557 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1561 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1562 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1566 if(mesh->threadstarted) {
1567 // Wait for the main thread to finish
1568 pthread_mutex_unlock(&mesh->mutex);
1569 pthread_join(mesh->thread, NULL);
1570 pthread_mutex_lock(&mesh->mutex);
1572 mesh->threadstarted = false;
1575 // Close all metaconnections
1576 if(mesh->connections) {
1577 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1579 connection_t *c = node->data;
1581 terminate_connection(mesh, c, false);
1585 exit_outgoings(mesh);
1587 // Ensure we are considered unreachable
1592 // Try to write out any changed node config files, ignore errors at this point.
1594 for splay_each(node_t, n, mesh->nodes) {
1595 if(n->status.dirty) {
1596 n->status.dirty = !node_write_config(mesh, n);
1601 pthread_mutex_unlock(&mesh->mutex);
1604 void meshlink_close(meshlink_handle_t *mesh) {
1606 meshlink_errno = MESHLINK_EINVAL;
1610 // stop can be called even if mesh has not been started
1611 meshlink_stop(mesh);
1613 // lock is not released after this
1614 pthread_mutex_lock(&mesh->mutex);
1616 // Close and free all resources used.
1618 close_network_connections(mesh);
1620 logger(mesh, MESHLINK_INFO, "Terminating");
1622 event_loop_exit(&mesh->loop);
1626 if(mesh->confbase) {
1632 ecdsa_free(mesh->invitation_key);
1634 if(mesh->netns != -1) {
1638 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1642 meshlink_queue_exit(&mesh->outpacketqueue);
1645 free(mesh->appname);
1646 free(mesh->confbase);
1647 free(mesh->config_key);
1648 ecdsa_free(mesh->private_key);
1650 main_config_unlock(mesh);
1652 pthread_mutex_unlock(&mesh->mutex);
1653 pthread_mutex_destroy(&mesh->mutex);
1655 memset(mesh, 0, sizeof(*mesh));
1660 bool meshlink_destroy(const char *confbase) {
1662 meshlink_errno = MESHLINK_EINVAL;
1666 /* Exit early if the confbase directory itself doesn't exist */
1667 if(access(confbase, F_OK) && errno == ENOENT) {
1671 /* Take the lock the same way meshlink_open() would. */
1672 char lockfilename[PATH_MAX];
1673 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1675 FILE *lockfile = fopen(lockfilename, "w+");
1678 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1679 meshlink_errno = MESHLINK_ESTORAGE;
1684 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1688 // TODO: use _locking()?
1691 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1692 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1694 meshlink_errno = MESHLINK_EBUSY;
1700 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1701 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1705 if(unlink(lockfilename)) {
1706 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1708 meshlink_errno = MESHLINK_ESTORAGE;
1714 if(!sync_path(confbase)) {
1715 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1716 meshlink_errno = MESHLINK_ESTORAGE;
1723 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1725 meshlink_errno = MESHLINK_EINVAL;
1729 pthread_mutex_lock(&mesh->mutex);
1730 mesh->receive_cb = cb;
1731 pthread_mutex_unlock(&mesh->mutex);
1734 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1736 meshlink_errno = MESHLINK_EINVAL;
1740 pthread_mutex_lock(&mesh->mutex);
1741 mesh->connection_try_cb = cb;
1742 pthread_mutex_unlock(&mesh->mutex);
1745 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1747 meshlink_errno = MESHLINK_EINVAL;
1751 pthread_mutex_lock(&mesh->mutex);
1752 mesh->node_status_cb = cb;
1753 pthread_mutex_unlock(&mesh->mutex);
1756 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1758 meshlink_errno = MESHLINK_EINVAL;
1762 pthread_mutex_lock(&mesh->mutex);
1763 mesh->node_pmtu_cb = cb;
1764 pthread_mutex_unlock(&mesh->mutex);
1767 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1769 meshlink_errno = MESHLINK_EINVAL;
1773 pthread_mutex_lock(&mesh->mutex);
1774 mesh->node_duplicate_cb = cb;
1775 pthread_mutex_unlock(&mesh->mutex);
1778 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1780 pthread_mutex_lock(&mesh->mutex);
1782 mesh->log_level = cb ? level : 0;
1783 pthread_mutex_unlock(&mesh->mutex);
1786 global_log_level = cb ? level : 0;
1790 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1792 meshlink_errno = MESHLINK_EINVAL;
1796 pthread_mutex_lock(&mesh->mutex);
1797 mesh->error_cb = cb;
1798 pthread_mutex_unlock(&mesh->mutex);
1801 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1802 meshlink_packethdr_t *hdr;
1804 // Validate arguments
1805 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1806 meshlink_errno = MESHLINK_EINVAL;
1815 meshlink_errno = MESHLINK_EINVAL;
1819 node_t *n = (node_t *)destination;
1821 if(n->status.blacklisted) {
1822 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1823 meshlink_errno = MESHLINK_EBLACKLISTED;
1827 // Prepare the packet
1828 vpn_packet_t *packet = malloc(sizeof(*packet));
1831 meshlink_errno = MESHLINK_ENOMEM;
1835 packet->probe = false;
1836 packet->tcp = false;
1837 packet->len = len + sizeof(*hdr);
1839 hdr = (meshlink_packethdr_t *)packet->data;
1840 memset(hdr, 0, sizeof(*hdr));
1841 // leave the last byte as 0 to make sure strings are always
1842 // null-terminated if they are longer than the buffer
1843 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1844 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1846 memcpy(packet->data + sizeof(*hdr), data, len);
1849 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1851 meshlink_errno = MESHLINK_ENOMEM;
1855 // Notify event loop
1856 signal_trigger(&mesh->loop, &mesh->datafromapp);
1861 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1863 meshlink_handle_t *mesh = data;
1864 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1870 mesh->self->in_packets++;
1871 mesh->self->in_bytes += packet->len;
1872 route(mesh, mesh->self, packet);
1877 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1878 if(!mesh || !destination) {
1879 meshlink_errno = MESHLINK_EINVAL;
1883 pthread_mutex_lock(&mesh->mutex);
1885 node_t *n = (node_t *)destination;
1887 if(!n->status.reachable) {
1888 pthread_mutex_unlock(&mesh->mutex);
1891 } else if(n->mtuprobes > 30 && n->minmtu) {
1892 pthread_mutex_unlock(&mesh->mutex);
1895 pthread_mutex_unlock(&mesh->mutex);
1900 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1901 if(!mesh || !node) {
1902 meshlink_errno = MESHLINK_EINVAL;
1906 pthread_mutex_lock(&mesh->mutex);
1908 node_t *n = (node_t *)node;
1910 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1911 meshlink_errno = MESHLINK_EINTERNAL;
1912 pthread_mutex_unlock(&mesh->mutex);
1916 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1919 meshlink_errno = MESHLINK_EINTERNAL;
1922 pthread_mutex_unlock(&mesh->mutex);
1926 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1928 meshlink_errno = MESHLINK_EINVAL;
1932 return (meshlink_node_t *)mesh->self;
1935 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1936 if(!mesh || !name) {
1937 meshlink_errno = MESHLINK_EINVAL;
1943 pthread_mutex_lock(&mesh->mutex);
1944 n = lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1945 pthread_mutex_unlock(&mesh->mutex);
1948 meshlink_errno = MESHLINK_ENOENT;
1951 return (meshlink_node_t *)n;
1954 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1955 if(!mesh || !name) {
1956 meshlink_errno = MESHLINK_EINVAL;
1960 meshlink_submesh_t *submesh = NULL;
1962 pthread_mutex_lock(&mesh->mutex);
1963 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1964 pthread_mutex_unlock(&mesh->mutex);
1967 meshlink_errno = MESHLINK_ENOENT;
1973 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1974 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1975 meshlink_errno = MESHLINK_EINVAL;
1979 meshlink_node_t **result;
1982 pthread_mutex_lock(&mesh->mutex);
1984 *nmemb = mesh->nodes->count;
1985 result = realloc(nodes, *nmemb * sizeof(*nodes));
1988 meshlink_node_t **p = result;
1990 for splay_each(node_t, n, mesh->nodes) {
1991 *p++ = (meshlink_node_t *)n;
1996 meshlink_errno = MESHLINK_ENOMEM;
1999 pthread_mutex_unlock(&mesh->mutex);
2004 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) {
2005 meshlink_node_t **result;
2007 pthread_mutex_lock(&mesh->mutex);
2011 for splay_each(node_t, n, mesh->nodes) {
2012 if(search_node(n, condition)) {
2019 pthread_mutex_unlock(&mesh->mutex);
2023 result = realloc(nodes, *nmemb * sizeof(*nodes));
2026 meshlink_node_t **p = result;
2028 for splay_each(node_t, n, mesh->nodes) {
2029 if(search_node(n, condition)) {
2030 *p++ = (meshlink_node_t *)n;
2036 meshlink_errno = MESHLINK_ENOMEM;
2039 pthread_mutex_unlock(&mesh->mutex);
2044 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2045 dev_class_t *devclass = (dev_class_t *)condition;
2047 if(*devclass == (dev_class_t)node->devclass) {
2054 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2055 if(condition == node->submesh) {
2067 static bool search_node_by_last_reachable(const node_t *node, const void *condition) {
2068 const struct time_range *range = condition;
2069 time_t start = node->last_reachable;
2070 time_t end = node->last_unreachable;
2080 if(range->end >= range->start) {
2081 return start <= range->end && end >= range->start;
2083 return start > range->start || end < range->end;
2087 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) {
2088 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2089 meshlink_errno = MESHLINK_EINVAL;
2093 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2096 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2097 if(!mesh || !submesh || !nmemb) {
2098 meshlink_errno = MESHLINK_EINVAL;
2102 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2105 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) {
2106 if(!mesh || !nmemb) {
2107 meshlink_errno = MESHLINK_EINVAL;
2111 struct time_range range = {start, end};
2113 return meshlink_get_all_nodes_by_condition(mesh, &range, nodes, nmemb, search_node_by_last_reachable);
2116 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2117 if(!mesh || !node) {
2118 meshlink_errno = MESHLINK_EINVAL;
2122 dev_class_t devclass;
2124 pthread_mutex_lock(&mesh->mutex);
2126 devclass = ((node_t *)node)->devclass;
2128 pthread_mutex_unlock(&mesh->mutex);
2133 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2134 if(!mesh || !node) {
2135 meshlink_errno = MESHLINK_EINVAL;
2139 node_t *n = (node_t *)node;
2141 meshlink_submesh_t *s;
2143 s = (meshlink_submesh_t *)n->submesh;
2148 bool meshlink_get_node_reachability(struct meshlink_handle *mesh, struct meshlink_node *node, time_t *last_reachable, time_t *last_unreachable) {
2149 if(!mesh || !node) {
2150 meshlink_errno = MESHLINK_EINVAL;
2154 node_t *n = (node_t *)node;
2157 pthread_mutex_lock(&mesh->mutex);
2158 reachable = n->status.reachable && !n->status.blacklisted;
2160 if(last_reachable) {
2161 *last_reachable = n->last_reachable;
2164 if(last_unreachable) {
2165 *last_unreachable = n->last_unreachable;
2168 pthread_mutex_unlock(&mesh->mutex);
2173 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2174 if(!mesh || !data || !len || !signature || !siglen) {
2175 meshlink_errno = MESHLINK_EINVAL;
2179 if(*siglen < MESHLINK_SIGLEN) {
2180 meshlink_errno = MESHLINK_EINVAL;
2184 pthread_mutex_lock(&mesh->mutex);
2186 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2187 meshlink_errno = MESHLINK_EINTERNAL;
2188 pthread_mutex_unlock(&mesh->mutex);
2192 *siglen = MESHLINK_SIGLEN;
2193 pthread_mutex_unlock(&mesh->mutex);
2197 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2198 if(!mesh || !data || !len || !signature) {
2199 meshlink_errno = MESHLINK_EINVAL;
2203 if(siglen != MESHLINK_SIGLEN) {
2204 meshlink_errno = MESHLINK_EINVAL;
2208 pthread_mutex_lock(&mesh->mutex);
2212 struct node_t *n = (struct node_t *)source;
2214 if(!node_read_public_key(mesh, n)) {
2215 meshlink_errno = MESHLINK_EINTERNAL;
2218 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2221 pthread_mutex_unlock(&mesh->mutex);
2225 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2226 pthread_mutex_lock(&mesh->mutex);
2228 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2231 // TODO: Update invitation key if necessary?
2234 pthread_mutex_unlock(&mesh->mutex);
2236 return mesh->invitation_key;
2239 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2240 if(!mesh || !node || !address) {
2241 meshlink_errno = MESHLINK_EINVAL;
2245 if(!is_valid_hostname(address)) {
2246 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2247 meshlink_errno = MESHLINK_EINVAL;
2251 if(port && !is_valid_port(port)) {
2252 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2253 meshlink_errno = MESHLINK_EINVAL;
2257 char *canonical_address;
2260 xasprintf(&canonical_address, "%s %s", address, port);
2262 canonical_address = xstrdup(address);
2265 pthread_mutex_lock(&mesh->mutex);
2267 node_t *n = (node_t *)node;
2268 free(n->canonical_address);
2269 n->canonical_address = canonical_address;
2271 if(!node_write_config(mesh, n)) {
2272 pthread_mutex_unlock(&mesh->mutex);
2276 pthread_mutex_unlock(&mesh->mutex);
2278 return config_sync(mesh, "current");
2281 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2282 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2285 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2287 meshlink_errno = MESHLINK_EINVAL;
2291 char *address = meshlink_get_external_address(mesh);
2297 bool rval = meshlink_add_address(mesh, address);
2303 int meshlink_get_port(meshlink_handle_t *mesh) {
2305 meshlink_errno = MESHLINK_EINVAL;
2310 meshlink_errno = MESHLINK_EINTERNAL;
2316 pthread_mutex_lock(&mesh->mutex);
2317 port = atoi(mesh->myport);
2318 pthread_mutex_unlock(&mesh->mutex);
2323 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2324 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2325 meshlink_errno = MESHLINK_EINVAL;
2329 if(mesh->myport && port == atoi(mesh->myport)) {
2333 if(!try_bind(port)) {
2334 meshlink_errno = MESHLINK_ENETWORK;
2338 devtool_trybind_probe();
2342 pthread_mutex_lock(&mesh->mutex);
2344 if(mesh->threadstarted) {
2345 meshlink_errno = MESHLINK_EINVAL;
2350 xasprintf(&mesh->myport, "%d", port);
2352 /* Close down the network. This also deletes mesh->self. */
2353 close_network_connections(mesh);
2355 /* Recreate mesh->self. */
2356 mesh->self = new_node();
2357 mesh->self->name = xstrdup(mesh->name);
2358 mesh->self->devclass = mesh->devclass;
2359 mesh->self->session_id = mesh->session_id;
2360 xasprintf(&mesh->myport, "%d", port);
2362 if(!node_read_public_key(mesh, mesh->self)) {
2363 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2364 meshlink_errno = MESHLINK_ESTORAGE;
2365 free_node(mesh->self);
2368 } else if(!setup_network(mesh)) {
2369 meshlink_errno = MESHLINK_ENETWORK;
2373 /* Rebuild our own list of recent addresses */
2374 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2375 add_local_addresses(mesh);
2377 /* Write meshlink.conf with the updated port number */
2378 write_main_config_files(mesh);
2380 rval = config_sync(mesh, "current");
2383 pthread_mutex_unlock(&mesh->mutex);
2385 return rval && meshlink_get_port(mesh) == port;
2388 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2389 mesh->invitation_timeout = timeout;
2392 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2393 meshlink_submesh_t *s = NULL;
2396 meshlink_errno = MESHLINK_EINVAL;
2401 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2404 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2405 meshlink_errno = MESHLINK_EINVAL;
2409 s = (meshlink_submesh_t *)mesh->self->submesh;
2412 pthread_mutex_lock(&mesh->mutex);
2414 // Check validity of the new node's name
2415 if(!check_id(name)) {
2416 logger(mesh, MESHLINK_ERROR, "Invalid name for node.\n");
2417 meshlink_errno = MESHLINK_EINVAL;
2418 pthread_mutex_unlock(&mesh->mutex);
2422 // Ensure no host configuration file with that name exists
2423 if(config_exists(mesh, "current", name)) {
2424 logger(mesh, MESHLINK_ERROR, "A host config file for %s already exists!\n", name);
2425 meshlink_errno = MESHLINK_EEXIST;
2426 pthread_mutex_unlock(&mesh->mutex);
2430 // Ensure no other nodes know about this name
2431 if(meshlink_get_node(mesh, name)) {
2432 logger(mesh, MESHLINK_ERROR, "A node with name %s is already known!\n", name);
2433 meshlink_errno = MESHLINK_EEXIST;
2434 pthread_mutex_unlock(&mesh->mutex);
2438 // Get the local address
2439 char *address = get_my_hostname(mesh, flags);
2442 logger(mesh, MESHLINK_ERROR, "No Address known for ourselves!\n");
2443 meshlink_errno = MESHLINK_ERESOLV;
2444 pthread_mutex_unlock(&mesh->mutex);
2448 if(!refresh_invitation_key(mesh)) {
2449 meshlink_errno = MESHLINK_EINTERNAL;
2450 pthread_mutex_unlock(&mesh->mutex);
2454 // If we changed our own host config file, write it out now
2455 if(mesh->self->status.dirty) {
2456 if(!node_write_config(mesh, mesh->self)) {
2457 logger(mesh, MESHLINK_ERROR, "Could not write our own host conifg file!\n");
2458 pthread_mutex_unlock(&mesh->mutex);
2465 // Create a hash of the key.
2466 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2467 sha512(fingerprint, strlen(fingerprint), hash);
2468 b64encode_urlsafe(hash, hash, 18);
2470 // Create a random cookie for this invitation.
2472 randomize(cookie, 18);
2474 // Create a filename that doesn't reveal the cookie itself
2475 char buf[18 + strlen(fingerprint)];
2476 char cookiehash[64];
2477 memcpy(buf, cookie, 18);
2478 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2479 sha512(buf, sizeof(buf), cookiehash);
2480 b64encode_urlsafe(cookiehash, cookiehash, 18);
2482 b64encode_urlsafe(cookie, cookie, 18);
2486 /* Construct the invitation file */
2487 uint8_t outbuf[4096];
2488 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2490 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2491 packmsg_add_str(&inv, name);
2492 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2493 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2495 /* TODO: Add several host config files to bootstrap connections.
2496 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2497 * and are not blacklisted.
2499 config_t configs[5];
2500 memset(configs, 0, sizeof(configs));
2503 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2507 /* Append host config files to the invitation file */
2508 packmsg_add_array(&inv, count);
2510 for(int i = 0; i < count; i++) {
2511 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2512 config_free(&configs[i]);
2515 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2517 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2518 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2519 meshlink_errno = MESHLINK_ESTORAGE;
2520 pthread_mutex_unlock(&mesh->mutex);
2524 // Create an URL from the local address, key hash and cookie
2526 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2529 pthread_mutex_unlock(&mesh->mutex);
2533 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2534 return meshlink_invite_ex(mesh, submesh, name, 0);
2537 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2538 if(!mesh || !invitation) {
2539 meshlink_errno = MESHLINK_EINVAL;
2543 pthread_mutex_lock(&mesh->mutex);
2545 //Before doing meshlink_join make sure we are not connected to another mesh
2546 if(mesh->threadstarted) {
2547 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2548 meshlink_errno = MESHLINK_EINVAL;
2549 pthread_mutex_unlock(&mesh->mutex);
2553 // 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.
2554 if(mesh->nodes->count > 1) {
2555 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2556 meshlink_errno = MESHLINK_EINVAL;
2557 pthread_mutex_unlock(&mesh->mutex);
2561 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2562 char copy[strlen(invitation) + 1];
2563 strcpy(copy, invitation);
2565 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2567 char *slash = strchr(copy, '/');
2575 if(strlen(slash) != 48) {
2579 char *address = copy;
2582 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2586 // Generate a throw-away key for the invitation.
2587 ecdsa_t *key = ecdsa_generate();
2590 meshlink_errno = MESHLINK_EINTERNAL;
2591 pthread_mutex_unlock(&mesh->mutex);
2595 char *b64key = ecdsa_get_base64_public_key(key);
2599 while(address && *address) {
2600 // We allow commas in the address part to support multiple addresses in one invitation URL.
2601 comma = strchr(address, ',');
2607 // Split of the port
2608 port = strrchr(address, ':');
2616 // IPv6 address are enclosed in brackets, per RFC 3986
2617 if(*address == '[') {
2619 char *bracket = strchr(address, ']');
2632 // Connect to the meshlink daemon mentioned in the URL.
2633 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2636 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2637 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2639 if(mesh->sock == -1) {
2640 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2641 meshlink_errno = MESHLINK_ENETWORK;
2645 set_timeout(mesh->sock, 5000);
2647 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2648 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2649 meshlink_errno = MESHLINK_ENETWORK;
2650 closesocket(mesh->sock);
2658 meshlink_errno = MESHLINK_ERESOLV;
2661 if(mesh->sock != -1 || !comma) {
2668 if(mesh->sock == -1) {
2669 pthread_mutex_unlock(&mesh->mutex);
2673 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2675 // Tell him we have an invitation, and give him our throw-away key.
2679 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2680 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2681 closesocket(mesh->sock);
2682 meshlink_errno = MESHLINK_ENETWORK;
2683 pthread_mutex_unlock(&mesh->mutex);
2689 char hisname[4096] = "";
2690 int code, hismajor, hisminor = 0;
2692 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) {
2693 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2694 closesocket(mesh->sock);
2695 meshlink_errno = MESHLINK_ENETWORK;
2696 pthread_mutex_unlock(&mesh->mutex);
2700 // Check if the hash of the key he gave us matches the hash in the URL.
2701 char *fingerprint = mesh->line + 2;
2704 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2705 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2706 meshlink_errno = MESHLINK_EINTERNAL;
2707 pthread_mutex_unlock(&mesh->mutex);
2711 if(memcmp(hishash, mesh->hash, 18)) {
2712 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2713 meshlink_errno = MESHLINK_EPEER;
2714 pthread_mutex_unlock(&mesh->mutex);
2719 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2722 meshlink_errno = MESHLINK_EINTERNAL;
2723 pthread_mutex_unlock(&mesh->mutex);
2727 // Start an SPTPS session
2728 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2729 meshlink_errno = MESHLINK_EINTERNAL;
2730 pthread_mutex_unlock(&mesh->mutex);
2734 // Feed rest of input buffer to SPTPS
2735 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2736 meshlink_errno = MESHLINK_EPEER;
2737 pthread_mutex_unlock(&mesh->mutex);
2743 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2745 if(errno == EINTR) {
2749 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2750 meshlink_errno = MESHLINK_ENETWORK;
2751 pthread_mutex_unlock(&mesh->mutex);
2755 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2756 meshlink_errno = MESHLINK_EPEER;
2757 pthread_mutex_unlock(&mesh->mutex);
2762 sptps_stop(&mesh->sptps);
2765 closesocket(mesh->sock);
2767 if(!mesh->success) {
2768 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2769 meshlink_errno = MESHLINK_EPEER;
2770 pthread_mutex_unlock(&mesh->mutex);
2774 pthread_mutex_unlock(&mesh->mutex);
2778 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2779 meshlink_errno = MESHLINK_EINVAL;
2780 pthread_mutex_unlock(&mesh->mutex);
2784 char *meshlink_export(meshlink_handle_t *mesh) {
2786 meshlink_errno = MESHLINK_EINVAL;
2790 // Create a config file on the fly.
2793 packmsg_output_t out = {buf, sizeof(buf)};
2794 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2795 packmsg_add_str(&out, mesh->name);
2796 packmsg_add_str(&out, CORE_MESH);
2798 pthread_mutex_lock(&mesh->mutex);
2800 packmsg_add_int32(&out, mesh->self->devclass);
2801 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2802 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2803 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2807 for(uint32_t i = 0; i < MAX_RECENT; i++) {
2808 if(mesh->self->recent[i].sa.sa_family) {
2815 packmsg_add_array(&out, count);
2817 for(uint32_t i = 0; i < count; i++) {
2818 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2821 packmsg_add_int64(&out, 0);
2822 packmsg_add_int64(&out, 0);
2824 pthread_mutex_unlock(&mesh->mutex);
2826 if(!packmsg_output_ok(&out)) {
2827 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2828 meshlink_errno = MESHLINK_EINTERNAL;
2832 // Prepare a base64-encoded packmsg array containing our config file
2834 uint32_t len = packmsg_output_size(&out, buf);
2835 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2836 uint8_t *buf2 = xmalloc(len2);
2837 packmsg_output_t out2 = {buf2, len2};
2838 packmsg_add_array(&out2, 1);
2839 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2841 if(!packmsg_output_ok(&out2)) {
2842 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2843 meshlink_errno = MESHLINK_EINTERNAL;
2848 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2850 return (char *)buf2;
2853 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2854 if(!mesh || !data) {
2855 meshlink_errno = MESHLINK_EINVAL;
2859 size_t datalen = strlen(data);
2860 uint8_t *buf = xmalloc(datalen);
2861 int buflen = b64decode(data, buf, datalen);
2864 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2865 meshlink_errno = MESHLINK_EPEER;
2869 packmsg_input_t in = {buf, buflen};
2870 uint32_t count = packmsg_get_array(&in);
2873 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2874 meshlink_errno = MESHLINK_EPEER;
2878 pthread_mutex_lock(&mesh->mutex);
2882 uint32_t len = packmsg_get_bin_raw(&in, &data);
2888 packmsg_input_t in2 = {data, len};
2889 uint32_t version = packmsg_get_uint32(&in2);
2890 char *name = packmsg_get_str_dup(&in2);
2892 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2894 packmsg_input_invalidate(&in);
2898 if(!check_id(name)) {
2903 node_t *n = lookup_node(mesh, name);
2906 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2914 config_t config = {data, len};
2916 if(!node_read_from_config(mesh, n, &config)) {
2918 packmsg_input_invalidate(&in);
2922 if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
2930 pthread_mutex_unlock(&mesh->mutex);
2934 if(!packmsg_done(&in)) {
2935 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2936 meshlink_errno = MESHLINK_EPEER;
2940 if(!config_sync(mesh, "current")) {
2947 static bool blacklist(meshlink_handle_t *mesh, node_t *n) {
2948 if(n == mesh->self) {
2949 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", n->name);
2950 meshlink_errno = MESHLINK_EINVAL;
2954 if(n->status.blacklisted) {
2955 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", n->name);
2959 n->status.blacklisted = true;
2961 /* Immediately shut down any connections we have with the blacklisted node.
2962 * We can't call terminate_connection(), because we might be called from a callback function.
2964 for list_each(connection_t, c, mesh->connections) {
2966 shutdown(c->socket, SHUT_RDWR);
2970 utcp_abort_all_connections(n->utcp);
2976 n->status.udp_confirmed = false;
2978 if(n->status.reachable) {
2979 n->last_unreachable = mesh->loop.now.tv_sec;
2982 /* Graph updates will suppress status updates for blacklisted nodes, so we need to
2983 * manually call the status callback if necessary.
2985 if(n->status.reachable && mesh->node_status_cb) {
2986 mesh->node_status_cb(mesh, (meshlink_node_t *)n, false);
2989 return node_write_config(mesh, n) && config_sync(mesh, "current");
2992 bool meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2993 if(!mesh || !node) {
2994 meshlink_errno = MESHLINK_EINVAL;
2998 pthread_mutex_lock(&mesh->mutex);
3000 if(!blacklist(mesh, (node_t *)node)) {
3001 pthread_mutex_unlock(&mesh->mutex);
3005 pthread_mutex_unlock(&mesh->mutex);
3007 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
3011 bool meshlink_blacklist_by_name(meshlink_handle_t *mesh, const char *name) {
3012 if(!mesh || !name) {
3013 meshlink_errno = MESHLINK_EINVAL;
3017 pthread_mutex_lock(&mesh->mutex);
3019 node_t *n = lookup_node(mesh, (char *)name);
3023 n->name = xstrdup(name);
3027 if(!blacklist(mesh, (node_t *)n)) {
3028 pthread_mutex_unlock(&mesh->mutex);
3032 pthread_mutex_unlock(&mesh->mutex);
3034 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", name);
3038 static bool whitelist(meshlink_handle_t *mesh, node_t *n) {
3039 if(n == mesh->self) {
3040 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", n->name);
3041 meshlink_errno = MESHLINK_EINVAL;
3045 if(!n->status.blacklisted) {
3046 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", n->name);
3050 n->status.blacklisted = false;
3052 if(n->status.reachable) {
3053 n->last_reachable = mesh->loop.now.tv_sec;
3054 update_node_status(mesh, n);
3057 return node_write_config(mesh, n) && config_sync(mesh, "current");
3060 bool meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
3061 if(!mesh || !node) {
3062 meshlink_errno = MESHLINK_EINVAL;
3066 pthread_mutex_lock(&mesh->mutex);
3068 if(!whitelist(mesh, (node_t *)node)) {
3069 pthread_mutex_unlock(&mesh->mutex);
3073 pthread_mutex_unlock(&mesh->mutex);
3075 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
3079 bool meshlink_whitelist_by_name(meshlink_handle_t *mesh, const char *name) {
3080 if(!mesh || !name) {
3081 meshlink_errno = MESHLINK_EINVAL;
3085 pthread_mutex_lock(&mesh->mutex);
3087 node_t *n = lookup_node(mesh, (char *)name);
3091 n->name = xstrdup(name);
3095 if(!whitelist(mesh, (node_t *)n)) {
3096 pthread_mutex_unlock(&mesh->mutex);
3100 pthread_mutex_unlock(&mesh->mutex);
3102 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", name);
3106 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
3107 mesh->default_blacklist = blacklist;
3110 bool meshlink_forget_node(meshlink_handle_t *mesh, meshlink_node_t *node) {
3111 if(!mesh || !node) {
3112 meshlink_errno = MESHLINK_EINVAL;
3116 node_t *n = (node_t *)node;
3118 pthread_mutex_lock(&mesh->mutex);
3120 /* Check that the node is not reachable */
3121 if(n->status.reachable || n->connection) {
3122 pthread_mutex_unlock(&mesh->mutex);
3123 logger(mesh, MESHLINK_WARNING, "Could not forget %s: still reachable", n->name);
3127 /* Check that we don't have any active UTCP connections */
3128 if(n->utcp && utcp_is_active(n->utcp)) {
3129 pthread_mutex_unlock(&mesh->mutex);
3130 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active UTCP connections", n->name);
3134 /* Check that we have no active connections to this node */
3135 for list_each(connection_t, c, mesh->connections) {
3137 pthread_mutex_unlock(&mesh->mutex);
3138 logger(mesh, MESHLINK_WARNING, "Could not forget %s: active connection", n->name);
3143 /* Remove any pending outgoings to this node */
3144 if(mesh->outgoings) {
3145 for list_each(outgoing_t, outgoing, mesh->outgoings) {
3146 if(outgoing->node == n) {
3147 list_delete_node(mesh->outgoings, node);
3152 /* Delete the config file for this node */
3153 if(!config_delete(mesh, "current", n->name)) {
3154 pthread_mutex_unlock(&mesh->mutex);
3158 /* Delete the node struct and any remaining edges referencing this node */
3161 pthread_mutex_unlock(&mesh->mutex);
3163 return config_sync(mesh, "current");
3166 /* Hint that a hostname may be found at an address
3167 * See header file for detailed comment.
3169 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
3170 if(!mesh || !node || !addr) {
3171 meshlink_errno = EINVAL;
3175 pthread_mutex_lock(&mesh->mutex);
3177 node_t *n = (node_t *)node;
3179 if(node_add_recent_address(mesh, n, (sockaddr_t *)addr)) {
3180 if(!node_write_config(mesh, n)) {
3181 logger(mesh, MESHLINK_DEBUG, "Could not update %s\n", n->name);
3185 pthread_mutex_unlock(&mesh->mutex);
3186 // @TODO do we want to fire off a connection attempt right away?
3189 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
3191 node_t *n = utcp->priv;
3192 meshlink_handle_t *mesh = n->mesh;
3193 return mesh->channel_accept_cb;
3196 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
3198 if(aio->cb.buffer) {
3199 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
3203 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
3208 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
3209 meshlink_channel_t *channel = connection->priv;
3215 node_t *n = channel->node;
3216 meshlink_handle_t *mesh = n->mesh;
3218 if(n->status.destroyed) {
3219 meshlink_channel_close(mesh, channel);
3223 const char *p = data;
3226 while(channel->aio_receive) {
3227 meshlink_aio_buffer_t *aio = channel->aio_receive;
3228 size_t todo = aio->len - aio->done;
3235 memcpy((char *)aio->data + aio->done, p, todo);
3237 ssize_t result = write(aio->fd, p, todo);
3246 if(aio->done == aio->len) {
3247 channel->aio_receive = aio->next;
3248 aio_signal(mesh, channel, aio);
3260 if(channel->receive_cb) {
3261 channel->receive_cb(mesh, channel, p, left);
3267 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3268 node_t *n = utcp_connection->utcp->priv;
3274 meshlink_handle_t *mesh = n->mesh;
3276 if(!mesh->channel_accept_cb) {
3280 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3282 channel->c = utcp_connection;
3284 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3285 utcp_accept(utcp_connection, channel_recv, channel);
3291 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3292 node_t *n = utcp->priv;
3294 if(n->status.destroyed) {
3298 meshlink_handle_t *mesh = n->mesh;
3299 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3302 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3303 if(!mesh || !channel) {
3304 meshlink_errno = MESHLINK_EINVAL;
3308 channel->receive_cb = cb;
3311 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3313 node_t *n = (node_t *)source;
3319 utcp_recv(n->utcp, data, len);
3322 static void channel_poll(struct utcp_connection *connection, size_t len) {
3323 meshlink_channel_t *channel = connection->priv;
3329 node_t *n = channel->node;
3330 meshlink_handle_t *mesh = n->mesh;
3331 meshlink_aio_buffer_t *aio = channel->aio_send;
3334 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3335 size_t left = aio->len - aio->done;
3343 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3346 size_t todo = utcp_get_sndbuf_free(connection);
3352 if(todo > sizeof(buf)) {
3356 ssize_t result = read(aio->fd, buf, todo);
3359 sent = utcp_send(connection, buf, result);
3369 /* If the buffer is now completely sent, call the callback and dispose of it. */
3370 if(aio->done >= aio->len) {
3371 channel->aio_send = aio->next;
3372 aio_signal(mesh, channel, aio);
3376 if(channel->poll_cb) {
3377 channel->poll_cb(mesh, channel, len);
3379 utcp_set_poll_cb(connection, NULL);
3384 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3385 if(!mesh || !channel) {
3386 meshlink_errno = MESHLINK_EINVAL;
3390 pthread_mutex_lock(&mesh->mutex);
3391 channel->poll_cb = cb;
3392 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3393 pthread_mutex_unlock(&mesh->mutex);
3396 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3398 meshlink_errno = MESHLINK_EINVAL;
3402 pthread_mutex_lock(&mesh->mutex);
3403 mesh->channel_accept_cb = cb;
3404 mesh->receive_cb = channel_receive;
3406 for splay_each(node_t, n, mesh->nodes) {
3407 if(!n->utcp && n != mesh->self) {
3408 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3412 pthread_mutex_unlock(&mesh->mutex);
3415 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3419 meshlink_errno = MESHLINK_EINVAL;
3423 pthread_mutex_lock(&mesh->mutex);
3424 utcp_set_sndbuf(channel->c, size);
3425 pthread_mutex_unlock(&mesh->mutex);
3428 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3432 meshlink_errno = MESHLINK_EINVAL;
3436 pthread_mutex_lock(&mesh->mutex);
3437 utcp_set_rcvbuf(channel->c, size);
3438 pthread_mutex_unlock(&mesh->mutex);
3441 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) {
3443 abort(); // TODO: handle non-NULL data
3446 if(!mesh || !node) {
3447 meshlink_errno = MESHLINK_EINVAL;
3451 pthread_mutex_lock(&mesh->mutex);
3453 node_t *n = (node_t *)node;
3456 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3457 mesh->receive_cb = channel_receive;
3460 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3461 pthread_mutex_unlock(&mesh->mutex);
3466 if(n->status.blacklisted) {
3467 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3468 meshlink_errno = MESHLINK_EBLACKLISTED;
3469 pthread_mutex_unlock(&mesh->mutex);
3473 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3475 channel->receive_cb = cb;
3478 channel->priv = (void *)data;
3481 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3483 pthread_mutex_unlock(&mesh->mutex);
3486 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3494 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) {
3495 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3498 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3499 if(!mesh || !channel) {
3500 meshlink_errno = MESHLINK_EINVAL;
3504 pthread_mutex_lock(&mesh->mutex);
3505 utcp_shutdown(channel->c, direction);
3506 pthread_mutex_unlock(&mesh->mutex);
3509 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3510 if(!mesh || !channel) {
3511 meshlink_errno = MESHLINK_EINVAL;
3515 pthread_mutex_lock(&mesh->mutex);
3517 utcp_close(channel->c);
3519 /* Clean up any outstanding AIO buffers. */
3520 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3522 aio_signal(mesh, channel, aio);
3526 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3528 aio_signal(mesh, channel, aio);
3532 pthread_mutex_unlock(&mesh->mutex);
3537 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3538 if(!mesh || !channel) {
3539 meshlink_errno = MESHLINK_EINVAL;
3548 meshlink_errno = MESHLINK_EINVAL;
3552 // TODO: more finegrained locking.
3553 // Ideally we want to put the data into the UTCP connection's send buffer.
3554 // Then, preferably only if there is room in the receiver window,
3555 // kick the meshlink thread to go send packets.
3559 pthread_mutex_lock(&mesh->mutex);
3561 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3562 if(channel->aio_send) {
3565 retval = utcp_send(channel->c, data, len);
3568 pthread_mutex_unlock(&mesh->mutex);
3571 meshlink_errno = MESHLINK_ENETWORK;
3577 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) {
3578 if(!mesh || !channel) {
3579 meshlink_errno = MESHLINK_EINVAL;
3584 meshlink_errno = MESHLINK_EINVAL;
3588 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3591 aio->cb.buffer = cb;
3594 pthread_mutex_lock(&mesh->mutex);
3596 /* Append the AIO buffer descriptor to the end of the chain */
3597 meshlink_aio_buffer_t **p = &channel->aio_send;
3605 /* Ensure the poll callback is set, and call it right now to push data if possible */
3606 utcp_set_poll_cb(channel->c, channel_poll);
3607 channel_poll(channel->c, len);
3609 pthread_mutex_unlock(&mesh->mutex);
3614 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) {
3615 if(!mesh || !channel) {
3616 meshlink_errno = MESHLINK_EINVAL;
3620 if(!len || fd == -1) {
3621 meshlink_errno = MESHLINK_EINVAL;
3625 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3631 pthread_mutex_lock(&mesh->mutex);
3633 /* Append the AIO buffer descriptor to the end of the chain */
3634 meshlink_aio_buffer_t **p = &channel->aio_send;
3642 /* Ensure the poll callback is set, and call it right now to push data if possible */
3643 utcp_set_poll_cb(channel->c, channel_poll);
3644 channel_poll(channel->c, len);
3646 pthread_mutex_unlock(&mesh->mutex);
3651 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) {
3652 if(!mesh || !channel) {
3653 meshlink_errno = MESHLINK_EINVAL;
3658 meshlink_errno = MESHLINK_EINVAL;
3662 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3665 aio->cb.buffer = cb;
3668 pthread_mutex_lock(&mesh->mutex);
3670 /* Append the AIO buffer descriptor to the end of the chain */
3671 meshlink_aio_buffer_t **p = &channel->aio_receive;
3679 pthread_mutex_unlock(&mesh->mutex);
3684 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) {
3685 if(!mesh || !channel) {
3686 meshlink_errno = MESHLINK_EINVAL;
3690 if(!len || fd == -1) {
3691 meshlink_errno = MESHLINK_EINVAL;
3695 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3701 pthread_mutex_lock(&mesh->mutex);
3703 /* Append the AIO buffer descriptor to the end of the chain */
3704 meshlink_aio_buffer_t **p = &channel->aio_receive;
3712 pthread_mutex_unlock(&mesh->mutex);
3717 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3718 if(!mesh || !channel) {
3719 meshlink_errno = MESHLINK_EINVAL;
3723 return channel->c->flags;
3726 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3727 if(!mesh || !channel) {
3728 meshlink_errno = MESHLINK_EINVAL;
3732 return utcp_get_sendq(channel->c);
3735 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3736 if(!mesh || !channel) {
3737 meshlink_errno = MESHLINK_EINVAL;
3741 return utcp_get_recvq(channel->c);
3744 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3745 if(!mesh || !node) {
3746 meshlink_errno = MESHLINK_EINVAL;
3750 node_t *n = (node_t *)node;
3752 pthread_mutex_lock(&mesh->mutex);
3755 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3758 utcp_set_user_timeout(n->utcp, timeout);
3760 pthread_mutex_unlock(&mesh->mutex);
3763 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3764 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3765 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3768 if(mesh->node_status_cb) {
3769 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3772 if(mesh->node_pmtu_cb) {
3773 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3777 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3778 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3779 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3783 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3784 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3788 n->status.duplicate = true;
3789 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3792 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3796 meshlink_errno = MESHLINK_EINVAL;
3800 pthread_mutex_lock(&mesh->mutex);
3802 if(mesh->discovery == enable) {
3806 if(mesh->threadstarted) {
3808 discovery_start(mesh);
3810 discovery_stop(mesh);
3814 mesh->discovery = enable;
3817 pthread_mutex_unlock(&mesh->mutex);
3821 meshlink_errno = MESHLINK_ENOTSUP;
3825 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3826 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3827 meshlink_errno = EINVAL;
3831 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3832 meshlink_errno = EINVAL;
3836 pthread_mutex_lock(&mesh->mutex);
3837 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3838 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3839 pthread_mutex_unlock(&mesh->mutex);
3842 void meshlink_set_dev_class_fast_retry_period(meshlink_handle_t *mesh, dev_class_t devclass, int fast_retry_period) {
3843 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3844 meshlink_errno = EINVAL;
3848 if(fast_retry_period < 0) {
3849 meshlink_errno = EINVAL;
3853 pthread_mutex_lock(&mesh->mutex);
3854 mesh->dev_class_traits[devclass].fast_retry_period = fast_retry_period;
3855 pthread_mutex_unlock(&mesh->mutex);
3858 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3861 if(!mesh->connections || !mesh->loop.running) {
3868 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3869 // We should only call the callback function if we are in the background thread.
3870 if(!mesh->error_cb) {
3874 if(!mesh->threadstarted) {
3878 if(mesh->thread == pthread_self()) {
3879 mesh->error_cb(mesh, meshlink_errno);
3884 static void __attribute__((constructor)) meshlink_init(void) {
3888 static void __attribute__((destructor)) meshlink_exit(void) {