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, struct sockaddr *sn, socklen_t *sl, 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, sn, sl)) {
203 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
204 struct sockaddr_storage sn;
205 socklen_t sl = sizeof(sn);
207 if(!getlocaladdr(destaddr, (struct sockaddr *)&sn, &sl, netns)) {
211 if(getnameinfo((struct sockaddr *)&sn, sl, 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])) {
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);
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 int check_port(meshlink_handle_t *mesh) {
518 for(int i = 0; i < 1000; i++) {
519 int port = 0x1000 + (rand() & 0x7fff);
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 int32_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 sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
666 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
671 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
673 meshlink_handle_t *mesh = handle;
674 const char *ptr = data;
677 int result = send(mesh->sock, ptr, len, 0);
679 if(result == -1 && errno == EINTR) {
681 } else if(result <= 0) {
692 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
693 meshlink_handle_t *mesh = handle;
696 case SPTPS_HANDSHAKE:
697 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
700 return finalize_join(mesh, msg, len);
703 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
704 shutdown(mesh->sock, SHUT_RDWR);
705 mesh->success = true;
715 static bool recvline(meshlink_handle_t *mesh, size_t len) {
716 char *newline = NULL;
722 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
723 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
725 if(result == -1 && errno == EINTR) {
727 } else if(result <= 0) {
731 mesh->blen += result;
734 if((size_t)(newline - mesh->buffer) >= len) {
738 len = newline - mesh->buffer;
740 memcpy(mesh->line, mesh->buffer, len);
742 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
743 mesh->blen -= len + 1;
748 static bool sendline(int fd, char *format, ...) {
754 va_start(ap, format);
755 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
758 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
766 int result = send(fd, p, blen, MSG_NOSIGNAL);
768 if(result == -1 && errno == EINTR) {
770 } else if(result <= 0) {
781 static const char *errstr[] = {
782 [MESHLINK_OK] = "No error",
783 [MESHLINK_EINVAL] = "Invalid argument",
784 [MESHLINK_ENOMEM] = "Out of memory",
785 [MESHLINK_ENOENT] = "No such node",
786 [MESHLINK_EEXIST] = "Node already exists",
787 [MESHLINK_EINTERNAL] = "Internal error",
788 [MESHLINK_ERESOLV] = "Could not resolve hostname",
789 [MESHLINK_ESTORAGE] = "Storage error",
790 [MESHLINK_ENETWORK] = "Network error",
791 [MESHLINK_EPEER] = "Error communicating with peer",
792 [MESHLINK_ENOTSUP] = "Operation not supported",
793 [MESHLINK_EBUSY] = "MeshLink instance already in use",
796 const char *meshlink_strerror(meshlink_errno_t err) {
797 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
798 return "Invalid error code";
804 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
805 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
807 mesh->private_key = ecdsa_generate();
808 mesh->invitation_key = ecdsa_generate();
810 if(!mesh->private_key || !mesh->invitation_key) {
811 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
812 meshlink_errno = MESHLINK_EINTERNAL;
816 logger(mesh, MESHLINK_DEBUG, "Done.\n");
821 static struct timeval idle(event_loop_t *loop, void *data) {
823 meshlink_handle_t *mesh = data;
824 struct timeval t, tmin = {3600, 0};
826 for splay_each(node_t, n, mesh->nodes) {
831 t = utcp_timeout(n->utcp);
833 if(timercmp(&t, &tmin, <)) {
841 // Get our local address(es) by simulating connecting to an Internet host.
842 static void add_local_addresses(meshlink_handle_t *mesh) {
843 struct sockaddr_storage sn;
844 socklen_t sl = sizeof(sn);
848 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl, mesh->netns)) {
849 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
850 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
857 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl, mesh->netns)) {
858 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
859 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
863 static bool meshlink_setup(meshlink_handle_t *mesh) {
864 if(!config_init(mesh, "current")) {
865 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
866 meshlink_errno = MESHLINK_ESTORAGE;
870 if(!ecdsa_keygen(mesh)) {
871 meshlink_errno = MESHLINK_EINTERNAL;
875 if(check_port(mesh) == 0) {
876 meshlink_errno = MESHLINK_ENETWORK;
880 /* Create a node for ourself */
882 mesh->self = new_node();
883 mesh->self->name = xstrdup(mesh->name);
884 mesh->self->devclass = mesh->devclass;
885 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
887 if(!write_main_config_files(mesh)) {
888 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
889 meshlink_errno = MESHLINK_ESTORAGE;
893 if(!main_config_lock(mesh)) {
894 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
895 meshlink_errno = MESHLINK_ESTORAGE;
902 static bool meshlink_read_config(meshlink_handle_t *mesh) {
903 // Open the configuration file and lock it
904 if(!main_config_lock(mesh)) {
905 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
906 meshlink_errno = MESHLINK_ESTORAGE;
912 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
913 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
917 packmsg_input_t in = {config.buf, config.len};
918 const void *private_key;
919 const void *invitation_key;
921 uint32_t version = packmsg_get_uint32(&in);
922 char *name = packmsg_get_str_dup(&in);
923 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
924 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
925 uint16_t myport = packmsg_get_uint16(&in);
927 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
928 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
930 config_free(&config);
937 if(mesh->name && strcmp(mesh->name, name)) {
938 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
939 meshlink_errno = MESHLINK_ESTORAGE;
941 config_free(&config);
949 xasprintf(&mesh->myport, "%u", myport);
950 mesh->private_key = ecdsa_set_private_key(private_key);
951 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
952 config_free(&config);
954 /* Create a node for ourself and read our host configuration file */
956 mesh->self = new_node();
957 mesh->self->name = xstrdup(name);
958 mesh->self->devclass = mesh->devclass;
960 if(!node_read_public_key(mesh, mesh->self)) {
961 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
962 meshlink_errno = MESHLINK_ESTORAGE;
963 free_node(mesh->self);
972 static void *setup_network_in_netns_thread(void *arg) {
973 meshlink_handle_t *mesh = arg;
975 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
979 bool success = setup_network(mesh);
980 add_local_addresses(mesh);
981 return success ? arg : NULL;
985 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
986 if(!confbase || !*confbase) {
987 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
988 meshlink_errno = MESHLINK_EINVAL;
992 if(!appname || !*appname) {
993 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
994 meshlink_errno = MESHLINK_EINVAL;
998 if(strchr(appname, ' ')) {
999 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1000 meshlink_errno = MESHLINK_EINVAL;
1004 if(!name || !*name) {
1005 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1007 } else { //check name only if there is a name != NULL
1008 if(!check_id(name)) {
1009 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1010 meshlink_errno = MESHLINK_EINVAL;
1015 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1016 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1017 meshlink_errno = MESHLINK_EINVAL;
1021 meshlink_open_params_t *params = xzalloc(sizeof * params);
1023 params->confbase = xstrdup(confbase);
1024 params->name = xstrdup(name);
1025 params->appname = xstrdup(appname);
1026 params->devclass = devclass;
1032 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1034 meshlink_errno = MESHLINK_EINVAL;
1038 params->netns = netns;
1043 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1045 meshlink_errno = MESHLINK_EINVAL;
1049 if((!key && keylen) || (key && !keylen)) {
1050 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1051 meshlink_errno = MESHLINK_EINVAL;
1056 params->keylen = keylen;
1061 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1062 if(!mesh || !new_key || !new_keylen) {
1063 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1064 meshlink_errno = MESHLINK_EINVAL;
1068 pthread_mutex_lock(&(mesh->mesh_mutex));
1070 // Create hash for the new key
1071 void *new_config_key;
1072 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1074 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1075 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1076 meshlink_errno = MESHLINK_EINTERNAL;
1077 pthread_mutex_unlock(&(mesh->mesh_mutex));
1081 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1083 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1084 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1085 meshlink_errno = MESHLINK_ESTORAGE;
1086 pthread_mutex_unlock(&(mesh->mesh_mutex));
1090 devtool_keyrotate_probe(1);
1092 main_config_unlock(mesh);
1094 // Rename confbase/current/ to confbase/old
1096 if(!config_rename(mesh, "current", "old")) {
1097 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1098 meshlink_errno = MESHLINK_ESTORAGE;
1099 main_config_lock(mesh);
1100 pthread_mutex_unlock(&(mesh->mesh_mutex));
1104 devtool_keyrotate_probe(2);
1106 // Rename confbase/new/ to confbase/current
1108 if(!config_rename(mesh, "new", "current")) {
1109 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1110 meshlink_errno = MESHLINK_ESTORAGE;
1111 main_config_lock(mesh);
1112 pthread_mutex_unlock(&(mesh->mesh_mutex));
1116 devtool_keyrotate_probe(3);
1118 if(!main_config_lock(mesh)) {
1119 pthread_mutex_unlock(&(mesh->mesh_mutex));
1123 // Cleanup the "old" confbase sub-directory
1125 if(!config_destroy(mesh->confbase, "old")) {
1126 pthread_mutex_unlock(&(mesh->mesh_mutex));
1130 // Change the mesh handle key with new key
1132 free(mesh->config_key);
1133 mesh->config_key = new_config_key;
1135 pthread_mutex_unlock(&(mesh->mesh_mutex));
1140 void meshlink_open_params_free(meshlink_open_params_t *params) {
1142 meshlink_errno = MESHLINK_EINVAL;
1146 free(params->confbase);
1148 free(params->appname);
1153 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1154 if(!confbase || !*confbase) {
1155 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1156 meshlink_errno = MESHLINK_EINVAL;
1160 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1161 meshlink_open_params_t params;
1162 memset(¶ms, 0, sizeof(params));
1164 params.confbase = (char *)confbase;
1165 params.name = (char *)name;
1166 params.appname = (char *)appname;
1167 params.devclass = devclass;
1170 return meshlink_open_ex(¶ms);
1173 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) {
1174 if(!confbase || !*confbase) {
1175 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1176 meshlink_errno = MESHLINK_EINVAL;
1180 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1181 meshlink_open_params_t params = {NULL};
1183 params.confbase = (char *)confbase;
1184 params.name = (char *)name;
1185 params.appname = (char *)appname;
1186 params.devclass = devclass;
1189 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1193 return meshlink_open_ex(¶ms);
1196 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1197 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1198 meshlink_open_params_t params = {NULL};
1200 params.name = (char *)name;
1201 params.appname = (char *)appname;
1202 params.devclass = devclass;
1205 return meshlink_open_ex(¶ms);
1208 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1209 // Validate arguments provided by the application
1210 bool usingname = false;
1212 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1214 if(!params->appname || !*params->appname) {
1215 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1216 meshlink_errno = MESHLINK_EINVAL;
1220 if(strchr(params->appname, ' ')) {
1221 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1222 meshlink_errno = MESHLINK_EINVAL;
1226 if(!params->name || !*params->name) {
1227 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1229 } else { //check name only if there is a name != NULL
1231 if(!check_id(params->name)) {
1232 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1233 meshlink_errno = MESHLINK_EINVAL;
1240 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1241 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1242 meshlink_errno = MESHLINK_EINVAL;
1246 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1247 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1248 meshlink_errno = MESHLINK_EINVAL;
1252 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1254 if(params->confbase) {
1255 mesh->confbase = xstrdup(params->confbase);
1258 mesh->appname = xstrdup(params->appname);
1259 mesh->devclass = params->devclass;
1260 mesh->discovery = true;
1261 mesh->invitation_timeout = 604800; // 1 week
1262 mesh->netns = params->netns;
1263 mesh->submeshes = NULL;
1266 mesh->name = xstrdup(params->name);
1271 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1273 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1274 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1275 meshlink_close(mesh);
1276 meshlink_errno = MESHLINK_EINTERNAL;
1282 pthread_mutexattr_t attr;
1283 pthread_mutexattr_init(&attr);
1284 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1285 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1287 mesh->threadstarted = false;
1288 event_loop_init(&mesh->loop);
1289 mesh->loop.data = mesh;
1291 meshlink_queue_init(&mesh->outpacketqueue);
1293 // If no configuration exists yet, create it.
1295 if(!meshlink_confbase_exists(mesh)) {
1296 if(!meshlink_setup(mesh)) {
1297 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1298 meshlink_close(mesh);
1302 if(!meshlink_read_config(mesh)) {
1303 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1304 meshlink_close(mesh);
1310 struct WSAData wsa_state;
1311 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1314 // Setup up everything
1315 // TODO: we should not open listening sockets yet
1317 bool success = false;
1319 if(mesh->netns != -1) {
1323 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1324 void *retval = NULL;
1325 success = pthread_join(thr, &retval) == 0 && retval;
1329 meshlink_errno = MESHLINK_EINTERNAL;
1332 #endif // HAVE_SETNS
1334 success = setup_network(mesh);
1335 add_local_addresses(mesh);
1339 meshlink_close(mesh);
1340 meshlink_errno = MESHLINK_ENETWORK;
1344 add_local_addresses(mesh);
1345 node_write_config(mesh, mesh->self);
1347 idle_set(&mesh->loop, idle, mesh);
1349 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1353 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1354 meshlink_submesh_t *s = NULL;
1357 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1358 meshlink_errno = MESHLINK_EINVAL;
1362 if(!submesh || !*submesh) {
1363 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1364 meshlink_errno = MESHLINK_EINVAL;
1369 pthread_mutex_lock(&(mesh->mesh_mutex));
1371 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1373 pthread_mutex_unlock(&(mesh->mesh_mutex));
1378 static void *meshlink_main_loop(void *arg) {
1379 meshlink_handle_t *mesh = arg;
1381 if(mesh->netns != -1) {
1384 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1390 #endif // HAVE_SETNS
1393 pthread_mutex_lock(&(mesh->mesh_mutex));
1397 if(mesh->discovery) {
1398 discovery_start(mesh);
1403 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1405 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1410 if(mesh->discovery) {
1411 discovery_stop(mesh);
1416 pthread_mutex_unlock(&(mesh->mesh_mutex));
1420 bool meshlink_start(meshlink_handle_t *mesh) {
1422 assert(mesh->private_key);
1425 meshlink_errno = MESHLINK_EINVAL;
1429 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1431 pthread_mutex_lock(&(mesh->mesh_mutex));
1433 if(mesh->threadstarted) {
1434 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1435 pthread_mutex_unlock(&(mesh->mesh_mutex));
1439 if(mesh->listen_socket[0].tcp.fd < 0) {
1440 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1441 meshlink_errno = MESHLINK_ENETWORK;
1445 mesh->thedatalen = 0;
1447 // TODO: open listening sockets first
1449 //Check that a valid name is set
1451 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1452 meshlink_errno = MESHLINK_EINVAL;
1453 pthread_mutex_unlock(&(mesh->mesh_mutex));
1457 init_outgoings(mesh);
1459 // Start the main thread
1461 event_loop_start(&mesh->loop);
1463 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1464 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1465 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1466 meshlink_errno = MESHLINK_EINTERNAL;
1467 event_loop_stop(&mesh->loop);
1468 pthread_mutex_unlock(&(mesh->mesh_mutex));
1472 mesh->threadstarted = true;
1474 assert(mesh->self->ecdsa);
1475 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1478 pthread_mutex_unlock(&(mesh->mesh_mutex));
1482 void meshlink_stop(meshlink_handle_t *mesh) {
1484 meshlink_errno = MESHLINK_EINVAL;
1488 pthread_mutex_lock(&(mesh->mesh_mutex));
1489 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1491 // Shut down the main thread
1492 event_loop_stop(&mesh->loop);
1494 // Send ourselves a UDP packet to kick the event loop
1495 for(int i = 0; i < mesh->listen_sockets; i++) {
1497 socklen_t salen = sizeof(sa.sa);
1499 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1500 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1504 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1505 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1509 if(mesh->threadstarted) {
1510 // Wait for the main thread to finish
1511 pthread_mutex_unlock(&(mesh->mesh_mutex));
1512 pthread_join(mesh->thread, NULL);
1513 pthread_mutex_lock(&(mesh->mesh_mutex));
1515 mesh->threadstarted = false;
1518 // Close all metaconnections
1519 if(mesh->connections) {
1520 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1522 connection_t *c = node->data;
1524 terminate_connection(mesh, c, false);
1528 exit_outgoings(mesh);
1530 // Write out any changed node config files
1532 for splay_each(node_t, n, mesh->nodes) {
1533 if(n->status.dirty) {
1534 node_write_config(mesh, n);
1535 n->status.dirty = false;
1540 pthread_mutex_unlock(&(mesh->mesh_mutex));
1543 void meshlink_close(meshlink_handle_t *mesh) {
1545 meshlink_errno = MESHLINK_EINVAL;
1549 // stop can be called even if mesh has not been started
1550 meshlink_stop(mesh);
1552 // lock is not released after this
1553 pthread_mutex_lock(&(mesh->mesh_mutex));
1555 // Close and free all resources used.
1557 close_network_connections(mesh);
1559 logger(mesh, MESHLINK_INFO, "Terminating");
1561 event_loop_exit(&mesh->loop);
1565 if(mesh->confbase) {
1571 ecdsa_free(mesh->invitation_key);
1573 if(mesh->netns != -1) {
1578 free(mesh->appname);
1579 free(mesh->confbase);
1580 free(mesh->config_key);
1581 ecdsa_free(mesh->private_key);
1582 pthread_mutex_destroy(&(mesh->mesh_mutex));
1584 main_config_unlock(mesh);
1586 memset(mesh, 0, sizeof(*mesh));
1591 bool meshlink_destroy(const char *confbase) {
1593 meshlink_errno = MESHLINK_EINVAL;
1597 if(!config_destroy(confbase, "current")) {
1598 logger(NULL, MESHLINK_ERROR, "Cannot remove confbase sub-directories %s: %s\n", confbase, strerror(errno));
1602 config_destroy(confbase, "new");
1603 config_destroy(confbase, "old");
1605 if(rmdir(confbase) && errno != ENOENT) {
1606 logger(NULL, MESHLINK_ERROR, "Cannot remove directory %s: %s\n", confbase, strerror(errno));
1607 meshlink_errno = MESHLINK_ESTORAGE;
1614 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1616 meshlink_errno = MESHLINK_EINVAL;
1620 pthread_mutex_lock(&(mesh->mesh_mutex));
1621 mesh->receive_cb = cb;
1622 pthread_mutex_unlock(&(mesh->mesh_mutex));
1625 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1627 meshlink_errno = MESHLINK_EINVAL;
1631 pthread_mutex_lock(&(mesh->mesh_mutex));
1632 mesh->connection_try_cb = cb;
1633 pthread_mutex_unlock(&(mesh->mesh_mutex));
1636 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1638 meshlink_errno = MESHLINK_EINVAL;
1642 pthread_mutex_lock(&(mesh->mesh_mutex));
1643 mesh->node_status_cb = cb;
1644 pthread_mutex_unlock(&(mesh->mesh_mutex));
1647 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1649 meshlink_errno = MESHLINK_EINVAL;
1653 pthread_mutex_lock(&(mesh->mesh_mutex));
1654 mesh->node_duplicate_cb = cb;
1655 pthread_mutex_unlock(&(mesh->mesh_mutex));
1658 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1660 pthread_mutex_lock(&(mesh->mesh_mutex));
1662 mesh->log_level = cb ? level : 0;
1663 pthread_mutex_unlock(&(mesh->mesh_mutex));
1666 global_log_level = cb ? level : 0;
1670 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1671 meshlink_packethdr_t *hdr;
1673 // Validate arguments
1674 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1675 meshlink_errno = MESHLINK_EINVAL;
1684 meshlink_errno = MESHLINK_EINVAL;
1688 node_t *n = (node_t *)destination;
1690 if(n->status.blacklisted) {
1691 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1695 // Prepare the packet
1696 vpn_packet_t *packet = malloc(sizeof(*packet));
1699 meshlink_errno = MESHLINK_ENOMEM;
1703 packet->probe = false;
1704 packet->tcp = false;
1705 packet->len = len + sizeof(*hdr);
1707 hdr = (meshlink_packethdr_t *)packet->data;
1708 memset(hdr, 0, sizeof(*hdr));
1709 // leave the last byte as 0 to make sure strings are always
1710 // null-terminated if they are longer than the buffer
1711 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1712 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1714 memcpy(packet->data + sizeof(*hdr), data, len);
1717 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1719 meshlink_errno = MESHLINK_ENOMEM;
1723 // Notify event loop
1724 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1729 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1731 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1737 mesh->self->in_packets++;
1738 mesh->self->in_bytes += packet->len;
1739 route(mesh, mesh->self, packet);
1742 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1743 if(!mesh || !destination) {
1744 meshlink_errno = MESHLINK_EINVAL;
1748 pthread_mutex_lock(&(mesh->mesh_mutex));
1750 node_t *n = (node_t *)destination;
1752 if(!n->status.reachable) {
1753 pthread_mutex_unlock(&(mesh->mesh_mutex));
1756 } else if(n->mtuprobes > 30 && n->minmtu) {
1757 pthread_mutex_unlock(&(mesh->mesh_mutex));
1760 pthread_mutex_unlock(&(mesh->mesh_mutex));
1765 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1766 if(!mesh || !node) {
1767 meshlink_errno = MESHLINK_EINVAL;
1771 pthread_mutex_lock(&(mesh->mesh_mutex));
1773 node_t *n = (node_t *)node;
1775 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1776 meshlink_errno = MESHLINK_EINTERNAL;
1777 pthread_mutex_unlock(&(mesh->mesh_mutex));
1781 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1784 meshlink_errno = MESHLINK_EINTERNAL;
1787 pthread_mutex_unlock(&(mesh->mesh_mutex));
1791 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1793 meshlink_errno = MESHLINK_EINVAL;
1797 return (meshlink_node_t *)mesh->self;
1800 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1801 if(!mesh || !name) {
1802 meshlink_errno = MESHLINK_EINVAL;
1806 meshlink_node_t *node = NULL;
1808 pthread_mutex_lock(&(mesh->mesh_mutex));
1809 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1810 pthread_mutex_unlock(&(mesh->mesh_mutex));
1814 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1815 if(!mesh || !name) {
1816 meshlink_errno = MESHLINK_EINVAL;
1820 meshlink_submesh_t *submesh = NULL;
1822 pthread_mutex_lock(&(mesh->mesh_mutex));
1823 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1824 pthread_mutex_unlock(&(mesh->mesh_mutex));
1828 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1829 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1830 meshlink_errno = MESHLINK_EINVAL;
1834 meshlink_node_t **result;
1837 pthread_mutex_lock(&(mesh->mesh_mutex));
1839 *nmemb = mesh->nodes->count;
1840 result = realloc(nodes, *nmemb * sizeof(*nodes));
1843 meshlink_node_t **p = result;
1845 for splay_each(node_t, n, mesh->nodes) {
1846 *p++ = (meshlink_node_t *)n;
1851 meshlink_errno = MESHLINK_ENOMEM;
1854 pthread_mutex_unlock(&(mesh->mesh_mutex));
1859 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) {
1860 meshlink_node_t **result;
1862 pthread_mutex_lock(&(mesh->mesh_mutex));
1866 for splay_each(node_t, n, mesh->nodes) {
1867 if(true == search_node(n, condition)) {
1868 *nmemb = *nmemb + 1;
1874 pthread_mutex_unlock(&(mesh->mesh_mutex));
1878 result = realloc(nodes, *nmemb * sizeof(*nodes));
1881 meshlink_node_t **p = result;
1883 for splay_each(node_t, n, mesh->nodes) {
1884 if(true == search_node(n, condition)) {
1885 *p++ = (meshlink_node_t *)n;
1891 meshlink_errno = MESHLINK_ENOMEM;
1894 pthread_mutex_unlock(&(mesh->mesh_mutex));
1899 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1900 dev_class_t *devclass = (dev_class_t *)condition;
1902 if(*devclass == (dev_class_t)node->devclass) {
1909 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1910 if(condition == node->submesh) {
1917 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) {
1918 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1919 meshlink_errno = MESHLINK_EINVAL;
1923 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1926 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1927 if(!mesh || !submesh || !nmemb) {
1928 meshlink_errno = MESHLINK_EINVAL;
1932 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1935 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1936 if(!mesh || !node) {
1937 meshlink_errno = MESHLINK_EINVAL;
1941 dev_class_t devclass;
1943 pthread_mutex_lock(&(mesh->mesh_mutex));
1945 devclass = ((node_t *)node)->devclass;
1947 pthread_mutex_unlock(&(mesh->mesh_mutex));
1952 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1953 if(!mesh || !node) {
1954 meshlink_errno = MESHLINK_EINVAL;
1958 node_t *n = (node_t *)node;
1960 meshlink_submesh_t *s;
1962 s = (meshlink_submesh_t *)n->submesh;
1967 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1968 if(!mesh || !data || !len || !signature || !siglen) {
1969 meshlink_errno = MESHLINK_EINVAL;
1973 if(*siglen < MESHLINK_SIGLEN) {
1974 meshlink_errno = MESHLINK_EINVAL;
1978 pthread_mutex_lock(&(mesh->mesh_mutex));
1980 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1981 meshlink_errno = MESHLINK_EINTERNAL;
1982 pthread_mutex_unlock(&(mesh->mesh_mutex));
1986 *siglen = MESHLINK_SIGLEN;
1987 pthread_mutex_unlock(&(mesh->mesh_mutex));
1991 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1992 if(!mesh || !data || !len || !signature) {
1993 meshlink_errno = MESHLINK_EINVAL;
1997 if(siglen != MESHLINK_SIGLEN) {
1998 meshlink_errno = MESHLINK_EINVAL;
2002 pthread_mutex_lock(&(mesh->mesh_mutex));
2006 struct node_t *n = (struct node_t *)source;
2008 if(!node_read_public_key(mesh, n)) {
2009 meshlink_errno = MESHLINK_EINTERNAL;
2012 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2015 pthread_mutex_unlock(&(mesh->mesh_mutex));
2019 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2020 pthread_mutex_lock(&(mesh->mesh_mutex));
2022 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2025 // TODO: Update invitation key if necessary?
2028 pthread_mutex_unlock(&(mesh->mesh_mutex));
2030 return mesh->invitation_key;
2033 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2034 if(!mesh || !node || !address) {
2035 meshlink_errno = MESHLINK_EINVAL;
2039 if(!is_valid_hostname(address)) {
2040 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2041 meshlink_errno = MESHLINK_EINVAL;
2045 if(port && !is_valid_port(port)) {
2046 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2047 meshlink_errno = MESHLINK_EINVAL;
2051 char *canonical_address;
2054 xasprintf(&canonical_address, "%s %s", address, port);
2056 canonical_address = xstrdup(address);
2059 pthread_mutex_lock(&(mesh->mesh_mutex));
2061 node_t *n = (node_t *)node;
2062 free(n->canonical_address);
2063 n->canonical_address = canonical_address;
2064 node_write_config(mesh, n);
2066 pthread_mutex_unlock(&(mesh->mesh_mutex));
2071 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2072 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2075 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2077 meshlink_errno = MESHLINK_EINVAL;
2081 char *address = meshlink_get_external_address(mesh);
2087 bool rval = meshlink_add_address(mesh, address);
2093 int meshlink_get_port(meshlink_handle_t *mesh) {
2095 meshlink_errno = MESHLINK_EINVAL;
2100 meshlink_errno = MESHLINK_EINTERNAL;
2104 return atoi(mesh->myport);
2107 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2108 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2109 meshlink_errno = MESHLINK_EINVAL;
2113 if(mesh->myport && port == atoi(mesh->myport)) {
2117 if(!try_bind(port)) {
2118 meshlink_errno = MESHLINK_ENETWORK;
2122 devtool_trybind_probe();
2126 pthread_mutex_lock(&(mesh->mesh_mutex));
2128 if(mesh->threadstarted) {
2129 meshlink_errno = MESHLINK_EINVAL;
2134 xasprintf(&mesh->myport, "%d", port);
2136 /* Write meshlink.conf with the updated port number */
2137 write_main_config_files(mesh);
2139 /* Close down the network. This also deletes mesh->self. */
2140 close_network_connections(mesh);
2142 /* Recreate mesh->self. */
2143 mesh->self = new_node();
2144 mesh->self->name = xstrdup(mesh->name);
2145 mesh->self->devclass = mesh->devclass;
2146 xasprintf(&mesh->myport, "%d", port);
2148 if(!node_read_public_key(mesh, mesh->self)) {
2149 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2150 meshlink_errno = MESHLINK_ESTORAGE;
2151 free_node(mesh->self);
2153 } else if(!setup_network(mesh)) {
2154 meshlink_errno = MESHLINK_ENETWORK;
2160 pthread_mutex_unlock(&(mesh->mesh_mutex));
2162 return rval && meshlink_get_port(mesh) == port;
2165 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2166 mesh->invitation_timeout = timeout;
2169 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2170 meshlink_submesh_t *s = NULL;
2173 meshlink_errno = MESHLINK_EINVAL;
2178 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2181 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2182 meshlink_errno = MESHLINK_EINVAL;
2186 s = (meshlink_submesh_t *)mesh->self->submesh;
2189 pthread_mutex_lock(&(mesh->mesh_mutex));
2191 // Check validity of the new node's name
2192 if(!check_id(name)) {
2193 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2194 meshlink_errno = MESHLINK_EINVAL;
2195 pthread_mutex_unlock(&(mesh->mesh_mutex));
2199 // Ensure no host configuration file with that name exists
2200 if(config_exists(mesh, "current", name)) {
2201 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2202 meshlink_errno = MESHLINK_EEXIST;
2203 pthread_mutex_unlock(&(mesh->mesh_mutex));
2207 // Ensure no other nodes know about this name
2208 if(meshlink_get_node(mesh, name)) {
2209 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2210 meshlink_errno = MESHLINK_EEXIST;
2211 pthread_mutex_unlock(&(mesh->mesh_mutex));
2215 // Get the local address
2216 char *address = get_my_hostname(mesh, flags);
2219 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2220 meshlink_errno = MESHLINK_ERESOLV;
2221 pthread_mutex_unlock(&(mesh->mesh_mutex));
2225 if(!refresh_invitation_key(mesh)) {
2226 meshlink_errno = MESHLINK_EINTERNAL;
2227 pthread_mutex_unlock(&(mesh->mesh_mutex));
2233 // Create a hash of the key.
2234 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2235 sha512(fingerprint, strlen(fingerprint), hash);
2236 b64encode_urlsafe(hash, hash, 18);
2238 // Create a random cookie for this invitation.
2240 randomize(cookie, 18);
2242 // Create a filename that doesn't reveal the cookie itself
2243 char buf[18 + strlen(fingerprint)];
2244 char cookiehash[64];
2245 memcpy(buf, cookie, 18);
2246 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2247 sha512(buf, sizeof(buf), cookiehash);
2248 b64encode_urlsafe(cookiehash, cookiehash, 18);
2250 b64encode_urlsafe(cookie, cookie, 18);
2254 /* Construct the invitation file */
2255 uint8_t outbuf[4096];
2256 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2258 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2259 packmsg_add_str(&inv, name);
2260 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2261 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2263 /* TODO: Add several host config files to bootstrap connections.
2264 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2265 * and are not blacklisted.
2267 config_t configs[5] = {NULL};
2270 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2274 /* Append host config files to the invitation file */
2275 packmsg_add_array(&inv, count);
2277 for(int i = 0; i < count; i++) {
2278 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2279 config_free(&configs[i]);
2282 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2284 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2285 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2286 meshlink_errno = MESHLINK_ESTORAGE;
2287 pthread_mutex_unlock(&(mesh->mesh_mutex));
2291 // Create an URL from the local address, key hash and cookie
2293 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2296 pthread_mutex_unlock(&(mesh->mesh_mutex));
2300 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2301 return meshlink_invite_ex(mesh, submesh, name, 0);
2304 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2305 if(!mesh || !invitation) {
2306 meshlink_errno = MESHLINK_EINVAL;
2310 pthread_mutex_lock(&(mesh->mesh_mutex));
2312 //Before doing meshlink_join make sure we are not connected to another mesh
2313 if(mesh->threadstarted) {
2314 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2315 meshlink_errno = MESHLINK_EINVAL;
2316 pthread_mutex_unlock(&(mesh->mesh_mutex));
2320 // 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.
2321 if(mesh->nodes->count > 1) {
2322 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2323 meshlink_errno = MESHLINK_EINVAL;
2324 pthread_mutex_unlock(&(mesh->mesh_mutex));
2328 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2329 char copy[strlen(invitation) + 1];
2330 strcpy(copy, invitation);
2332 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2334 char *slash = strchr(copy, '/');
2342 if(strlen(slash) != 48) {
2346 char *address = copy;
2349 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2353 // Generate a throw-away key for the invitation.
2354 ecdsa_t *key = ecdsa_generate();
2357 meshlink_errno = MESHLINK_EINTERNAL;
2358 pthread_mutex_unlock(&(mesh->mesh_mutex));
2362 char *b64key = ecdsa_get_base64_public_key(key);
2366 while(address && *address) {
2367 // We allow commas in the address part to support multiple addresses in one invitation URL.
2368 comma = strchr(address, ',');
2374 // Split of the port
2375 port = strrchr(address, ':');
2383 // IPv6 address are enclosed in brackets, per RFC 3986
2384 if(*address == '[') {
2386 char *bracket = strchr(address, ']');
2399 // Connect to the meshlink daemon mentioned in the URL.
2400 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2403 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2404 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2406 if(mesh->sock == -1) {
2407 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2408 meshlink_errno = MESHLINK_ENETWORK;
2412 set_timeout(mesh->sock, 5000);
2414 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2415 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2416 meshlink_errno = MESHLINK_ENETWORK;
2417 closesocket(mesh->sock);
2425 meshlink_errno = MESHLINK_ERESOLV;
2428 if(mesh->sock != -1 || !comma) {
2435 if(mesh->sock == -1) {
2436 pthread_mutex_unlock(&mesh->mesh_mutex);
2440 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2442 // Tell him we have an invitation, and give him our throw-away key.
2446 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2447 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2448 closesocket(mesh->sock);
2449 meshlink_errno = MESHLINK_ENETWORK;
2450 pthread_mutex_unlock(&(mesh->mesh_mutex));
2456 char hisname[4096] = "";
2457 int code, hismajor, hisminor = 0;
2459 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) {
2460 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2461 closesocket(mesh->sock);
2462 meshlink_errno = MESHLINK_ENETWORK;
2463 pthread_mutex_unlock(&(mesh->mesh_mutex));
2467 // Check if the hash of the key he gave us matches the hash in the URL.
2468 char *fingerprint = mesh->line + 2;
2471 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2472 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2473 meshlink_errno = MESHLINK_EINTERNAL;
2474 pthread_mutex_unlock(&(mesh->mesh_mutex));
2478 if(memcmp(hishash, mesh->hash, 18)) {
2479 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2480 meshlink_errno = MESHLINK_EPEER;
2481 pthread_mutex_unlock(&(mesh->mesh_mutex));
2486 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2489 meshlink_errno = MESHLINK_EINTERNAL;
2490 pthread_mutex_unlock(&(mesh->mesh_mutex));
2494 // Start an SPTPS session
2495 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2496 meshlink_errno = MESHLINK_EINTERNAL;
2497 pthread_mutex_unlock(&(mesh->mesh_mutex));
2501 // Feed rest of input buffer to SPTPS
2502 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2503 meshlink_errno = MESHLINK_EPEER;
2504 pthread_mutex_unlock(&(mesh->mesh_mutex));
2510 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2512 if(errno == EINTR) {
2516 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2517 meshlink_errno = MESHLINK_ENETWORK;
2518 pthread_mutex_unlock(&(mesh->mesh_mutex));
2522 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2523 meshlink_errno = MESHLINK_EPEER;
2524 pthread_mutex_unlock(&(mesh->mesh_mutex));
2529 sptps_stop(&mesh->sptps);
2532 closesocket(mesh->sock);
2534 if(!mesh->success) {
2535 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2536 meshlink_errno = MESHLINK_EPEER;
2537 pthread_mutex_unlock(&(mesh->mesh_mutex));
2541 pthread_mutex_unlock(&(mesh->mesh_mutex));
2545 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2546 meshlink_errno = MESHLINK_EINVAL;
2547 pthread_mutex_unlock(&(mesh->mesh_mutex));
2551 char *meshlink_export(meshlink_handle_t *mesh) {
2553 meshlink_errno = MESHLINK_EINVAL;
2557 // Create a config file on the fly.
2560 packmsg_output_t out = {buf, sizeof(buf)};
2561 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2562 packmsg_add_str(&out, mesh->name);
2563 packmsg_add_str(&out, CORE_MESH);
2565 pthread_mutex_lock(&(mesh->mesh_mutex));
2567 packmsg_add_int32(&out, mesh->self->devclass);
2568 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2569 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2570 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2574 for(uint32_t i = 0; i < 5; i++) {
2575 if(mesh->self->recent[i].sa.sa_family) {
2582 packmsg_add_array(&out, count);
2584 for(uint32_t i = 0; i < count; i++) {
2585 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2588 pthread_mutex_unlock(&(mesh->mesh_mutex));
2590 if(!packmsg_output_ok(&out)) {
2591 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2592 meshlink_errno = MESHLINK_EINTERNAL;
2596 // Prepare a base64-encoded packmsg array containing our config file
2598 uint32_t len = packmsg_output_size(&out, buf);
2599 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2600 uint8_t *buf2 = xmalloc(len2);
2601 packmsg_output_t out2 = {buf2, len2};
2602 packmsg_add_array(&out2, 1);
2603 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2605 if(!packmsg_output_ok(&out2)) {
2606 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2607 meshlink_errno = MESHLINK_EINTERNAL;
2612 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2614 return (char *)buf2;
2617 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2618 if(!mesh || !data) {
2619 meshlink_errno = MESHLINK_EINVAL;
2623 size_t datalen = strlen(data);
2624 uint8_t *buf = xmalloc(datalen);
2625 int buflen = b64decode(data, buf, datalen);
2628 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2629 meshlink_errno = MESHLINK_EPEER;
2633 packmsg_input_t in = {buf, buflen};
2634 uint32_t count = packmsg_get_array(&in);
2637 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2638 meshlink_errno = MESHLINK_EPEER;
2642 pthread_mutex_lock(&(mesh->mesh_mutex));
2646 uint32_t len = packmsg_get_bin_raw(&in, &data);
2652 packmsg_input_t in2 = {data, len};
2653 uint32_t version = packmsg_get_uint32(&in2);
2654 char *name = packmsg_get_str_dup(&in2);
2656 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2658 packmsg_input_invalidate(&in);
2662 if(!check_id(name)) {
2667 node_t *n = lookup_node(mesh, name);
2670 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2678 config_t config = {data, len};
2680 if(!node_read_from_config(mesh, n, &config)) {
2682 packmsg_input_invalidate(&in);
2686 config_write(mesh, "current", n->name, &config, mesh->config_key);
2690 pthread_mutex_unlock(&(mesh->mesh_mutex));
2692 if(!packmsg_done(&in)) {
2693 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2694 meshlink_errno = MESHLINK_EPEER;
2701 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2702 if(!mesh || !node) {
2703 meshlink_errno = MESHLINK_EINVAL;
2707 pthread_mutex_lock(&(mesh->mesh_mutex));
2712 if(n == mesh->self) {
2713 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2714 meshlink_errno = MESHLINK_EINVAL;
2715 pthread_mutex_unlock(&(mesh->mesh_mutex));
2719 if(n->status.blacklisted) {
2720 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2721 pthread_mutex_unlock(&(mesh->mesh_mutex));
2725 n->status.blacklisted = true;
2726 node_write_config(mesh, n);
2727 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2729 //Immediately terminate any connections we have with the blacklisted node
2730 for list_each(connection_t, c, mesh->connections) {
2732 terminate_connection(mesh, c, c->status.active);
2736 utcp_abort_all_connections(n->utcp);
2742 n->status.udp_confirmed = false;
2744 if(n->status.reachable) {
2745 update_node_status(mesh, n);
2748 pthread_mutex_unlock(&(mesh->mesh_mutex));
2751 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2752 if(!mesh || !node) {
2753 meshlink_errno = MESHLINK_EINVAL;
2757 pthread_mutex_lock(&(mesh->mesh_mutex));
2759 node_t *n = (node_t *)node;
2761 if(!n->status.blacklisted) {
2762 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2763 meshlink_errno = MESHLINK_EINVAL;
2764 pthread_mutex_unlock(&(mesh->mesh_mutex));
2768 n->status.blacklisted = false;
2769 node_write_config(mesh, n);
2771 pthread_mutex_unlock(&(mesh->mesh_mutex));
2775 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2776 mesh->default_blacklist = blacklist;
2779 /* Hint that a hostname may be found at an address
2780 * See header file for detailed comment.
2782 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2783 if(!mesh || !node || !addr) {
2784 meshlink_errno = EINVAL;
2788 pthread_mutex_lock(&(mesh->mesh_mutex));
2790 node_t *n = (node_t *)node;
2791 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2792 memcpy(n->recent, addr, SALEN(*addr));
2793 node_write_config(mesh, n);
2795 pthread_mutex_unlock(&(mesh->mesh_mutex));
2796 // @TODO do we want to fire off a connection attempt right away?
2799 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2801 node_t *n = utcp->priv;
2802 meshlink_handle_t *mesh = n->mesh;
2803 return mesh->channel_accept_cb;
2806 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2807 meshlink_channel_t *channel = connection->priv;
2813 node_t *n = channel->node;
2814 meshlink_handle_t *mesh = n->mesh;
2816 if(n->status.destroyed) {
2817 meshlink_channel_close(mesh, channel);
2818 } else if(channel->receive_cb) {
2819 channel->receive_cb(mesh, channel, data, len);
2825 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2826 node_t *n = utcp_connection->utcp->priv;
2832 meshlink_handle_t *mesh = n->mesh;
2834 if(!mesh->channel_accept_cb) {
2838 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2840 channel->c = utcp_connection;
2842 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2843 utcp_accept(utcp_connection, channel_recv, channel);
2849 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2850 node_t *n = utcp->priv;
2852 if(n->status.destroyed) {
2856 meshlink_handle_t *mesh = n->mesh;
2857 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2860 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2861 if(!mesh || !channel) {
2862 meshlink_errno = MESHLINK_EINVAL;
2866 channel->receive_cb = cb;
2869 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2871 node_t *n = (node_t *)source;
2877 utcp_recv(n->utcp, data, len);
2880 static void channel_poll(struct utcp_connection *connection, size_t len) {
2881 meshlink_channel_t *channel = connection->priv;
2887 node_t *n = channel->node;
2888 meshlink_handle_t *mesh = n->mesh;
2890 if(channel->poll_cb) {
2891 channel->poll_cb(mesh, channel, len);
2895 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2897 channel->poll_cb = cb;
2898 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2901 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2903 meshlink_errno = MESHLINK_EINVAL;
2907 pthread_mutex_lock(&mesh->mesh_mutex);
2908 mesh->channel_accept_cb = cb;
2909 mesh->receive_cb = channel_receive;
2911 for splay_each(node_t, n, mesh->nodes) {
2912 if(!n->utcp && n != mesh->self) {
2913 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2917 pthread_mutex_unlock(&mesh->mesh_mutex);
2920 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) {
2922 abort(); // TODO: handle non-NULL data
2925 if(!mesh || !node) {
2926 meshlink_errno = MESHLINK_EINVAL;
2930 node_t *n = (node_t *)node;
2933 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2934 mesh->receive_cb = channel_receive;
2937 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2942 if(n->status.blacklisted) {
2943 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2947 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2949 channel->receive_cb = cb;
2950 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2953 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2961 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) {
2962 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2965 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2966 if(!mesh || !channel) {
2967 meshlink_errno = MESHLINK_EINVAL;
2971 utcp_shutdown(channel->c, direction);
2974 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2975 if(!mesh || !channel) {
2976 meshlink_errno = MESHLINK_EINVAL;
2980 utcp_close(channel->c);
2984 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2985 if(!mesh || !channel) {
2986 meshlink_errno = MESHLINK_EINVAL;
2995 meshlink_errno = MESHLINK_EINVAL;
2999 // TODO: more finegrained locking.
3000 // Ideally we want to put the data into the UTCP connection's send buffer.
3001 // Then, preferably only if there is room in the receiver window,
3002 // kick the meshlink thread to go send packets.
3004 pthread_mutex_lock(&mesh->mesh_mutex);
3005 ssize_t retval = utcp_send(channel->c, data, len);
3006 pthread_mutex_unlock(&mesh->mesh_mutex);
3009 meshlink_errno = MESHLINK_ENETWORK;
3015 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3016 if(!mesh || !channel) {
3017 meshlink_errno = MESHLINK_EINVAL;
3021 return channel->c->flags;
3024 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3025 if(!mesh || !channel) {
3026 meshlink_errno = MESHLINK_EINVAL;
3030 return utcp_get_sendq(channel->c);
3033 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3034 if(!mesh || !channel) {
3035 meshlink_errno = MESHLINK_EINVAL;
3039 return utcp_get_recvq(channel->c);
3042 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3043 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3044 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3047 if(mesh->node_status_cb) {
3048 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3052 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3053 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3057 n->status.duplicate = true;
3058 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3061 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3065 meshlink_errno = MESHLINK_EINVAL;
3069 pthread_mutex_lock(&mesh->mesh_mutex);
3071 if(mesh->discovery == enable) {
3075 if(mesh->threadstarted) {
3077 discovery_start(mesh);
3079 discovery_stop(mesh);
3083 mesh->discovery = enable;
3086 pthread_mutex_unlock(&mesh->mesh_mutex);
3090 meshlink_errno = MESHLINK_ENOTSUP;
3094 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3097 if(!mesh->connections) {
3104 static void __attribute__((constructor)) meshlink_init(void) {
3107 randomize(&seed, sizeof(seed));
3111 static void __attribute__((destructor)) meshlink_exit(void) {
3115 /// Device class traits
3116 const dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
3117 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
3118 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3119 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3120 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN