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])) {
336 if(found || !is_valid_hostname(host[i])) {
346 // This gets the hostname part for use in invitation URLs
347 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
348 char *hostname[4] = {NULL};
349 char *port[4] = {NULL};
350 char *hostport = NULL;
352 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
353 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
356 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
357 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
360 // Add local addresses if requested
361 if(flags & MESHLINK_INVITE_LOCAL) {
362 if(flags & MESHLINK_INVITE_IPV4) {
363 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
366 if(flags & MESHLINK_INVITE_IPV6) {
367 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
371 // Add public/canonical addresses if requested
372 if(flags & MESHLINK_INVITE_PUBLIC) {
373 // Try the CanonicalAddress first
374 get_canonical_address(mesh->self, &hostname[2], &port[2]);
377 if(flags & MESHLINK_INVITE_IPV4) {
378 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
381 if(flags & MESHLINK_INVITE_IPV6) {
382 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
387 for(int i = 0; i < 4; i++) {
388 // Ensure we always have a port number
389 if(hostname[i] && !port[i]) {
390 port[i] = xstrdup(mesh->myport);
394 remove_duplicate_hostnames(hostname, port, 4);
396 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
397 for(int i = 0; i < 4; i++) {
402 // Convert what we have to a sockaddr
403 struct addrinfo *ai_in, *ai_out;
404 struct addrinfo hint = {
405 .ai_family = AF_UNSPEC,
406 .ai_flags = AI_NUMERICSERV,
407 .ai_socktype = SOCK_STREAM,
409 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
415 // Convert it to a hostname
416 char resolved_host[NI_MAXHOST];
417 char resolved_port[NI_MAXSERV];
418 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
420 if(err || !is_valid_hostname(resolved_host)) {
425 // Convert the hostname back to a sockaddr
426 hint.ai_family = ai_in->ai_family;
427 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
434 // Check if it's still the same sockaddr
435 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
437 freeaddrinfo(ai_out);
441 // Yes: replace the hostname with the resolved one
443 hostname[i] = xstrdup(resolved_host);
446 freeaddrinfo(ai_out);
450 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
451 remove_duplicate_hostnames(hostname, port, 4);
453 // Concatenate all unique address to the hostport string
454 for(int i = 0; i < 4; i++) {
459 // Ensure we have the same addresses in our own host config file.
461 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
463 //config_add_string(&mesh->config, "Address", tmphostport);
466 // Append the address to the hostport string
468 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
470 hostport = newhostport;
479 static bool try_bind(int port) {
480 struct addrinfo *ai = NULL;
481 struct addrinfo hint = {
482 .ai_flags = AI_PASSIVE,
483 .ai_family = AF_UNSPEC,
484 .ai_socktype = SOCK_STREAM,
485 .ai_protocol = IPPROTO_TCP,
489 snprintf(portstr, sizeof(portstr), "%d", port);
491 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
496 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
497 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
504 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
517 static int check_port(meshlink_handle_t *mesh) {
518 for(int i = 0; i < 1000; i++) {
519 int port = 0x1000 + prng(mesh, 0x8000);
523 xasprintf(&mesh->myport, "%d", port);
528 meshlink_errno = MESHLINK_ENETWORK;
529 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
533 static bool write_main_config_files(meshlink_handle_t *mesh) {
534 if(!mesh->confbase) {
540 /* Write the main config file */
541 packmsg_output_t out = {buf, sizeof buf};
543 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
544 packmsg_add_str(&out, mesh->name);
545 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
546 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
547 packmsg_add_uint16(&out, atoi(mesh->myport));
549 if(!packmsg_output_ok(&out)) {
553 config_t config = {buf, packmsg_output_size(&out, buf)};
555 if(!main_config_write(mesh, "current", &config, mesh->config_key)) {
559 /* Write our own host config file */
560 if(!node_write_config(mesh, mesh->self)) {
567 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
568 packmsg_input_t in = {buf, len};
569 uint32_t version = packmsg_get_uint32(&in);
571 if(version != MESHLINK_INVITATION_VERSION) {
572 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
576 char *name = packmsg_get_str_dup(&in);
577 packmsg_skip_element(&in); /* submesh */
578 dev_class_t devclass = packmsg_get_int32(&in);
579 uint32_t count = packmsg_get_array(&in);
582 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
586 if(!check_id(name)) {
587 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
593 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
599 free(mesh->self->name);
601 mesh->self->name = xstrdup(name);
602 mesh->self->devclass = devclass == DEV_CLASS_UNKNOWN ? mesh->devclass : devclass;
604 // Initialize configuration directory
605 if(!config_init(mesh, "current")) {
609 if(!write_main_config_files(mesh)) {
613 // Write host config files
616 uint32_t len = packmsg_get_bin_raw(&in, &data);
619 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
623 packmsg_input_t in2 = {data, len};
624 uint32_t version = packmsg_get_uint32(&in2);
625 char *name = packmsg_get_str_dup(&in2);
627 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
629 packmsg_input_invalidate(&in);
633 if(!check_id(name)) {
638 if(!strcmp(name, mesh->name)) {
639 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
641 meshlink_errno = MESHLINK_EPEER;
645 node_t *n = new_node();
648 config_t config = {data, len};
650 if(!node_read_from_config(mesh, n, &config)) {
652 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
653 meshlink_errno = MESHLINK_EPEER;
659 if(!config_write(mesh, "current", n->name, &config, mesh->config_key)) {
664 /* Ensure the configuration directory metadata is on disk */
665 if(!config_sync(mesh, "current")) {
669 sptps_send_record(&mesh->sptps, 1, ecdsa_get_public_key(mesh->private_key), 32);
671 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
676 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
678 meshlink_handle_t *mesh = handle;
679 const char *ptr = data;
682 int result = send(mesh->sock, ptr, len, 0);
684 if(result == -1 && errno == EINTR) {
686 } else if(result <= 0) {
697 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
698 meshlink_handle_t *mesh = handle;
701 case SPTPS_HANDSHAKE:
702 return sptps_send_record(&mesh->sptps, 0, mesh->cookie, sizeof(mesh)->cookie);
705 return finalize_join(mesh, msg, len);
708 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
709 shutdown(mesh->sock, SHUT_RDWR);
710 mesh->success = true;
720 static bool recvline(meshlink_handle_t *mesh, size_t len) {
721 char *newline = NULL;
727 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
728 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
730 if(result == -1 && errno == EINTR) {
732 } else if(result <= 0) {
736 mesh->blen += result;
739 if((size_t)(newline - mesh->buffer) >= len) {
743 len = newline - mesh->buffer;
745 memcpy(mesh->line, mesh->buffer, len);
747 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
748 mesh->blen -= len + 1;
753 static bool sendline(int fd, char *format, ...) {
759 va_start(ap, format);
760 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
763 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
771 int result = send(fd, p, blen, MSG_NOSIGNAL);
773 if(result == -1 && errno == EINTR) {
775 } else if(result <= 0) {
786 static const char *errstr[] = {
787 [MESHLINK_OK] = "No error",
788 [MESHLINK_EINVAL] = "Invalid argument",
789 [MESHLINK_ENOMEM] = "Out of memory",
790 [MESHLINK_ENOENT] = "No such node",
791 [MESHLINK_EEXIST] = "Node already exists",
792 [MESHLINK_EINTERNAL] = "Internal error",
793 [MESHLINK_ERESOLV] = "Could not resolve hostname",
794 [MESHLINK_ESTORAGE] = "Storage error",
795 [MESHLINK_ENETWORK] = "Network error",
796 [MESHLINK_EPEER] = "Error communicating with peer",
797 [MESHLINK_ENOTSUP] = "Operation not supported",
798 [MESHLINK_EBUSY] = "MeshLink instance already in use",
799 [MESHLINK_EBLACKLISTED] = "Node is blacklisted",
802 const char *meshlink_strerror(meshlink_errno_t err) {
803 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
804 return "Invalid error code";
810 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
811 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
813 mesh->private_key = ecdsa_generate();
814 mesh->invitation_key = ecdsa_generate();
816 if(!mesh->private_key || !mesh->invitation_key) {
817 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
818 meshlink_errno = MESHLINK_EINTERNAL;
822 logger(mesh, MESHLINK_DEBUG, "Done.\n");
827 static struct timeval idle(event_loop_t *loop, void *data) {
829 meshlink_handle_t *mesh = data;
830 struct timeval t, tmin = {3600, 0};
832 for splay_each(node_t, n, mesh->nodes) {
837 t = utcp_timeout(n->utcp);
839 if(timercmp(&t, &tmin, <)) {
847 // Get our local address(es) by simulating connecting to an Internet host.
848 static void add_local_addresses(meshlink_handle_t *mesh) {
849 struct sockaddr_storage sn;
850 sn.ss_family = AF_UNKNOWN;
851 socklen_t sl = sizeof(sn);
855 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl, mesh->netns)) {
856 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
857 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
864 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl, mesh->netns)) {
865 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
866 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
870 static bool meshlink_setup(meshlink_handle_t *mesh) {
871 if(!config_init(mesh, "current")) {
872 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
873 meshlink_errno = MESHLINK_ESTORAGE;
877 if(!ecdsa_keygen(mesh)) {
878 meshlink_errno = MESHLINK_EINTERNAL;
882 if(check_port(mesh) == 0) {
883 meshlink_errno = MESHLINK_ENETWORK;
887 /* Create a node for ourself */
889 mesh->self = new_node();
890 mesh->self->name = xstrdup(mesh->name);
891 mesh->self->devclass = mesh->devclass;
892 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
893 mesh->self->session_id = mesh->session_id;
895 if(!write_main_config_files(mesh)) {
896 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
897 meshlink_errno = MESHLINK_ESTORAGE;
901 /* Ensure the configuration directory metadata is on disk */
902 if(!config_sync(mesh, "current")) {
909 static bool meshlink_read_config(meshlink_handle_t *mesh) {
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;
959 mesh->self->session_id = mesh->session_id;
961 if(!node_read_public_key(mesh, mesh->self)) {
962 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
963 meshlink_errno = MESHLINK_ESTORAGE;
964 free_node(mesh->self);
973 static void *setup_network_in_netns_thread(void *arg) {
974 meshlink_handle_t *mesh = arg;
976 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
980 bool success = setup_network(mesh);
981 add_local_addresses(mesh);
982 return success ? arg : NULL;
986 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
987 if(!confbase || !*confbase) {
988 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
989 meshlink_errno = MESHLINK_EINVAL;
993 if(!appname || !*appname) {
994 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
995 meshlink_errno = MESHLINK_EINVAL;
999 if(strchr(appname, ' ')) {
1000 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1001 meshlink_errno = MESHLINK_EINVAL;
1005 if(!name || !*name) {
1006 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1007 meshlink_errno = MESHLINK_EINVAL;
1011 if(!check_id(name)) {
1012 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1013 meshlink_errno = MESHLINK_EINVAL;
1017 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1018 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1019 meshlink_errno = MESHLINK_EINVAL;
1023 meshlink_open_params_t *params = xzalloc(sizeof * params);
1025 params->confbase = xstrdup(confbase);
1026 params->name = xstrdup(name);
1027 params->appname = xstrdup(appname);
1028 params->devclass = devclass;
1034 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1036 meshlink_errno = MESHLINK_EINVAL;
1040 params->netns = netns;
1045 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1047 meshlink_errno = MESHLINK_EINVAL;
1051 if((!key && keylen) || (key && !keylen)) {
1052 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1053 meshlink_errno = MESHLINK_EINVAL;
1058 params->keylen = keylen;
1063 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1064 if(!mesh || !new_key || !new_keylen) {
1065 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1066 meshlink_errno = MESHLINK_EINVAL;
1070 pthread_mutex_lock(&mesh->mutex);
1072 // Create hash for the new key
1073 void *new_config_key;
1074 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1076 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1077 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1078 meshlink_errno = MESHLINK_EINTERNAL;
1079 pthread_mutex_unlock(&mesh->mutex);
1083 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1085 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1086 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1087 meshlink_errno = MESHLINK_ESTORAGE;
1088 pthread_mutex_unlock(&mesh->mutex);
1092 devtool_keyrotate_probe(1);
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 pthread_mutex_unlock(&mesh->mutex);
1103 devtool_keyrotate_probe(2);
1105 // Rename confbase/new/ to confbase/current
1107 if(!config_rename(mesh, "new", "current")) {
1108 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1109 meshlink_errno = MESHLINK_ESTORAGE;
1110 pthread_mutex_unlock(&mesh->mutex);
1114 devtool_keyrotate_probe(3);
1116 // Cleanup the "old" confbase sub-directory
1118 if(!config_destroy(mesh->confbase, "old")) {
1119 pthread_mutex_unlock(&mesh->mutex);
1123 // Change the mesh handle key with new key
1125 free(mesh->config_key);
1126 mesh->config_key = new_config_key;
1128 pthread_mutex_unlock(&mesh->mutex);
1133 void meshlink_open_params_free(meshlink_open_params_t *params) {
1135 meshlink_errno = MESHLINK_EINVAL;
1139 free(params->confbase);
1141 free(params->appname);
1146 /// Device class traits
1147 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1148 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1149 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1150 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1151 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1154 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1155 if(!confbase || !*confbase) {
1156 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1157 meshlink_errno = MESHLINK_EINVAL;
1161 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1162 meshlink_open_params_t params;
1163 memset(¶ms, 0, sizeof(params));
1165 params.confbase = (char *)confbase;
1166 params.name = (char *)name;
1167 params.appname = (char *)appname;
1168 params.devclass = devclass;
1171 return meshlink_open_ex(¶ms);
1174 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) {
1175 if(!confbase || !*confbase) {
1176 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1177 meshlink_errno = MESHLINK_EINVAL;
1181 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1182 meshlink_open_params_t params;
1183 memset(¶ms, 0, sizeof(params));
1185 params.confbase = (char *)confbase;
1186 params.name = (char *)name;
1187 params.appname = (char *)appname;
1188 params.devclass = devclass;
1191 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1195 return meshlink_open_ex(¶ms);
1198 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1199 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1200 meshlink_open_params_t params;
1201 memset(¶ms, 0, sizeof(params));
1203 params.name = (char *)name;
1204 params.appname = (char *)appname;
1205 params.devclass = devclass;
1208 return meshlink_open_ex(¶ms);
1211 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1212 // Validate arguments provided by the application
1213 bool usingname = false;
1215 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1217 if(!params->appname || !*params->appname) {
1218 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1219 meshlink_errno = MESHLINK_EINVAL;
1223 if(strchr(params->appname, ' ')) {
1224 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1225 meshlink_errno = MESHLINK_EINVAL;
1229 if(!params->name || !*params->name) {
1230 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1232 } else { //check name only if there is a name != NULL
1234 if(!check_id(params->name)) {
1235 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1236 meshlink_errno = MESHLINK_EINVAL;
1243 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1244 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1245 meshlink_errno = MESHLINK_EINVAL;
1249 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1250 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1251 meshlink_errno = MESHLINK_EINVAL;
1255 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1257 if(params->confbase) {
1258 mesh->confbase = xstrdup(params->confbase);
1261 mesh->appname = xstrdup(params->appname);
1262 mesh->devclass = params->devclass;
1263 mesh->discovery = true;
1264 mesh->invitation_timeout = 604800; // 1 week
1265 mesh->netns = params->netns;
1266 mesh->submeshes = NULL;
1267 mesh->log_cb = global_log_cb;
1268 mesh->log_level = global_log_level;
1270 randomize(&mesh->prng_state, sizeof(mesh->prng_state));
1273 randomize(&mesh->session_id, sizeof(mesh->session_id));
1274 } while(mesh->session_id == 0);
1276 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1279 mesh->name = xstrdup(params->name);
1284 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1286 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1287 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1288 meshlink_close(mesh);
1289 meshlink_errno = MESHLINK_EINTERNAL;
1295 pthread_mutexattr_t attr;
1296 pthread_mutexattr_init(&attr);
1297 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1298 pthread_mutex_init(&mesh->mutex, &attr);
1300 mesh->threadstarted = false;
1301 event_loop_init(&mesh->loop);
1302 mesh->loop.data = mesh;
1304 meshlink_queue_init(&mesh->outpacketqueue);
1306 // Atomically lock the configuration directory.
1307 if(!main_config_lock(mesh)) {
1308 meshlink_close(mesh);
1312 // If no configuration exists yet, create it.
1314 if(!meshlink_confbase_exists(mesh)) {
1315 if(!meshlink_setup(mesh)) {
1316 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1317 meshlink_close(mesh);
1321 if(!meshlink_read_config(mesh)) {
1322 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1323 meshlink_close(mesh);
1329 struct WSAData wsa_state;
1330 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1333 // Setup up everything
1334 // TODO: we should not open listening sockets yet
1336 bool success = false;
1338 if(mesh->netns != -1) {
1342 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1343 void *retval = NULL;
1344 success = pthread_join(thr, &retval) == 0 && retval;
1348 meshlink_errno = MESHLINK_EINTERNAL;
1351 #endif // HAVE_SETNS
1353 success = setup_network(mesh);
1354 add_local_addresses(mesh);
1358 meshlink_close(mesh);
1359 meshlink_errno = MESHLINK_ENETWORK;
1363 add_local_addresses(mesh);
1364 node_write_config(mesh, mesh->self);
1366 idle_set(&mesh->loop, idle, mesh);
1368 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1372 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1373 meshlink_submesh_t *s = NULL;
1376 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1377 meshlink_errno = MESHLINK_EINVAL;
1381 if(!submesh || !*submesh) {
1382 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1383 meshlink_errno = MESHLINK_EINVAL;
1388 pthread_mutex_lock(&mesh->mutex);
1390 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1392 pthread_mutex_unlock(&mesh->mutex);
1397 static void *meshlink_main_loop(void *arg) {
1398 meshlink_handle_t *mesh = arg;
1400 if(mesh->netns != -1) {
1403 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1404 pthread_cond_signal(&mesh->cond);
1409 pthread_cond_signal(&mesh->cond);
1411 #endif // HAVE_SETNS
1416 if(mesh->discovery) {
1417 discovery_start(mesh);
1422 pthread_mutex_lock(&mesh->mutex);
1424 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1425 pthread_cond_broadcast(&mesh->cond);
1427 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1429 pthread_mutex_unlock(&mesh->mutex);
1434 if(mesh->discovery) {
1435 discovery_stop(mesh);
1443 bool meshlink_start(meshlink_handle_t *mesh) {
1445 assert(mesh->private_key);
1448 meshlink_errno = MESHLINK_EINVAL;
1452 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1454 pthread_mutex_lock(&mesh->mutex);
1456 assert(mesh->self->ecdsa);
1457 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1459 if(mesh->threadstarted) {
1460 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1461 pthread_mutex_unlock(&mesh->mutex);
1465 if(mesh->listen_socket[0].tcp.fd < 0) {
1466 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1467 meshlink_errno = MESHLINK_ENETWORK;
1471 mesh->thedatalen = 0;
1473 // TODO: open listening sockets first
1475 //Check that a valid name is set
1477 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1478 meshlink_errno = MESHLINK_EINVAL;
1479 pthread_mutex_unlock(&mesh->mutex);
1483 init_outgoings(mesh);
1485 // Start the main thread
1487 event_loop_start(&mesh->loop);
1489 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1490 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1491 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1492 meshlink_errno = MESHLINK_EINTERNAL;
1493 event_loop_stop(&mesh->loop);
1494 pthread_mutex_unlock(&mesh->mutex);
1498 pthread_cond_wait(&mesh->cond, &mesh->mutex);
1499 mesh->threadstarted = true;
1501 pthread_mutex_unlock(&mesh->mutex);
1505 void meshlink_stop(meshlink_handle_t *mesh) {
1507 meshlink_errno = MESHLINK_EINVAL;
1511 pthread_mutex_lock(&mesh->mutex);
1512 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1514 // Shut down the main thread
1515 event_loop_stop(&mesh->loop);
1517 // Send ourselves a UDP packet to kick the event loop
1518 for(int i = 0; i < mesh->listen_sockets; i++) {
1520 socklen_t salen = sizeof(sa.sa);
1522 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1523 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1527 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1528 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1532 if(mesh->threadstarted) {
1533 // Wait for the main thread to finish
1534 pthread_mutex_unlock(&mesh->mutex);
1535 pthread_join(mesh->thread, NULL);
1536 pthread_mutex_lock(&mesh->mutex);
1538 mesh->threadstarted = false;
1541 // Close all metaconnections
1542 if(mesh->connections) {
1543 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1545 connection_t *c = node->data;
1547 terminate_connection(mesh, c, false);
1551 exit_outgoings(mesh);
1553 // Write out any changed node config files
1555 for splay_each(node_t, n, mesh->nodes) {
1556 if(n->status.dirty) {
1557 node_write_config(mesh, n);
1558 n->status.dirty = false;
1563 pthread_mutex_unlock(&mesh->mutex);
1566 void meshlink_close(meshlink_handle_t *mesh) {
1568 meshlink_errno = MESHLINK_EINVAL;
1572 // stop can be called even if mesh has not been started
1573 meshlink_stop(mesh);
1575 // lock is not released after this
1576 pthread_mutex_lock(&mesh->mutex);
1578 // Close and free all resources used.
1580 close_network_connections(mesh);
1582 logger(mesh, MESHLINK_INFO, "Terminating");
1584 event_loop_exit(&mesh->loop);
1588 if(mesh->confbase) {
1594 ecdsa_free(mesh->invitation_key);
1596 if(mesh->netns != -1) {
1600 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1604 meshlink_queue_exit(&mesh->outpacketqueue);
1607 free(mesh->appname);
1608 free(mesh->confbase);
1609 free(mesh->config_key);
1610 ecdsa_free(mesh->private_key);
1612 main_config_unlock(mesh);
1614 pthread_mutex_unlock(&mesh->mutex);
1615 pthread_mutex_destroy(&mesh->mutex);
1617 memset(mesh, 0, sizeof(*mesh));
1622 bool meshlink_destroy(const char *confbase) {
1624 meshlink_errno = MESHLINK_EINVAL;
1628 /* Exit early if the confbase directory itself doesn't exist */
1629 if(access(confbase, F_OK) && errno == ENOENT) {
1633 /* Take the lock the same way meshlink_open() would. */
1634 char lockfilename[PATH_MAX];
1635 snprintf(lockfilename, sizeof(lockfilename), "%s" SLASH "meshlink.lock", confbase);
1637 FILE *lockfile = fopen(lockfilename, "w+");
1640 logger(NULL, MESHLINK_ERROR, "Could not open lock file %s: %s", lockfilename, strerror(errno));
1641 meshlink_errno = MESHLINK_ESTORAGE;
1646 fcntl(fileno(lockfile), F_SETFD, FD_CLOEXEC);
1650 // TODO: use _locking()?
1653 if(flock(fileno(lockfile), LOCK_EX | LOCK_NB) != 0) {
1654 logger(NULL, MESHLINK_ERROR, "Configuration directory %s still in use\n", lockfilename);
1656 meshlink_errno = MESHLINK_EBUSY;
1662 if(!config_destroy(confbase, "current") || !config_destroy(confbase, "new") || !config_destroy(confbase, "old")) {
1663 logger(NULL, MESHLINK_ERROR, "Cannot remove sub-directories in %s: %s\n", confbase, strerror(errno));
1667 if(unlink(lockfilename)) {
1668 logger(NULL, MESHLINK_ERROR, "Cannot remove lock file %s: %s\n", lockfilename, strerror(errno));
1670 meshlink_errno = MESHLINK_ESTORAGE;
1676 /* TODO: do we need to remove confbase? Potential race condition? */
1677 if(!sync_path(confbase)) {
1678 logger(NULL, MESHLINK_ERROR, "Cannot sync directory %s: %s\n", confbase, strerror(errno));
1679 meshlink_errno = MESHLINK_ESTORAGE;
1686 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1688 meshlink_errno = MESHLINK_EINVAL;
1692 pthread_mutex_lock(&mesh->mutex);
1693 mesh->receive_cb = cb;
1694 pthread_mutex_unlock(&mesh->mutex);
1697 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1699 meshlink_errno = MESHLINK_EINVAL;
1703 pthread_mutex_lock(&mesh->mutex);
1704 mesh->connection_try_cb = cb;
1705 pthread_mutex_unlock(&mesh->mutex);
1708 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1710 meshlink_errno = MESHLINK_EINVAL;
1714 pthread_mutex_lock(&mesh->mutex);
1715 mesh->node_status_cb = cb;
1716 pthread_mutex_unlock(&mesh->mutex);
1719 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1721 meshlink_errno = MESHLINK_EINVAL;
1725 pthread_mutex_lock(&mesh->mutex);
1726 mesh->node_pmtu_cb = cb;
1727 pthread_mutex_unlock(&mesh->mutex);
1730 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1732 meshlink_errno = MESHLINK_EINVAL;
1736 pthread_mutex_lock(&mesh->mutex);
1737 mesh->node_duplicate_cb = cb;
1738 pthread_mutex_unlock(&mesh->mutex);
1741 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1743 pthread_mutex_lock(&mesh->mutex);
1745 mesh->log_level = cb ? level : 0;
1746 pthread_mutex_unlock(&mesh->mutex);
1749 global_log_level = cb ? level : 0;
1753 void meshlink_set_error_cb(struct meshlink_handle *mesh, meshlink_error_cb_t cb) {
1755 meshlink_errno = MESHLINK_EINVAL;
1759 pthread_mutex_lock(&mesh->mutex);
1760 mesh->error_cb = cb;
1761 pthread_mutex_unlock(&mesh->mutex);
1764 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1765 meshlink_packethdr_t *hdr;
1767 // Validate arguments
1768 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1769 meshlink_errno = MESHLINK_EINVAL;
1778 meshlink_errno = MESHLINK_EINVAL;
1782 node_t *n = (node_t *)destination;
1784 if(n->status.blacklisted) {
1785 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1786 meshlink_errno = MESHLINK_EBLACKLISTED;
1790 // Prepare the packet
1791 vpn_packet_t *packet = malloc(sizeof(*packet));
1794 meshlink_errno = MESHLINK_ENOMEM;
1798 packet->probe = false;
1799 packet->tcp = false;
1800 packet->len = len + sizeof(*hdr);
1802 hdr = (meshlink_packethdr_t *)packet->data;
1803 memset(hdr, 0, sizeof(*hdr));
1804 // leave the last byte as 0 to make sure strings are always
1805 // null-terminated if they are longer than the buffer
1806 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1807 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1809 memcpy(packet->data + sizeof(*hdr), data, len);
1812 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1814 meshlink_errno = MESHLINK_ENOMEM;
1818 // Notify event loop
1819 signal_trigger(&mesh->loop, &mesh->datafromapp);
1824 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1826 meshlink_handle_t *mesh = data;
1827 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1833 mesh->self->in_packets++;
1834 mesh->self->in_bytes += packet->len;
1835 route(mesh, mesh->self, packet);
1840 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1841 if(!mesh || !destination) {
1842 meshlink_errno = MESHLINK_EINVAL;
1846 pthread_mutex_lock(&mesh->mutex);
1848 node_t *n = (node_t *)destination;
1850 if(!n->status.reachable) {
1851 pthread_mutex_unlock(&mesh->mutex);
1854 } else if(n->mtuprobes > 30 && n->minmtu) {
1855 pthread_mutex_unlock(&mesh->mutex);
1858 pthread_mutex_unlock(&mesh->mutex);
1863 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1864 if(!mesh || !node) {
1865 meshlink_errno = MESHLINK_EINVAL;
1869 pthread_mutex_lock(&mesh->mutex);
1871 node_t *n = (node_t *)node;
1873 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1874 meshlink_errno = MESHLINK_EINTERNAL;
1875 pthread_mutex_unlock(&mesh->mutex);
1879 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1882 meshlink_errno = MESHLINK_EINTERNAL;
1885 pthread_mutex_unlock(&mesh->mutex);
1889 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1891 meshlink_errno = MESHLINK_EINVAL;
1895 return (meshlink_node_t *)mesh->self;
1898 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1899 if(!mesh || !name) {
1900 meshlink_errno = MESHLINK_EINVAL;
1904 meshlink_node_t *node = NULL;
1906 pthread_mutex_lock(&mesh->mutex);
1907 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1908 pthread_mutex_unlock(&mesh->mutex);
1911 meshlink_errno = MESHLINK_ENOENT;
1917 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1918 if(!mesh || !name) {
1919 meshlink_errno = MESHLINK_EINVAL;
1923 meshlink_submesh_t *submesh = NULL;
1925 pthread_mutex_lock(&mesh->mutex);
1926 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1927 pthread_mutex_unlock(&mesh->mutex);
1930 meshlink_errno = MESHLINK_ENOENT;
1936 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1937 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1938 meshlink_errno = MESHLINK_EINVAL;
1942 meshlink_node_t **result;
1945 pthread_mutex_lock(&mesh->mutex);
1947 *nmemb = mesh->nodes->count;
1948 result = realloc(nodes, *nmemb * sizeof(*nodes));
1951 meshlink_node_t **p = result;
1953 for splay_each(node_t, n, mesh->nodes) {
1954 *p++ = (meshlink_node_t *)n;
1959 meshlink_errno = MESHLINK_ENOMEM;
1962 pthread_mutex_unlock(&mesh->mutex);
1967 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) {
1968 meshlink_node_t **result;
1970 pthread_mutex_lock(&mesh->mutex);
1974 for splay_each(node_t, n, mesh->nodes) {
1975 if(true == search_node(n, condition)) {
1976 *nmemb = *nmemb + 1;
1982 pthread_mutex_unlock(&mesh->mutex);
1986 result = realloc(nodes, *nmemb * sizeof(*nodes));
1989 meshlink_node_t **p = result;
1991 for splay_each(node_t, n, mesh->nodes) {
1992 if(true == search_node(n, condition)) {
1993 *p++ = (meshlink_node_t *)n;
1999 meshlink_errno = MESHLINK_ENOMEM;
2002 pthread_mutex_unlock(&mesh->mutex);
2007 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
2008 dev_class_t *devclass = (dev_class_t *)condition;
2010 if(*devclass == (dev_class_t)node->devclass) {
2017 static bool search_node_by_submesh(const node_t *node, const void *condition) {
2018 if(condition == node->submesh) {
2025 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) {
2026 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
2027 meshlink_errno = MESHLINK_EINVAL;
2031 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
2034 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
2035 if(!mesh || !submesh || !nmemb) {
2036 meshlink_errno = MESHLINK_EINVAL;
2040 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
2043 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
2044 if(!mesh || !node) {
2045 meshlink_errno = MESHLINK_EINVAL;
2049 dev_class_t devclass;
2051 pthread_mutex_lock(&mesh->mutex);
2053 devclass = ((node_t *)node)->devclass;
2055 pthread_mutex_unlock(&mesh->mutex);
2060 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2061 if(!mesh || !node) {
2062 meshlink_errno = MESHLINK_EINVAL;
2066 node_t *n = (node_t *)node;
2068 meshlink_submesh_t *s;
2070 s = (meshlink_submesh_t *)n->submesh;
2075 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2076 if(!mesh || !data || !len || !signature || !siglen) {
2077 meshlink_errno = MESHLINK_EINVAL;
2081 if(*siglen < MESHLINK_SIGLEN) {
2082 meshlink_errno = MESHLINK_EINVAL;
2086 pthread_mutex_lock(&mesh->mutex);
2088 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2089 meshlink_errno = MESHLINK_EINTERNAL;
2090 pthread_mutex_unlock(&mesh->mutex);
2094 *siglen = MESHLINK_SIGLEN;
2095 pthread_mutex_unlock(&mesh->mutex);
2099 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2100 if(!mesh || !data || !len || !signature) {
2101 meshlink_errno = MESHLINK_EINVAL;
2105 if(siglen != MESHLINK_SIGLEN) {
2106 meshlink_errno = MESHLINK_EINVAL;
2110 pthread_mutex_lock(&mesh->mutex);
2114 struct node_t *n = (struct node_t *)source;
2116 if(!node_read_public_key(mesh, n)) {
2117 meshlink_errno = MESHLINK_EINTERNAL;
2120 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2123 pthread_mutex_unlock(&mesh->mutex);
2127 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2128 pthread_mutex_lock(&mesh->mutex);
2130 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2133 // TODO: Update invitation key if necessary?
2136 pthread_mutex_unlock(&mesh->mutex);
2138 return mesh->invitation_key;
2141 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2142 if(!mesh || !node || !address) {
2143 meshlink_errno = MESHLINK_EINVAL;
2147 if(!is_valid_hostname(address)) {
2148 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2149 meshlink_errno = MESHLINK_EINVAL;
2153 if(port && !is_valid_port(port)) {
2154 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2155 meshlink_errno = MESHLINK_EINVAL;
2159 char *canonical_address;
2162 xasprintf(&canonical_address, "%s %s", address, port);
2164 canonical_address = xstrdup(address);
2167 pthread_mutex_lock(&mesh->mutex);
2169 node_t *n = (node_t *)node;
2170 free(n->canonical_address);
2171 n->canonical_address = canonical_address;
2172 node_write_config(mesh, n);
2174 pthread_mutex_unlock(&mesh->mutex);
2179 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2180 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2183 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2185 meshlink_errno = MESHLINK_EINVAL;
2189 char *address = meshlink_get_external_address(mesh);
2195 bool rval = meshlink_add_address(mesh, address);
2201 int meshlink_get_port(meshlink_handle_t *mesh) {
2203 meshlink_errno = MESHLINK_EINVAL;
2208 meshlink_errno = MESHLINK_EINTERNAL;
2214 pthread_mutex_lock(&mesh->mutex);
2215 port = atoi(mesh->myport);
2216 pthread_mutex_unlock(&mesh->mutex);
2221 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2222 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2223 meshlink_errno = MESHLINK_EINVAL;
2227 if(mesh->myport && port == atoi(mesh->myport)) {
2231 if(!try_bind(port)) {
2232 meshlink_errno = MESHLINK_ENETWORK;
2236 devtool_trybind_probe();
2240 pthread_mutex_lock(&mesh->mutex);
2242 if(mesh->threadstarted) {
2243 meshlink_errno = MESHLINK_EINVAL;
2248 xasprintf(&mesh->myport, "%d", port);
2250 /* Close down the network. This also deletes mesh->self. */
2251 close_network_connections(mesh);
2253 /* Recreate mesh->self. */
2254 mesh->self = new_node();
2255 mesh->self->name = xstrdup(mesh->name);
2256 mesh->self->devclass = mesh->devclass;
2257 mesh->self->session_id = mesh->session_id;
2258 xasprintf(&mesh->myport, "%d", port);
2260 if(!node_read_public_key(mesh, mesh->self)) {
2261 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2262 meshlink_errno = MESHLINK_ESTORAGE;
2263 free_node(mesh->self);
2266 } else if(!setup_network(mesh)) {
2267 meshlink_errno = MESHLINK_ENETWORK;
2271 /* Rebuild our own list of recent addresses */
2272 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2273 add_local_addresses(mesh);
2275 /* Write meshlink.conf with the updated port number */
2276 write_main_config_files(mesh);
2278 rval = config_sync(mesh, "current");
2281 pthread_mutex_unlock(&mesh->mutex);
2283 return rval && meshlink_get_port(mesh) == port;
2286 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2287 mesh->invitation_timeout = timeout;
2290 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2291 meshlink_submesh_t *s = NULL;
2294 meshlink_errno = MESHLINK_EINVAL;
2299 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2302 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2303 meshlink_errno = MESHLINK_EINVAL;
2307 s = (meshlink_submesh_t *)mesh->self->submesh;
2310 pthread_mutex_lock(&mesh->mutex);
2312 // Check validity of the new node's name
2313 if(!check_id(name)) {
2314 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2315 meshlink_errno = MESHLINK_EINVAL;
2316 pthread_mutex_unlock(&mesh->mutex);
2320 // Ensure no host configuration file with that name exists
2321 if(config_exists(mesh, "current", name)) {
2322 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2323 meshlink_errno = MESHLINK_EEXIST;
2324 pthread_mutex_unlock(&mesh->mutex);
2328 // Ensure no other nodes know about this name
2329 if(meshlink_get_node(mesh, name)) {
2330 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2331 meshlink_errno = MESHLINK_EEXIST;
2332 pthread_mutex_unlock(&mesh->mutex);
2336 // Get the local address
2337 char *address = get_my_hostname(mesh, flags);
2340 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2341 meshlink_errno = MESHLINK_ERESOLV;
2342 pthread_mutex_unlock(&mesh->mutex);
2346 if(!refresh_invitation_key(mesh)) {
2347 meshlink_errno = MESHLINK_EINTERNAL;
2348 pthread_mutex_unlock(&mesh->mutex);
2354 // Create a hash of the key.
2355 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2356 sha512(fingerprint, strlen(fingerprint), hash);
2357 b64encode_urlsafe(hash, hash, 18);
2359 // Create a random cookie for this invitation.
2361 randomize(cookie, 18);
2363 // Create a filename that doesn't reveal the cookie itself
2364 char buf[18 + strlen(fingerprint)];
2365 char cookiehash[64];
2366 memcpy(buf, cookie, 18);
2367 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2368 sha512(buf, sizeof(buf), cookiehash);
2369 b64encode_urlsafe(cookiehash, cookiehash, 18);
2371 b64encode_urlsafe(cookie, cookie, 18);
2375 /* Construct the invitation file */
2376 uint8_t outbuf[4096];
2377 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2379 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2380 packmsg_add_str(&inv, name);
2381 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2382 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2384 /* TODO: Add several host config files to bootstrap connections.
2385 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2386 * and are not blacklisted.
2388 config_t configs[5];
2389 memset(configs, 0, sizeof(configs));
2392 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2396 /* Append host config files to the invitation file */
2397 packmsg_add_array(&inv, count);
2399 for(int i = 0; i < count; i++) {
2400 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2401 config_free(&configs[i]);
2404 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2406 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2407 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2408 meshlink_errno = MESHLINK_ESTORAGE;
2409 pthread_mutex_unlock(&mesh->mutex);
2413 // Create an URL from the local address, key hash and cookie
2415 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2418 pthread_mutex_unlock(&mesh->mutex);
2422 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2423 return meshlink_invite_ex(mesh, submesh, name, 0);
2426 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2427 if(!mesh || !invitation) {
2428 meshlink_errno = MESHLINK_EINVAL;
2432 pthread_mutex_lock(&mesh->mutex);
2434 //Before doing meshlink_join make sure we are not connected to another mesh
2435 if(mesh->threadstarted) {
2436 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2437 meshlink_errno = MESHLINK_EINVAL;
2438 pthread_mutex_unlock(&mesh->mutex);
2442 // 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.
2443 if(mesh->nodes->count > 1) {
2444 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2445 meshlink_errno = MESHLINK_EINVAL;
2446 pthread_mutex_unlock(&mesh->mutex);
2450 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2451 char copy[strlen(invitation) + 1];
2452 strcpy(copy, invitation);
2454 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2456 char *slash = strchr(copy, '/');
2464 if(strlen(slash) != 48) {
2468 char *address = copy;
2471 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2475 // Generate a throw-away key for the invitation.
2476 ecdsa_t *key = ecdsa_generate();
2479 meshlink_errno = MESHLINK_EINTERNAL;
2480 pthread_mutex_unlock(&mesh->mutex);
2484 char *b64key = ecdsa_get_base64_public_key(key);
2488 while(address && *address) {
2489 // We allow commas in the address part to support multiple addresses in one invitation URL.
2490 comma = strchr(address, ',');
2496 // Split of the port
2497 port = strrchr(address, ':');
2505 // IPv6 address are enclosed in brackets, per RFC 3986
2506 if(*address == '[') {
2508 char *bracket = strchr(address, ']');
2521 // Connect to the meshlink daemon mentioned in the URL.
2522 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2525 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2526 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2528 if(mesh->sock == -1) {
2529 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2530 meshlink_errno = MESHLINK_ENETWORK;
2534 set_timeout(mesh->sock, 5000);
2536 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2537 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2538 meshlink_errno = MESHLINK_ENETWORK;
2539 closesocket(mesh->sock);
2547 meshlink_errno = MESHLINK_ERESOLV;
2550 if(mesh->sock != -1 || !comma) {
2557 if(mesh->sock == -1) {
2558 pthread_mutex_unlock(&mesh->mutex);
2562 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2564 // Tell him we have an invitation, and give him our throw-away key.
2568 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2569 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2570 closesocket(mesh->sock);
2571 meshlink_errno = MESHLINK_ENETWORK;
2572 pthread_mutex_unlock(&mesh->mutex);
2578 char hisname[4096] = "";
2579 int code, hismajor, hisminor = 0;
2581 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) {
2582 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2583 closesocket(mesh->sock);
2584 meshlink_errno = MESHLINK_ENETWORK;
2585 pthread_mutex_unlock(&mesh->mutex);
2589 // Check if the hash of the key he gave us matches the hash in the URL.
2590 char *fingerprint = mesh->line + 2;
2593 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2594 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2595 meshlink_errno = MESHLINK_EINTERNAL;
2596 pthread_mutex_unlock(&mesh->mutex);
2600 if(memcmp(hishash, mesh->hash, 18)) {
2601 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2602 meshlink_errno = MESHLINK_EPEER;
2603 pthread_mutex_unlock(&mesh->mutex);
2608 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2611 meshlink_errno = MESHLINK_EINTERNAL;
2612 pthread_mutex_unlock(&mesh->mutex);
2616 // Start an SPTPS session
2617 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2618 meshlink_errno = MESHLINK_EINTERNAL;
2619 pthread_mutex_unlock(&mesh->mutex);
2623 // Feed rest of input buffer to SPTPS
2624 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2625 meshlink_errno = MESHLINK_EPEER;
2626 pthread_mutex_unlock(&mesh->mutex);
2632 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2634 if(errno == EINTR) {
2638 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2639 meshlink_errno = MESHLINK_ENETWORK;
2640 pthread_mutex_unlock(&mesh->mutex);
2644 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2645 meshlink_errno = MESHLINK_EPEER;
2646 pthread_mutex_unlock(&mesh->mutex);
2651 sptps_stop(&mesh->sptps);
2654 closesocket(mesh->sock);
2656 if(!mesh->success) {
2657 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2658 meshlink_errno = MESHLINK_EPEER;
2659 pthread_mutex_unlock(&mesh->mutex);
2663 pthread_mutex_unlock(&mesh->mutex);
2667 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2668 meshlink_errno = MESHLINK_EINVAL;
2669 pthread_mutex_unlock(&mesh->mutex);
2673 char *meshlink_export(meshlink_handle_t *mesh) {
2675 meshlink_errno = MESHLINK_EINVAL;
2679 // Create a config file on the fly.
2682 packmsg_output_t out = {buf, sizeof(buf)};
2683 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2684 packmsg_add_str(&out, mesh->name);
2685 packmsg_add_str(&out, CORE_MESH);
2687 pthread_mutex_lock(&mesh->mutex);
2689 packmsg_add_int32(&out, mesh->self->devclass);
2690 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2691 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2692 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2696 for(uint32_t i = 0; i < 5; i++) {
2697 if(mesh->self->recent[i].sa.sa_family) {
2704 packmsg_add_array(&out, count);
2706 for(uint32_t i = 0; i < count; i++) {
2707 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2710 pthread_mutex_unlock(&mesh->mutex);
2712 if(!packmsg_output_ok(&out)) {
2713 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2714 meshlink_errno = MESHLINK_EINTERNAL;
2718 // Prepare a base64-encoded packmsg array containing our config file
2720 uint32_t len = packmsg_output_size(&out, buf);
2721 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2722 uint8_t *buf2 = xmalloc(len2);
2723 packmsg_output_t out2 = {buf2, len2};
2724 packmsg_add_array(&out2, 1);
2725 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2727 if(!packmsg_output_ok(&out2)) {
2728 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2729 meshlink_errno = MESHLINK_EINTERNAL;
2734 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2736 return (char *)buf2;
2739 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2740 if(!mesh || !data) {
2741 meshlink_errno = MESHLINK_EINVAL;
2745 size_t datalen = strlen(data);
2746 uint8_t *buf = xmalloc(datalen);
2747 int buflen = b64decode(data, buf, datalen);
2750 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2751 meshlink_errno = MESHLINK_EPEER;
2755 packmsg_input_t in = {buf, buflen};
2756 uint32_t count = packmsg_get_array(&in);
2759 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2760 meshlink_errno = MESHLINK_EPEER;
2764 pthread_mutex_lock(&mesh->mutex);
2768 uint32_t len = packmsg_get_bin_raw(&in, &data);
2774 packmsg_input_t in2 = {data, len};
2775 uint32_t version = packmsg_get_uint32(&in2);
2776 char *name = packmsg_get_str_dup(&in2);
2778 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2780 packmsg_input_invalidate(&in);
2784 if(!check_id(name)) {
2789 node_t *n = lookup_node(mesh, name);
2792 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2800 config_t config = {data, len};
2802 if(!node_read_from_config(mesh, n, &config)) {
2804 packmsg_input_invalidate(&in);
2808 config_write(mesh, "current", n->name, &config, mesh->config_key);
2812 pthread_mutex_unlock(&mesh->mutex);
2816 if(!packmsg_done(&in)) {
2817 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2818 meshlink_errno = MESHLINK_EPEER;
2822 if(!config_sync(mesh, "current")) {
2829 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2830 if(!mesh || !node) {
2831 meshlink_errno = MESHLINK_EINVAL;
2835 pthread_mutex_lock(&mesh->mutex);
2840 if(n == mesh->self) {
2841 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2842 meshlink_errno = MESHLINK_EINVAL;
2843 pthread_mutex_unlock(&mesh->mutex);
2847 if(n->status.blacklisted) {
2848 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2849 pthread_mutex_unlock(&mesh->mutex);
2853 n->status.blacklisted = true;
2854 node_write_config(mesh, n);
2855 config_sync(mesh, "current");
2857 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2859 /* Immediately shut down any connections we have with the blacklisted node.
2860 * We can't call terminate_connection(), because we might be called from a callback function.
2862 for list_each(connection_t, c, mesh->connections) {
2864 shutdown(c->socket, SHUT_RDWR);
2868 utcp_abort_all_connections(n->utcp);
2874 n->status.udp_confirmed = false;
2876 pthread_mutex_unlock(&mesh->mutex);
2879 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2880 if(!mesh || !node) {
2881 meshlink_errno = MESHLINK_EINVAL;
2885 pthread_mutex_lock(&mesh->mutex);
2887 node_t *n = (node_t *)node;
2889 if(n == mesh->self) {
2890 logger(mesh, MESHLINK_ERROR, "%s whitelisting itself?\n", node->name);
2891 meshlink_errno = MESHLINK_EINVAL;
2892 pthread_mutex_unlock(&mesh->mutex);
2896 if(!n->status.blacklisted) {
2897 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2898 pthread_mutex_unlock(&mesh->mutex);
2902 n->status.blacklisted = false;
2903 node_write_config(mesh, n);
2904 config_sync(mesh, "current");
2906 if(n->status.reachable) {
2907 update_node_status(mesh, n);
2910 logger(mesh, MESHLINK_DEBUG, "Whitelisted %s.\n", node->name);
2912 pthread_mutex_unlock(&mesh->mutex);
2916 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2917 mesh->default_blacklist = blacklist;
2920 /* Hint that a hostname may be found at an address
2921 * See header file for detailed comment.
2923 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2924 if(!mesh || !node || !addr) {
2925 meshlink_errno = EINVAL;
2929 pthread_mutex_lock(&mesh->mutex);
2931 node_t *n = (node_t *)node;
2932 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2933 memcpy(n->recent, addr, SALEN(*addr));
2934 node_write_config(mesh, n);
2936 pthread_mutex_unlock(&mesh->mutex);
2937 // @TODO do we want to fire off a connection attempt right away?
2940 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2942 node_t *n = utcp->priv;
2943 meshlink_handle_t *mesh = n->mesh;
2944 return mesh->channel_accept_cb;
2947 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
2949 if(aio->cb.buffer) {
2950 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
2954 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2959 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2960 meshlink_channel_t *channel = connection->priv;
2966 node_t *n = channel->node;
2967 meshlink_handle_t *mesh = n->mesh;
2969 if(n->status.destroyed) {
2970 meshlink_channel_close(mesh, channel);
2974 const char *p = data;
2977 while(channel->aio_receive) {
2978 meshlink_aio_buffer_t *aio = channel->aio_receive;
2979 size_t todo = aio->len - aio->done;
2986 memcpy((char *)aio->data + aio->done, p, todo);
2988 ssize_t result = write(aio->fd, p, todo);
2997 if(aio->done == aio->len) {
2998 channel->aio_receive = aio->next;
2999 aio_signal(mesh, channel, aio);
3011 if(channel->receive_cb) {
3012 channel->receive_cb(mesh, channel, p, left);
3018 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
3019 node_t *n = utcp_connection->utcp->priv;
3025 meshlink_handle_t *mesh = n->mesh;
3027 if(!mesh->channel_accept_cb) {
3031 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3033 channel->c = utcp_connection;
3035 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
3036 utcp_accept(utcp_connection, channel_recv, channel);
3042 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
3043 node_t *n = utcp->priv;
3045 if(n->status.destroyed) {
3049 meshlink_handle_t *mesh = n->mesh;
3050 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
3053 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
3054 if(!mesh || !channel) {
3055 meshlink_errno = MESHLINK_EINVAL;
3059 channel->receive_cb = cb;
3062 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3064 node_t *n = (node_t *)source;
3070 utcp_recv(n->utcp, data, len);
3073 static void channel_poll(struct utcp_connection *connection, size_t len) {
3074 meshlink_channel_t *channel = connection->priv;
3080 node_t *n = channel->node;
3081 meshlink_handle_t *mesh = n->mesh;
3082 meshlink_aio_buffer_t *aio = channel->aio_send;
3085 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3086 size_t left = aio->len - aio->done;
3094 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3097 size_t todo = utcp_get_sndbuf_free(connection);
3103 if(todo > sizeof(buf)) {
3107 ssize_t result = read(aio->fd, buf, todo);
3110 sent = utcp_send(connection, buf, result);
3120 /* If the buffer is now completely sent, call the callback and dispose of it. */
3121 if(aio->done >= aio->len) {
3122 channel->aio_send = aio->next;
3123 aio_signal(mesh, channel, aio);
3127 if(channel->poll_cb) {
3128 channel->poll_cb(mesh, channel, len);
3130 utcp_set_poll_cb(connection, NULL);
3135 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3136 if(!mesh || !channel) {
3137 meshlink_errno = MESHLINK_EINVAL;
3141 pthread_mutex_lock(&mesh->mutex);
3142 channel->poll_cb = cb;
3143 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3144 pthread_mutex_unlock(&mesh->mutex);
3147 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3149 meshlink_errno = MESHLINK_EINVAL;
3153 pthread_mutex_lock(&mesh->mutex);
3154 mesh->channel_accept_cb = cb;
3155 mesh->receive_cb = channel_receive;
3157 for splay_each(node_t, n, mesh->nodes) {
3158 if(!n->utcp && n != mesh->self) {
3159 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3163 pthread_mutex_unlock(&mesh->mutex);
3166 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3170 meshlink_errno = MESHLINK_EINVAL;
3174 pthread_mutex_lock(&mesh->mutex);
3175 utcp_set_sndbuf(channel->c, size);
3176 pthread_mutex_unlock(&mesh->mutex);
3179 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3183 meshlink_errno = MESHLINK_EINVAL;
3187 pthread_mutex_lock(&mesh->mutex);
3188 utcp_set_rcvbuf(channel->c, size);
3189 pthread_mutex_unlock(&mesh->mutex);
3192 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) {
3194 abort(); // TODO: handle non-NULL data
3197 if(!mesh || !node) {
3198 meshlink_errno = MESHLINK_EINVAL;
3202 pthread_mutex_lock(&mesh->mutex);
3204 node_t *n = (node_t *)node;
3207 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3208 mesh->receive_cb = channel_receive;
3211 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3212 pthread_mutex_unlock(&mesh->mutex);
3217 if(n->status.blacklisted) {
3218 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3219 meshlink_errno = MESHLINK_EBLACKLISTED;
3220 pthread_mutex_unlock(&mesh->mutex);
3224 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3226 channel->receive_cb = cb;
3229 channel->priv = (void *)data;
3232 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3234 pthread_mutex_unlock(&mesh->mutex);
3237 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3245 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) {
3246 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3249 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3250 if(!mesh || !channel) {
3251 meshlink_errno = MESHLINK_EINVAL;
3255 pthread_mutex_lock(&mesh->mutex);
3256 utcp_shutdown(channel->c, direction);
3257 pthread_mutex_unlock(&mesh->mutex);
3260 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3261 if(!mesh || !channel) {
3262 meshlink_errno = MESHLINK_EINVAL;
3266 pthread_mutex_lock(&mesh->mutex);
3268 utcp_close(channel->c);
3270 /* Clean up any outstanding AIO buffers. */
3271 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3273 aio_signal(mesh, channel, aio);
3277 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3279 aio_signal(mesh, channel, aio);
3283 pthread_mutex_unlock(&mesh->mutex);
3288 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3289 if(!mesh || !channel) {
3290 meshlink_errno = MESHLINK_EINVAL;
3299 meshlink_errno = MESHLINK_EINVAL;
3303 // TODO: more finegrained locking.
3304 // Ideally we want to put the data into the UTCP connection's send buffer.
3305 // Then, preferably only if there is room in the receiver window,
3306 // kick the meshlink thread to go send packets.
3310 pthread_mutex_lock(&mesh->mutex);
3312 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3313 if(channel->aio_send) {
3316 retval = utcp_send(channel->c, data, len);
3319 pthread_mutex_unlock(&mesh->mutex);
3322 meshlink_errno = MESHLINK_ENETWORK;
3328 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) {
3329 if(!mesh || !channel) {
3330 meshlink_errno = MESHLINK_EINVAL;
3335 meshlink_errno = MESHLINK_EINVAL;
3339 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3342 aio->cb.buffer = cb;
3345 pthread_mutex_lock(&mesh->mutex);
3347 /* Append the AIO buffer descriptor to the end of the chain */
3348 meshlink_aio_buffer_t **p = &channel->aio_send;
3356 /* Ensure the poll callback is set, and call it right now to push data if possible */
3357 utcp_set_poll_cb(channel->c, channel_poll);
3358 channel_poll(channel->c, len);
3360 pthread_mutex_unlock(&mesh->mutex);
3365 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) {
3366 if(!mesh || !channel) {
3367 meshlink_errno = MESHLINK_EINVAL;
3371 if(!len || fd == -1) {
3372 meshlink_errno = MESHLINK_EINVAL;
3376 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3382 pthread_mutex_lock(&mesh->mutex);
3384 /* Append the AIO buffer descriptor to the end of the chain */
3385 meshlink_aio_buffer_t **p = &channel->aio_send;
3393 /* Ensure the poll callback is set, and call it right now to push data if possible */
3394 utcp_set_poll_cb(channel->c, channel_poll);
3395 channel_poll(channel->c, len);
3397 pthread_mutex_unlock(&mesh->mutex);
3402 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) {
3403 if(!mesh || !channel) {
3404 meshlink_errno = MESHLINK_EINVAL;
3409 meshlink_errno = MESHLINK_EINVAL;
3413 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3416 aio->cb.buffer = cb;
3419 pthread_mutex_lock(&mesh->mutex);
3421 /* Append the AIO buffer descriptor to the end of the chain */
3422 meshlink_aio_buffer_t **p = &channel->aio_receive;
3430 pthread_mutex_unlock(&mesh->mutex);
3435 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) {
3436 if(!mesh || !channel) {
3437 meshlink_errno = MESHLINK_EINVAL;
3441 if(!len || fd == -1) {
3442 meshlink_errno = MESHLINK_EINVAL;
3446 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3452 pthread_mutex_lock(&mesh->mutex);
3454 /* Append the AIO buffer descriptor to the end of the chain */
3455 meshlink_aio_buffer_t **p = &channel->aio_receive;
3463 pthread_mutex_unlock(&mesh->mutex);
3468 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3469 if(!mesh || !channel) {
3470 meshlink_errno = MESHLINK_EINVAL;
3474 return channel->c->flags;
3477 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3478 if(!mesh || !channel) {
3479 meshlink_errno = MESHLINK_EINVAL;
3483 return utcp_get_sendq(channel->c);
3486 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3487 if(!mesh || !channel) {
3488 meshlink_errno = MESHLINK_EINVAL;
3492 return utcp_get_recvq(channel->c);
3495 void meshlink_set_node_channel_timeout(meshlink_handle_t *mesh, meshlink_node_t *node, int timeout) {
3496 if(!mesh || !node) {
3497 meshlink_errno = MESHLINK_EINVAL;
3501 node_t *n = (node_t *)node;
3503 pthread_mutex_lock(&mesh->mutex);
3506 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3509 utcp_set_user_timeout(n->utcp, timeout);
3511 pthread_mutex_unlock(&mesh->mutex);
3514 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3515 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3516 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3519 if(mesh->node_status_cb) {
3520 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3523 if(mesh->node_pmtu_cb) {
3524 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3528 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3529 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3530 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3534 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3535 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3539 n->status.duplicate = true;
3540 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3543 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3547 meshlink_errno = MESHLINK_EINVAL;
3551 pthread_mutex_lock(&mesh->mutex);
3553 if(mesh->discovery == enable) {
3557 if(mesh->threadstarted) {
3559 discovery_start(mesh);
3561 discovery_stop(mesh);
3565 mesh->discovery = enable;
3568 pthread_mutex_unlock(&mesh->mutex);
3572 meshlink_errno = MESHLINK_ENOTSUP;
3576 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3577 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3578 meshlink_errno = EINVAL;
3582 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3583 meshlink_errno = EINVAL;
3587 pthread_mutex_lock(&mesh->mutex);
3588 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3589 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3590 pthread_mutex_unlock(&mesh->mutex);
3593 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3596 if(!mesh->connections || !mesh->loop.running) {
3603 void call_error_cb(meshlink_handle_t *mesh, meshlink_errno_t meshlink_errno) {
3604 // We should only call the callback function if we are in the background thread.
3605 if(!mesh->error_cb) {
3609 if(!mesh->threadstarted) {
3613 if(mesh->thread == pthread_self()) {
3614 mesh->error_cb(mesh, meshlink_errno);
3619 static void __attribute__((constructor)) meshlink_init(void) {
3623 static void __attribute__((destructor)) meshlink_exit(void) {