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 + (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 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",
801 const char *meshlink_strerror(meshlink_errno_t err) {
802 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
803 return "Invalid error code";
809 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
810 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
812 mesh->private_key = ecdsa_generate();
813 mesh->invitation_key = ecdsa_generate();
815 if(!mesh->private_key || !mesh->invitation_key) {
816 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
817 meshlink_errno = MESHLINK_EINTERNAL;
821 logger(mesh, MESHLINK_DEBUG, "Done.\n");
826 static struct timeval idle(event_loop_t *loop, void *data) {
828 meshlink_handle_t *mesh = data;
829 struct timeval t, tmin = {3600, 0};
831 for splay_each(node_t, n, mesh->nodes) {
836 t = utcp_timeout(n->utcp);
838 if(timercmp(&t, &tmin, <)) {
846 // Get our local address(es) by simulating connecting to an Internet host.
847 static void add_local_addresses(meshlink_handle_t *mesh) {
848 struct sockaddr_storage sn;
849 sn.ss_family = AF_UNKNOWN;
850 socklen_t sl = sizeof(sn);
854 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl, mesh->netns)) {
855 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
856 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
863 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl, mesh->netns)) {
864 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
865 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
869 static bool meshlink_setup(meshlink_handle_t *mesh) {
870 if(!config_init(mesh, "current")) {
871 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/current: %s\n", mesh->confbase, strerror(errno));
872 meshlink_errno = MESHLINK_ESTORAGE;
876 if(!ecdsa_keygen(mesh)) {
877 meshlink_errno = MESHLINK_EINTERNAL;
881 if(check_port(mesh) == 0) {
882 meshlink_errno = MESHLINK_ENETWORK;
886 /* Create a node for ourself */
888 mesh->self = new_node();
889 mesh->self->name = xstrdup(mesh->name);
890 mesh->self->devclass = mesh->devclass;
891 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
893 if(!write_main_config_files(mesh)) {
894 logger(mesh, MESHLINK_ERROR, "Could not write main config files into %s/current: %s\n", mesh->confbase, strerror(errno));
895 meshlink_errno = MESHLINK_ESTORAGE;
899 /* Ensure the configuration directory metadata is on disk */
900 if(!config_sync(mesh, "current")) {
904 if(!main_config_lock(mesh)) {
905 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
906 meshlink_errno = MESHLINK_ESTORAGE;
913 static bool meshlink_read_config(meshlink_handle_t *mesh) {
914 // Open the configuration file and lock it
915 if(!main_config_lock(mesh)) {
916 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
917 meshlink_errno = MESHLINK_ESTORAGE;
923 if(!main_config_read(mesh, "current", &config, mesh->config_key)) {
924 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
928 packmsg_input_t in = {config.buf, config.len};
929 const void *private_key;
930 const void *invitation_key;
932 uint32_t version = packmsg_get_uint32(&in);
933 char *name = packmsg_get_str_dup(&in);
934 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
935 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
936 uint16_t myport = packmsg_get_uint16(&in);
938 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
939 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
941 config_free(&config);
948 if(mesh->name && strcmp(mesh->name, name)) {
949 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
950 meshlink_errno = MESHLINK_ESTORAGE;
952 config_free(&config);
960 xasprintf(&mesh->myport, "%u", myport);
961 mesh->private_key = ecdsa_set_private_key(private_key);
962 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
963 config_free(&config);
965 /* Create a node for ourself and read our host configuration file */
967 mesh->self = new_node();
968 mesh->self->name = xstrdup(name);
969 mesh->self->devclass = mesh->devclass;
971 if(!node_read_public_key(mesh, mesh->self)) {
972 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
973 meshlink_errno = MESHLINK_ESTORAGE;
974 free_node(mesh->self);
983 static void *setup_network_in_netns_thread(void *arg) {
984 meshlink_handle_t *mesh = arg;
986 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
990 bool success = setup_network(mesh);
991 add_local_addresses(mesh);
992 return success ? arg : NULL;
996 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
997 if(!confbase || !*confbase) {
998 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
999 meshlink_errno = MESHLINK_EINVAL;
1003 if(!appname || !*appname) {
1004 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1005 meshlink_errno = MESHLINK_EINVAL;
1009 if(strchr(appname, ' ')) {
1010 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1011 meshlink_errno = MESHLINK_EINVAL;
1015 if(!name || !*name) {
1016 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1017 meshlink_errno = MESHLINK_EINVAL;
1021 if(!check_id(name)) {
1022 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1023 meshlink_errno = MESHLINK_EINVAL;
1027 if(devclass < 0 || devclass >= DEV_CLASS_COUNT) {
1028 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1029 meshlink_errno = MESHLINK_EINVAL;
1033 meshlink_open_params_t *params = xzalloc(sizeof * params);
1035 params->confbase = xstrdup(confbase);
1036 params->name = xstrdup(name);
1037 params->appname = xstrdup(appname);
1038 params->devclass = devclass;
1044 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1046 meshlink_errno = MESHLINK_EINVAL;
1050 params->netns = netns;
1055 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1057 meshlink_errno = MESHLINK_EINVAL;
1061 if((!key && keylen) || (key && !keylen)) {
1062 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1063 meshlink_errno = MESHLINK_EINVAL;
1068 params->keylen = keylen;
1073 bool meshlink_encrypted_key_rotate(meshlink_handle_t *mesh, const void *new_key, size_t new_keylen) {
1074 if(!mesh || !new_key || !new_keylen) {
1075 logger(mesh, MESHLINK_ERROR, "Invalid arguments given!\n");
1076 meshlink_errno = MESHLINK_EINVAL;
1080 pthread_mutex_lock(&(mesh->mesh_mutex));
1082 // Create hash for the new key
1083 void *new_config_key;
1084 new_config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1086 if(!prf(new_key, new_keylen, "MeshLink configuration key", 26, new_config_key, CHACHA_POLY1305_KEYLEN)) {
1087 logger(mesh, MESHLINK_ERROR, "Error creating new configuration key!\n");
1088 meshlink_errno = MESHLINK_EINTERNAL;
1089 pthread_mutex_unlock(&(mesh->mesh_mutex));
1093 // Copy contents of the "current" confbase sub-directory to "new" confbase sub-directory with the new key
1095 if(!config_copy(mesh, "current", mesh->config_key, "new", new_config_key)) {
1096 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s/old: %s\n", mesh->confbase, strerror(errno));
1097 meshlink_errno = MESHLINK_ESTORAGE;
1098 pthread_mutex_unlock(&(mesh->mesh_mutex));
1102 devtool_keyrotate_probe(1);
1104 main_config_unlock(mesh);
1106 // Rename confbase/current/ to confbase/old
1108 if(!config_rename(mesh, "current", "old")) {
1109 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/current to %s/old\n", mesh->confbase, mesh->confbase);
1110 meshlink_errno = MESHLINK_ESTORAGE;
1111 main_config_lock(mesh);
1112 pthread_mutex_unlock(&(mesh->mesh_mutex));
1116 devtool_keyrotate_probe(2);
1118 // Rename confbase/new/ to confbase/current
1120 if(!config_rename(mesh, "new", "current")) {
1121 logger(mesh, MESHLINK_ERROR, "Cannot rename %s/new to %s/current\n", mesh->confbase, mesh->confbase);
1122 meshlink_errno = MESHLINK_ESTORAGE;
1123 main_config_lock(mesh);
1124 pthread_mutex_unlock(&(mesh->mesh_mutex));
1128 devtool_keyrotate_probe(3);
1130 if(!main_config_lock(mesh)) {
1131 pthread_mutex_unlock(&(mesh->mesh_mutex));
1135 // Cleanup the "old" confbase sub-directory
1137 if(!config_destroy(mesh->confbase, "old")) {
1138 pthread_mutex_unlock(&(mesh->mesh_mutex));
1142 // Change the mesh handle key with new key
1144 free(mesh->config_key);
1145 mesh->config_key = new_config_key;
1147 pthread_mutex_unlock(&(mesh->mesh_mutex));
1152 void meshlink_open_params_free(meshlink_open_params_t *params) {
1154 meshlink_errno = MESHLINK_EINVAL;
1158 free(params->confbase);
1160 free(params->appname);
1165 /// Device class traits
1166 static const dev_class_traits_t default_class_traits[DEV_CLASS_COUNT] = {
1167 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
1168 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
1169 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
1170 { .pingtimeout = 5, .pinginterval = 60, .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN
1173 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
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;
1182 memset(¶ms, 0, sizeof(params));
1184 params.confbase = (char *)confbase;
1185 params.name = (char *)name;
1186 params.appname = (char *)appname;
1187 params.devclass = devclass;
1190 return meshlink_open_ex(¶ms);
1193 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) {
1194 if(!confbase || !*confbase) {
1195 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1196 meshlink_errno = MESHLINK_EINVAL;
1200 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1201 meshlink_open_params_t params;
1202 memset(¶ms, 0, sizeof(params));
1204 params.confbase = (char *)confbase;
1205 params.name = (char *)name;
1206 params.appname = (char *)appname;
1207 params.devclass = devclass;
1210 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1214 return meshlink_open_ex(¶ms);
1217 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1218 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1219 meshlink_open_params_t params;
1220 memset(¶ms, 0, sizeof(params));
1222 params.name = (char *)name;
1223 params.appname = (char *)appname;
1224 params.devclass = devclass;
1227 return meshlink_open_ex(¶ms);
1230 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1231 // Validate arguments provided by the application
1232 bool usingname = false;
1234 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1236 if(!params->appname || !*params->appname) {
1237 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1238 meshlink_errno = MESHLINK_EINVAL;
1242 if(strchr(params->appname, ' ')) {
1243 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1244 meshlink_errno = MESHLINK_EINVAL;
1248 if(!params->name || !*params->name) {
1249 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1251 } else { //check name only if there is a name != NULL
1253 if(!check_id(params->name)) {
1254 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1255 meshlink_errno = MESHLINK_EINVAL;
1262 if(params->devclass < 0 || params->devclass >= DEV_CLASS_COUNT) {
1263 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1264 meshlink_errno = MESHLINK_EINVAL;
1268 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1269 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1270 meshlink_errno = MESHLINK_EINVAL;
1274 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1276 if(params->confbase) {
1277 mesh->confbase = xstrdup(params->confbase);
1280 mesh->appname = xstrdup(params->appname);
1281 mesh->devclass = params->devclass;
1282 mesh->discovery = true;
1283 mesh->invitation_timeout = 604800; // 1 week
1284 mesh->netns = params->netns;
1285 mesh->submeshes = NULL;
1286 mesh->log_cb = global_log_cb;
1287 mesh->log_level = global_log_level;
1289 memcpy(mesh->dev_class_traits, default_class_traits, sizeof(default_class_traits));
1292 mesh->name = xstrdup(params->name);
1297 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1299 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1300 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1301 meshlink_close(mesh);
1302 meshlink_errno = MESHLINK_EINTERNAL;
1308 pthread_mutexattr_t attr;
1309 pthread_mutexattr_init(&attr);
1310 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1311 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1313 mesh->threadstarted = false;
1314 event_loop_init(&mesh->loop);
1315 mesh->loop.data = mesh;
1317 meshlink_queue_init(&mesh->outpacketqueue);
1319 // If no configuration exists yet, create it.
1321 if(!meshlink_confbase_exists(mesh)) {
1322 if(!meshlink_setup(mesh)) {
1323 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1324 meshlink_close(mesh);
1328 if(!meshlink_read_config(mesh)) {
1329 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1330 meshlink_close(mesh);
1336 struct WSAData wsa_state;
1337 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1340 // Setup up everything
1341 // TODO: we should not open listening sockets yet
1343 bool success = false;
1345 if(mesh->netns != -1) {
1349 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1350 void *retval = NULL;
1351 success = pthread_join(thr, &retval) == 0 && retval;
1355 meshlink_errno = MESHLINK_EINTERNAL;
1358 #endif // HAVE_SETNS
1360 success = setup_network(mesh);
1361 add_local_addresses(mesh);
1365 meshlink_close(mesh);
1366 meshlink_errno = MESHLINK_ENETWORK;
1370 add_local_addresses(mesh);
1371 node_write_config(mesh, mesh->self);
1373 idle_set(&mesh->loop, idle, mesh);
1375 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1379 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1380 meshlink_submesh_t *s = NULL;
1383 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1384 meshlink_errno = MESHLINK_EINVAL;
1388 if(!submesh || !*submesh) {
1389 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1390 meshlink_errno = MESHLINK_EINVAL;
1395 pthread_mutex_lock(&(mesh->mesh_mutex));
1397 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1399 pthread_mutex_unlock(&(mesh->mesh_mutex));
1404 static void *meshlink_main_loop(void *arg) {
1405 meshlink_handle_t *mesh = arg;
1407 if(mesh->netns != -1) {
1410 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1411 pthread_cond_signal(&mesh->cond);
1416 pthread_cond_signal(&mesh->cond);
1418 #endif // HAVE_SETNS
1423 if(mesh->discovery) {
1424 discovery_start(mesh);
1429 pthread_mutex_lock(&(mesh->mesh_mutex));
1431 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1432 pthread_cond_broadcast(&mesh->cond);
1434 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1436 pthread_mutex_unlock(&(mesh->mesh_mutex));
1441 if(mesh->discovery) {
1442 discovery_stop(mesh);
1450 bool meshlink_start(meshlink_handle_t *mesh) {
1452 assert(mesh->private_key);
1455 meshlink_errno = MESHLINK_EINVAL;
1459 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1461 pthread_mutex_lock(&(mesh->mesh_mutex));
1463 assert(mesh->self->ecdsa);
1464 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1466 if(mesh->threadstarted) {
1467 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1468 pthread_mutex_unlock(&(mesh->mesh_mutex));
1472 if(mesh->listen_socket[0].tcp.fd < 0) {
1473 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1474 meshlink_errno = MESHLINK_ENETWORK;
1478 mesh->thedatalen = 0;
1480 // TODO: open listening sockets first
1482 //Check that a valid name is set
1484 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1485 meshlink_errno = MESHLINK_EINVAL;
1486 pthread_mutex_unlock(&(mesh->mesh_mutex));
1490 init_outgoings(mesh);
1492 // Start the main thread
1494 event_loop_start(&mesh->loop);
1496 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1497 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1498 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1499 meshlink_errno = MESHLINK_EINTERNAL;
1500 event_loop_stop(&mesh->loop);
1501 pthread_mutex_unlock(&(mesh->mesh_mutex));
1505 pthread_cond_wait(&mesh->cond, &mesh->mesh_mutex);
1506 mesh->threadstarted = true;
1508 pthread_mutex_unlock(&(mesh->mesh_mutex));
1512 void meshlink_stop(meshlink_handle_t *mesh) {
1514 meshlink_errno = MESHLINK_EINVAL;
1518 pthread_mutex_lock(&(mesh->mesh_mutex));
1519 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1521 // Shut down the main thread
1522 event_loop_stop(&mesh->loop);
1524 // Send ourselves a UDP packet to kick the event loop
1525 for(int i = 0; i < mesh->listen_sockets; i++) {
1527 socklen_t salen = sizeof(sa.sa);
1529 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1530 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1534 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1535 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1539 if(mesh->threadstarted) {
1540 // Wait for the main thread to finish
1541 pthread_mutex_unlock(&(mesh->mesh_mutex));
1542 pthread_join(mesh->thread, NULL);
1543 pthread_mutex_lock(&(mesh->mesh_mutex));
1545 mesh->threadstarted = false;
1548 // Close all metaconnections
1549 if(mesh->connections) {
1550 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1552 connection_t *c = node->data;
1554 terminate_connection(mesh, c, false);
1558 exit_outgoings(mesh);
1560 // Write out any changed node config files
1562 for splay_each(node_t, n, mesh->nodes) {
1563 if(n->status.dirty) {
1564 node_write_config(mesh, n);
1565 n->status.dirty = false;
1570 pthread_mutex_unlock(&(mesh->mesh_mutex));
1573 void meshlink_close(meshlink_handle_t *mesh) {
1575 meshlink_errno = MESHLINK_EINVAL;
1579 // stop can be called even if mesh has not been started
1580 meshlink_stop(mesh);
1582 // lock is not released after this
1583 pthread_mutex_lock(&(mesh->mesh_mutex));
1585 // Close and free all resources used.
1587 close_network_connections(mesh);
1589 logger(mesh, MESHLINK_INFO, "Terminating");
1591 event_loop_exit(&mesh->loop);
1595 if(mesh->confbase) {
1601 ecdsa_free(mesh->invitation_key);
1603 if(mesh->netns != -1) {
1607 for(vpn_packet_t *packet; (packet = meshlink_queue_pop(&mesh->outpacketqueue));) {
1611 meshlink_queue_exit(&mesh->outpacketqueue);
1614 free(mesh->appname);
1615 free(mesh->confbase);
1616 free(mesh->config_key);
1617 ecdsa_free(mesh->private_key);
1618 pthread_mutex_destroy(&(mesh->mesh_mutex));
1620 main_config_unlock(mesh);
1622 memset(mesh, 0, sizeof(*mesh));
1627 bool meshlink_destroy(const char *confbase) {
1629 meshlink_errno = MESHLINK_EINVAL;
1633 if(!config_destroy(confbase, "current")) {
1634 logger(NULL, MESHLINK_ERROR, "Cannot remove confbase sub-directories %s: %s\n", confbase, strerror(errno));
1638 config_destroy(confbase, "new");
1639 config_destroy(confbase, "old");
1641 if(rmdir(confbase) && errno != ENOENT) {
1642 logger(NULL, MESHLINK_ERROR, "Cannot remove directory %s: %s\n", confbase, strerror(errno));
1643 meshlink_errno = MESHLINK_ESTORAGE;
1650 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1652 meshlink_errno = MESHLINK_EINVAL;
1656 pthread_mutex_lock(&(mesh->mesh_mutex));
1657 mesh->receive_cb = cb;
1658 pthread_mutex_unlock(&(mesh->mesh_mutex));
1661 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1663 meshlink_errno = MESHLINK_EINVAL;
1667 pthread_mutex_lock(&(mesh->mesh_mutex));
1668 mesh->connection_try_cb = cb;
1669 pthread_mutex_unlock(&(mesh->mesh_mutex));
1672 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1674 meshlink_errno = MESHLINK_EINVAL;
1678 pthread_mutex_lock(&(mesh->mesh_mutex));
1679 mesh->node_status_cb = cb;
1680 pthread_mutex_unlock(&(mesh->mesh_mutex));
1683 void meshlink_set_node_pmtu_cb(meshlink_handle_t *mesh, meshlink_node_pmtu_cb_t cb) {
1685 meshlink_errno = MESHLINK_EINVAL;
1689 pthread_mutex_lock(&(mesh->mesh_mutex));
1690 mesh->node_pmtu_cb = cb;
1691 pthread_mutex_unlock(&(mesh->mesh_mutex));
1694 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1696 meshlink_errno = MESHLINK_EINVAL;
1700 pthread_mutex_lock(&(mesh->mesh_mutex));
1701 mesh->node_duplicate_cb = cb;
1702 pthread_mutex_unlock(&(mesh->mesh_mutex));
1705 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1707 pthread_mutex_lock(&(mesh->mesh_mutex));
1709 mesh->log_level = cb ? level : 0;
1710 pthread_mutex_unlock(&(mesh->mesh_mutex));
1713 global_log_level = cb ? level : 0;
1717 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1718 meshlink_packethdr_t *hdr;
1720 // Validate arguments
1721 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1722 meshlink_errno = MESHLINK_EINVAL;
1731 meshlink_errno = MESHLINK_EINVAL;
1735 node_t *n = (node_t *)destination;
1737 if(n->status.blacklisted) {
1738 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1742 // Prepare the packet
1743 vpn_packet_t *packet = malloc(sizeof(*packet));
1746 meshlink_errno = MESHLINK_ENOMEM;
1750 packet->probe = false;
1751 packet->tcp = false;
1752 packet->len = len + sizeof(*hdr);
1754 hdr = (meshlink_packethdr_t *)packet->data;
1755 memset(hdr, 0, sizeof(*hdr));
1756 // leave the last byte as 0 to make sure strings are always
1757 // null-terminated if they are longer than the buffer
1758 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1759 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1761 memcpy(packet->data + sizeof(*hdr), data, len);
1764 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1766 meshlink_errno = MESHLINK_ENOMEM;
1770 // Notify event loop
1771 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1776 void meshlink_send_from_queue(event_loop_t *loop, void *data) {
1778 meshlink_handle_t *mesh = data;
1779 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1785 mesh->self->in_packets++;
1786 mesh->self->in_bytes += packet->len;
1787 route(mesh, mesh->self, packet);
1792 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1793 if(!mesh || !destination) {
1794 meshlink_errno = MESHLINK_EINVAL;
1798 pthread_mutex_lock(&(mesh->mesh_mutex));
1800 node_t *n = (node_t *)destination;
1802 if(!n->status.reachable) {
1803 pthread_mutex_unlock(&(mesh->mesh_mutex));
1806 } else if(n->mtuprobes > 30 && n->minmtu) {
1807 pthread_mutex_unlock(&(mesh->mesh_mutex));
1810 pthread_mutex_unlock(&(mesh->mesh_mutex));
1815 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1816 if(!mesh || !node) {
1817 meshlink_errno = MESHLINK_EINVAL;
1821 pthread_mutex_lock(&(mesh->mesh_mutex));
1823 node_t *n = (node_t *)node;
1825 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1826 meshlink_errno = MESHLINK_EINTERNAL;
1827 pthread_mutex_unlock(&(mesh->mesh_mutex));
1831 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1834 meshlink_errno = MESHLINK_EINTERNAL;
1837 pthread_mutex_unlock(&(mesh->mesh_mutex));
1841 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1843 meshlink_errno = MESHLINK_EINVAL;
1847 return (meshlink_node_t *)mesh->self;
1850 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1851 if(!mesh || !name) {
1852 meshlink_errno = MESHLINK_EINVAL;
1856 meshlink_node_t *node = NULL;
1858 pthread_mutex_lock(&(mesh->mesh_mutex));
1859 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1860 pthread_mutex_unlock(&(mesh->mesh_mutex));
1863 meshlink_errno = MESHLINK_ENOENT;
1869 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1870 if(!mesh || !name) {
1871 meshlink_errno = MESHLINK_EINVAL;
1875 meshlink_submesh_t *submesh = NULL;
1877 pthread_mutex_lock(&(mesh->mesh_mutex));
1878 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1879 pthread_mutex_unlock(&(mesh->mesh_mutex));
1882 meshlink_errno = MESHLINK_ENOENT;
1888 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1889 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1890 meshlink_errno = MESHLINK_EINVAL;
1894 meshlink_node_t **result;
1897 pthread_mutex_lock(&(mesh->mesh_mutex));
1899 *nmemb = mesh->nodes->count;
1900 result = realloc(nodes, *nmemb * sizeof(*nodes));
1903 meshlink_node_t **p = result;
1905 for splay_each(node_t, n, mesh->nodes) {
1906 *p++ = (meshlink_node_t *)n;
1911 meshlink_errno = MESHLINK_ENOMEM;
1914 pthread_mutex_unlock(&(mesh->mesh_mutex));
1919 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) {
1920 meshlink_node_t **result;
1922 pthread_mutex_lock(&(mesh->mesh_mutex));
1926 for splay_each(node_t, n, mesh->nodes) {
1927 if(true == search_node(n, condition)) {
1928 *nmemb = *nmemb + 1;
1934 pthread_mutex_unlock(&(mesh->mesh_mutex));
1938 result = realloc(nodes, *nmemb * sizeof(*nodes));
1941 meshlink_node_t **p = result;
1943 for splay_each(node_t, n, mesh->nodes) {
1944 if(true == search_node(n, condition)) {
1945 *p++ = (meshlink_node_t *)n;
1951 meshlink_errno = MESHLINK_ENOMEM;
1954 pthread_mutex_unlock(&(mesh->mesh_mutex));
1959 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1960 dev_class_t *devclass = (dev_class_t *)condition;
1962 if(*devclass == (dev_class_t)node->devclass) {
1969 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1970 if(condition == node->submesh) {
1977 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) {
1978 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT || !nmemb) {
1979 meshlink_errno = MESHLINK_EINVAL;
1983 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1986 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1987 if(!mesh || !submesh || !nmemb) {
1988 meshlink_errno = MESHLINK_EINVAL;
1992 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1995 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1996 if(!mesh || !node) {
1997 meshlink_errno = MESHLINK_EINVAL;
2001 dev_class_t devclass;
2003 pthread_mutex_lock(&(mesh->mesh_mutex));
2005 devclass = ((node_t *)node)->devclass;
2007 pthread_mutex_unlock(&(mesh->mesh_mutex));
2012 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
2013 if(!mesh || !node) {
2014 meshlink_errno = MESHLINK_EINVAL;
2018 node_t *n = (node_t *)node;
2020 meshlink_submesh_t *s;
2022 s = (meshlink_submesh_t *)n->submesh;
2027 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
2028 if(!mesh || !data || !len || !signature || !siglen) {
2029 meshlink_errno = MESHLINK_EINVAL;
2033 if(*siglen < MESHLINK_SIGLEN) {
2034 meshlink_errno = MESHLINK_EINVAL;
2038 pthread_mutex_lock(&(mesh->mesh_mutex));
2040 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
2041 meshlink_errno = MESHLINK_EINTERNAL;
2042 pthread_mutex_unlock(&(mesh->mesh_mutex));
2046 *siglen = MESHLINK_SIGLEN;
2047 pthread_mutex_unlock(&(mesh->mesh_mutex));
2051 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
2052 if(!mesh || !data || !len || !signature) {
2053 meshlink_errno = MESHLINK_EINVAL;
2057 if(siglen != MESHLINK_SIGLEN) {
2058 meshlink_errno = MESHLINK_EINVAL;
2062 pthread_mutex_lock(&(mesh->mesh_mutex));
2066 struct node_t *n = (struct node_t *)source;
2068 if(!node_read_public_key(mesh, n)) {
2069 meshlink_errno = MESHLINK_EINTERNAL;
2072 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
2075 pthread_mutex_unlock(&(mesh->mesh_mutex));
2079 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
2080 pthread_mutex_lock(&(mesh->mesh_mutex));
2082 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
2085 // TODO: Update invitation key if necessary?
2088 pthread_mutex_unlock(&(mesh->mesh_mutex));
2090 return mesh->invitation_key;
2093 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
2094 if(!mesh || !node || !address) {
2095 meshlink_errno = MESHLINK_EINVAL;
2099 if(!is_valid_hostname(address)) {
2100 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
2101 meshlink_errno = MESHLINK_EINVAL;
2105 if(port && !is_valid_port(port)) {
2106 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
2107 meshlink_errno = MESHLINK_EINVAL;
2111 char *canonical_address;
2114 xasprintf(&canonical_address, "%s %s", address, port);
2116 canonical_address = xstrdup(address);
2119 pthread_mutex_lock(&(mesh->mesh_mutex));
2121 node_t *n = (node_t *)node;
2122 free(n->canonical_address);
2123 n->canonical_address = canonical_address;
2124 node_write_config(mesh, n);
2126 pthread_mutex_unlock(&(mesh->mesh_mutex));
2131 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
2132 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
2135 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
2137 meshlink_errno = MESHLINK_EINVAL;
2141 char *address = meshlink_get_external_address(mesh);
2147 bool rval = meshlink_add_address(mesh, address);
2153 int meshlink_get_port(meshlink_handle_t *mesh) {
2155 meshlink_errno = MESHLINK_EINVAL;
2160 meshlink_errno = MESHLINK_EINTERNAL;
2166 pthread_mutex_lock(&(mesh->mesh_mutex));
2167 port = atoi(mesh->myport);
2168 pthread_mutex_unlock(&(mesh->mesh_mutex));
2173 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2174 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2175 meshlink_errno = MESHLINK_EINVAL;
2179 if(mesh->myport && port == atoi(mesh->myport)) {
2183 if(!try_bind(port)) {
2184 meshlink_errno = MESHLINK_ENETWORK;
2188 devtool_trybind_probe();
2192 pthread_mutex_lock(&(mesh->mesh_mutex));
2194 if(mesh->threadstarted) {
2195 meshlink_errno = MESHLINK_EINVAL;
2200 xasprintf(&mesh->myport, "%d", port);
2202 /* Close down the network. This also deletes mesh->self. */
2203 close_network_connections(mesh);
2205 /* Recreate mesh->self. */
2206 mesh->self = new_node();
2207 mesh->self->name = xstrdup(mesh->name);
2208 mesh->self->devclass = mesh->devclass;
2209 xasprintf(&mesh->myport, "%d", port);
2211 if(!node_read_public_key(mesh, mesh->self)) {
2212 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2213 meshlink_errno = MESHLINK_ESTORAGE;
2214 free_node(mesh->self);
2217 } else if(!setup_network(mesh)) {
2218 meshlink_errno = MESHLINK_ENETWORK;
2222 /* Rebuild our own list of recent addresses */
2223 memset(mesh->self->recent, 0, sizeof(mesh->self->recent));
2224 add_local_addresses(mesh);
2226 /* Write meshlink.conf with the updated port number */
2227 write_main_config_files(mesh);
2229 rval = config_sync(mesh, "current");
2232 pthread_mutex_unlock(&(mesh->mesh_mutex));
2234 return rval && meshlink_get_port(mesh) == port;
2237 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2238 mesh->invitation_timeout = timeout;
2241 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2242 meshlink_submesh_t *s = NULL;
2245 meshlink_errno = MESHLINK_EINVAL;
2250 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2253 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2254 meshlink_errno = MESHLINK_EINVAL;
2258 s = (meshlink_submesh_t *)mesh->self->submesh;
2261 pthread_mutex_lock(&(mesh->mesh_mutex));
2263 // Check validity of the new node's name
2264 if(!check_id(name)) {
2265 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2266 meshlink_errno = MESHLINK_EINVAL;
2267 pthread_mutex_unlock(&(mesh->mesh_mutex));
2271 // Ensure no host configuration file with that name exists
2272 if(config_exists(mesh, "current", name)) {
2273 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2274 meshlink_errno = MESHLINK_EEXIST;
2275 pthread_mutex_unlock(&(mesh->mesh_mutex));
2279 // Ensure no other nodes know about this name
2280 if(meshlink_get_node(mesh, name)) {
2281 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2282 meshlink_errno = MESHLINK_EEXIST;
2283 pthread_mutex_unlock(&(mesh->mesh_mutex));
2287 // Get the local address
2288 char *address = get_my_hostname(mesh, flags);
2291 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2292 meshlink_errno = MESHLINK_ERESOLV;
2293 pthread_mutex_unlock(&(mesh->mesh_mutex));
2297 if(!refresh_invitation_key(mesh)) {
2298 meshlink_errno = MESHLINK_EINTERNAL;
2299 pthread_mutex_unlock(&(mesh->mesh_mutex));
2305 // Create a hash of the key.
2306 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2307 sha512(fingerprint, strlen(fingerprint), hash);
2308 b64encode_urlsafe(hash, hash, 18);
2310 // Create a random cookie for this invitation.
2312 randomize(cookie, 18);
2314 // Create a filename that doesn't reveal the cookie itself
2315 char buf[18 + strlen(fingerprint)];
2316 char cookiehash[64];
2317 memcpy(buf, cookie, 18);
2318 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2319 sha512(buf, sizeof(buf), cookiehash);
2320 b64encode_urlsafe(cookiehash, cookiehash, 18);
2322 b64encode_urlsafe(cookie, cookie, 18);
2326 /* Construct the invitation file */
2327 uint8_t outbuf[4096];
2328 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2330 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2331 packmsg_add_str(&inv, name);
2332 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2333 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2335 /* TODO: Add several host config files to bootstrap connections.
2336 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2337 * and are not blacklisted.
2339 config_t configs[5];
2340 memset(configs, 0, sizeof(configs));
2343 if(config_read(mesh, "current", mesh->self->name, &configs[count], mesh->config_key)) {
2347 /* Append host config files to the invitation file */
2348 packmsg_add_array(&inv, count);
2350 for(int i = 0; i < count; i++) {
2351 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2352 config_free(&configs[i]);
2355 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2357 if(!invitation_write(mesh, "current", cookiehash, &config, mesh->config_key)) {
2358 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2359 meshlink_errno = MESHLINK_ESTORAGE;
2360 pthread_mutex_unlock(&(mesh->mesh_mutex));
2364 // Create an URL from the local address, key hash and cookie
2366 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2369 pthread_mutex_unlock(&(mesh->mesh_mutex));
2373 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2374 return meshlink_invite_ex(mesh, submesh, name, 0);
2377 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2378 if(!mesh || !invitation) {
2379 meshlink_errno = MESHLINK_EINVAL;
2383 pthread_mutex_lock(&(mesh->mesh_mutex));
2385 //Before doing meshlink_join make sure we are not connected to another mesh
2386 if(mesh->threadstarted) {
2387 logger(mesh, MESHLINK_ERROR, "Cannot join while started\n");
2388 meshlink_errno = MESHLINK_EINVAL;
2389 pthread_mutex_unlock(&(mesh->mesh_mutex));
2393 // 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.
2394 if(mesh->nodes->count > 1) {
2395 logger(mesh, MESHLINK_ERROR, "Already part of an existing mesh\n");
2396 meshlink_errno = MESHLINK_EINVAL;
2397 pthread_mutex_unlock(&(mesh->mesh_mutex));
2401 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2402 char copy[strlen(invitation) + 1];
2403 strcpy(copy, invitation);
2405 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2407 char *slash = strchr(copy, '/');
2415 if(strlen(slash) != 48) {
2419 char *address = copy;
2422 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2426 // Generate a throw-away key for the invitation.
2427 ecdsa_t *key = ecdsa_generate();
2430 meshlink_errno = MESHLINK_EINTERNAL;
2431 pthread_mutex_unlock(&(mesh->mesh_mutex));
2435 char *b64key = ecdsa_get_base64_public_key(key);
2439 while(address && *address) {
2440 // We allow commas in the address part to support multiple addresses in one invitation URL.
2441 comma = strchr(address, ',');
2447 // Split of the port
2448 port = strrchr(address, ':');
2456 // IPv6 address are enclosed in brackets, per RFC 3986
2457 if(*address == '[') {
2459 char *bracket = strchr(address, ']');
2472 // Connect to the meshlink daemon mentioned in the URL.
2473 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2476 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2477 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2479 if(mesh->sock == -1) {
2480 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2481 meshlink_errno = MESHLINK_ENETWORK;
2485 set_timeout(mesh->sock, 5000);
2487 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2488 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2489 meshlink_errno = MESHLINK_ENETWORK;
2490 closesocket(mesh->sock);
2498 meshlink_errno = MESHLINK_ERESOLV;
2501 if(mesh->sock != -1 || !comma) {
2508 if(mesh->sock == -1) {
2509 pthread_mutex_unlock(&mesh->mesh_mutex);
2513 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2515 // Tell him we have an invitation, and give him our throw-away key.
2519 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2520 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2521 closesocket(mesh->sock);
2522 meshlink_errno = MESHLINK_ENETWORK;
2523 pthread_mutex_unlock(&(mesh->mesh_mutex));
2529 char hisname[4096] = "";
2530 int code, hismajor, hisminor = 0;
2532 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) {
2533 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2534 closesocket(mesh->sock);
2535 meshlink_errno = MESHLINK_ENETWORK;
2536 pthread_mutex_unlock(&(mesh->mesh_mutex));
2540 // Check if the hash of the key he gave us matches the hash in the URL.
2541 char *fingerprint = mesh->line + 2;
2544 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2545 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2546 meshlink_errno = MESHLINK_EINTERNAL;
2547 pthread_mutex_unlock(&(mesh->mesh_mutex));
2551 if(memcmp(hishash, mesh->hash, 18)) {
2552 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2553 meshlink_errno = MESHLINK_EPEER;
2554 pthread_mutex_unlock(&(mesh->mesh_mutex));
2559 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2562 meshlink_errno = MESHLINK_EINTERNAL;
2563 pthread_mutex_unlock(&(mesh->mesh_mutex));
2567 // Start an SPTPS session
2568 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2569 meshlink_errno = MESHLINK_EINTERNAL;
2570 pthread_mutex_unlock(&(mesh->mesh_mutex));
2574 // Feed rest of input buffer to SPTPS
2575 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2576 meshlink_errno = MESHLINK_EPEER;
2577 pthread_mutex_unlock(&(mesh->mesh_mutex));
2583 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2585 if(errno == EINTR) {
2589 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2590 meshlink_errno = MESHLINK_ENETWORK;
2591 pthread_mutex_unlock(&(mesh->mesh_mutex));
2595 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2596 meshlink_errno = MESHLINK_EPEER;
2597 pthread_mutex_unlock(&(mesh->mesh_mutex));
2602 sptps_stop(&mesh->sptps);
2605 closesocket(mesh->sock);
2607 if(!mesh->success) {
2608 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2609 meshlink_errno = MESHLINK_EPEER;
2610 pthread_mutex_unlock(&(mesh->mesh_mutex));
2614 pthread_mutex_unlock(&(mesh->mesh_mutex));
2618 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2619 meshlink_errno = MESHLINK_EINVAL;
2620 pthread_mutex_unlock(&(mesh->mesh_mutex));
2624 char *meshlink_export(meshlink_handle_t *mesh) {
2626 meshlink_errno = MESHLINK_EINVAL;
2630 // Create a config file on the fly.
2633 packmsg_output_t out = {buf, sizeof(buf)};
2634 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2635 packmsg_add_str(&out, mesh->name);
2636 packmsg_add_str(&out, CORE_MESH);
2638 pthread_mutex_lock(&(mesh->mesh_mutex));
2640 packmsg_add_int32(&out, mesh->self->devclass);
2641 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2642 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2643 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2647 for(uint32_t i = 0; i < 5; i++) {
2648 if(mesh->self->recent[i].sa.sa_family) {
2655 packmsg_add_array(&out, count);
2657 for(uint32_t i = 0; i < count; i++) {
2658 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2661 pthread_mutex_unlock(&(mesh->mesh_mutex));
2663 if(!packmsg_output_ok(&out)) {
2664 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2665 meshlink_errno = MESHLINK_EINTERNAL;
2669 // Prepare a base64-encoded packmsg array containing our config file
2671 uint32_t len = packmsg_output_size(&out, buf);
2672 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2673 uint8_t *buf2 = xmalloc(len2);
2674 packmsg_output_t out2 = {buf2, len2};
2675 packmsg_add_array(&out2, 1);
2676 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2678 if(!packmsg_output_ok(&out2)) {
2679 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2680 meshlink_errno = MESHLINK_EINTERNAL;
2685 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2687 return (char *)buf2;
2690 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2691 if(!mesh || !data) {
2692 meshlink_errno = MESHLINK_EINVAL;
2696 size_t datalen = strlen(data);
2697 uint8_t *buf = xmalloc(datalen);
2698 int buflen = b64decode(data, buf, datalen);
2701 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2702 meshlink_errno = MESHLINK_EPEER;
2706 packmsg_input_t in = {buf, buflen};
2707 uint32_t count = packmsg_get_array(&in);
2710 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2711 meshlink_errno = MESHLINK_EPEER;
2715 pthread_mutex_lock(&(mesh->mesh_mutex));
2719 uint32_t len = packmsg_get_bin_raw(&in, &data);
2725 packmsg_input_t in2 = {data, len};
2726 uint32_t version = packmsg_get_uint32(&in2);
2727 char *name = packmsg_get_str_dup(&in2);
2729 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2731 packmsg_input_invalidate(&in);
2735 if(!check_id(name)) {
2740 node_t *n = lookup_node(mesh, name);
2743 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2751 config_t config = {data, len};
2753 if(!node_read_from_config(mesh, n, &config)) {
2755 packmsg_input_invalidate(&in);
2759 config_write(mesh, "current", n->name, &config, mesh->config_key);
2763 pthread_mutex_unlock(&(mesh->mesh_mutex));
2767 if(!packmsg_done(&in)) {
2768 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2769 meshlink_errno = MESHLINK_EPEER;
2773 if(!config_sync(mesh, "current")) {
2780 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2781 if(!mesh || !node) {
2782 meshlink_errno = MESHLINK_EINVAL;
2786 pthread_mutex_lock(&(mesh->mesh_mutex));
2791 if(n == mesh->self) {
2792 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2793 meshlink_errno = MESHLINK_EINVAL;
2794 pthread_mutex_unlock(&(mesh->mesh_mutex));
2798 if(n->status.blacklisted) {
2799 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2800 pthread_mutex_unlock(&(mesh->mesh_mutex));
2804 n->status.blacklisted = true;
2805 node_write_config(mesh, n);
2806 config_sync(mesh, "current");
2808 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2810 //Immediately terminate any connections we have with the blacklisted node
2811 for list_each(connection_t, c, mesh->connections) {
2813 terminate_connection(mesh, c, c->status.active);
2817 utcp_abort_all_connections(n->utcp);
2823 n->status.udp_confirmed = false;
2825 if(n->status.reachable) {
2826 update_node_status(mesh, n);
2829 pthread_mutex_unlock(&(mesh->mesh_mutex));
2832 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2833 if(!mesh || !node) {
2834 meshlink_errno = MESHLINK_EINVAL;
2838 pthread_mutex_lock(&(mesh->mesh_mutex));
2840 node_t *n = (node_t *)node;
2842 if(!n->status.blacklisted) {
2843 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2844 meshlink_errno = MESHLINK_EINVAL;
2845 pthread_mutex_unlock(&(mesh->mesh_mutex));
2849 n->status.blacklisted = false;
2850 node_write_config(mesh, n);
2851 config_sync(mesh, "current");
2853 if(n->status.reachable) {
2854 update_node_status(mesh, n);
2857 pthread_mutex_unlock(&(mesh->mesh_mutex));
2861 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2862 mesh->default_blacklist = blacklist;
2865 /* Hint that a hostname may be found at an address
2866 * See header file for detailed comment.
2868 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2869 if(!mesh || !node || !addr) {
2870 meshlink_errno = EINVAL;
2874 pthread_mutex_lock(&(mesh->mesh_mutex));
2876 node_t *n = (node_t *)node;
2877 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2878 memcpy(n->recent, addr, SALEN(*addr));
2879 node_write_config(mesh, n);
2881 pthread_mutex_unlock(&(mesh->mesh_mutex));
2882 // @TODO do we want to fire off a connection attempt right away?
2885 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2887 node_t *n = utcp->priv;
2888 meshlink_handle_t *mesh = n->mesh;
2889 return mesh->channel_accept_cb;
2892 static void aio_signal(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_aio_buffer_t *aio) {
2894 if(aio->cb.buffer) {
2895 aio->cb.buffer(mesh, channel, aio->data, aio->len, aio->priv);
2899 aio->cb.fd(mesh, channel, aio->fd, aio->done, aio->priv);
2904 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2905 meshlink_channel_t *channel = connection->priv;
2911 node_t *n = channel->node;
2912 meshlink_handle_t *mesh = n->mesh;
2914 if(n->status.destroyed) {
2915 meshlink_channel_close(mesh, channel);
2919 const char *p = data;
2922 while(channel->aio_receive) {
2923 meshlink_aio_buffer_t *aio = channel->aio_receive;
2924 size_t todo = aio->len - aio->done;
2931 memcpy((char *)aio->data + aio->done, p, todo);
2933 ssize_t result = write(aio->fd, p, todo);
2942 if(aio->done == aio->len) {
2943 channel->aio_receive = aio->next;
2944 aio_signal(mesh, channel, aio);
2956 if(channel->receive_cb) {
2957 channel->receive_cb(mesh, channel, p, left);
2963 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2964 node_t *n = utcp_connection->utcp->priv;
2970 meshlink_handle_t *mesh = n->mesh;
2972 if(!mesh->channel_accept_cb) {
2976 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2978 channel->c = utcp_connection;
2980 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2981 utcp_accept(utcp_connection, channel_recv, channel);
2987 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2988 node_t *n = utcp->priv;
2990 if(n->status.destroyed) {
2994 meshlink_handle_t *mesh = n->mesh;
2995 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2998 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2999 if(!mesh || !channel) {
3000 meshlink_errno = MESHLINK_EINVAL;
3004 channel->receive_cb = cb;
3007 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
3009 node_t *n = (node_t *)source;
3015 utcp_recv(n->utcp, data, len);
3018 static void channel_poll(struct utcp_connection *connection, size_t len) {
3019 meshlink_channel_t *channel = connection->priv;
3025 node_t *n = channel->node;
3026 meshlink_handle_t *mesh = n->mesh;
3027 meshlink_aio_buffer_t *aio = channel->aio_send;
3030 /* We at least one AIO buffer. Send as much as possible form the first buffer. */
3031 size_t left = aio->len - aio->done;
3039 sent = utcp_send(connection, (char *)aio->data + aio->done, len);
3042 size_t todo = utcp_get_sndbuf_free(connection);
3048 if(todo > sizeof(buf)) {
3052 ssize_t result = read(aio->fd, buf, todo);
3055 sent = utcp_send(connection, buf, result);
3065 /* If the buffer is now completely sent, call the callback and dispose of it. */
3066 if(aio->done >= aio->len) {
3067 channel->aio_send = aio->next;
3068 aio_signal(mesh, channel, aio);
3072 if(channel->poll_cb) {
3073 channel->poll_cb(mesh, channel, len);
3075 utcp_set_poll_cb(connection, NULL);
3080 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
3081 if(!mesh || !channel) {
3082 meshlink_errno = MESHLINK_EINVAL;
3086 pthread_mutex_lock(&mesh->mesh_mutex);
3087 channel->poll_cb = cb;
3088 utcp_set_poll_cb(channel->c, (cb || channel->aio_send) ? channel_poll : NULL);
3089 pthread_mutex_unlock(&mesh->mesh_mutex);
3092 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
3094 meshlink_errno = MESHLINK_EINVAL;
3098 pthread_mutex_lock(&mesh->mesh_mutex);
3099 mesh->channel_accept_cb = cb;
3100 mesh->receive_cb = channel_receive;
3102 for splay_each(node_t, n, mesh->nodes) {
3103 if(!n->utcp && n != mesh->self) {
3104 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3108 pthread_mutex_unlock(&mesh->mesh_mutex);
3111 void meshlink_set_channel_sndbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3115 meshlink_errno = MESHLINK_EINVAL;
3119 pthread_mutex_lock(&mesh->mesh_mutex);
3120 utcp_set_sndbuf(channel->c, size);
3121 pthread_mutex_unlock(&mesh->mesh_mutex);
3124 void meshlink_set_channel_rcvbuf(meshlink_handle_t *mesh, meshlink_channel_t *channel, size_t size) {
3128 meshlink_errno = MESHLINK_EINVAL;
3132 pthread_mutex_lock(&mesh->mesh_mutex);
3133 utcp_set_rcvbuf(channel->c, size);
3134 pthread_mutex_unlock(&mesh->mesh_mutex);
3137 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) {
3139 abort(); // TODO: handle non-NULL data
3142 if(!mesh || !node) {
3143 meshlink_errno = MESHLINK_EINVAL;
3147 pthread_mutex_lock(&mesh->mesh_mutex);
3149 node_t *n = (node_t *)node;
3152 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3153 mesh->receive_cb = channel_receive;
3156 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3157 pthread_mutex_unlock(&mesh->mesh_mutex);
3162 if(n->status.blacklisted) {
3163 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
3164 pthread_mutex_unlock(&mesh->mesh_mutex);
3168 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
3170 channel->receive_cb = cb;
3171 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
3173 pthread_mutex_unlock(&mesh->mesh_mutex);
3176 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
3184 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) {
3185 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
3188 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
3189 if(!mesh || !channel) {
3190 meshlink_errno = MESHLINK_EINVAL;
3194 pthread_mutex_lock(&mesh->mesh_mutex);
3195 utcp_shutdown(channel->c, direction);
3196 pthread_mutex_unlock(&mesh->mesh_mutex);
3199 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3200 if(!mesh || !channel) {
3201 meshlink_errno = MESHLINK_EINVAL;
3205 pthread_mutex_lock(&mesh->mesh_mutex);
3207 utcp_close(channel->c);
3209 /* Clean up any outstanding AIO buffers. */
3210 for(meshlink_aio_buffer_t *aio = channel->aio_send, *next; aio; aio = next) {
3212 aio_signal(mesh, channel, aio);
3216 for(meshlink_aio_buffer_t *aio = channel->aio_receive, *next; aio; aio = next) {
3218 aio_signal(mesh, channel, aio);
3222 pthread_mutex_unlock(&mesh->mesh_mutex);
3227 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
3228 if(!mesh || !channel) {
3229 meshlink_errno = MESHLINK_EINVAL;
3238 meshlink_errno = MESHLINK_EINVAL;
3242 // TODO: more finegrained locking.
3243 // Ideally we want to put the data into the UTCP connection's send buffer.
3244 // Then, preferably only if there is room in the receiver window,
3245 // kick the meshlink thread to go send packets.
3249 pthread_mutex_lock(&mesh->mesh_mutex);
3251 /* Disallow direct calls to utcp_send() while we still have AIO active. */
3252 if(channel->aio_send) {
3255 retval = utcp_send(channel->c, data, len);
3258 pthread_mutex_unlock(&mesh->mesh_mutex);
3261 meshlink_errno = MESHLINK_ENETWORK;
3267 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) {
3268 if(!mesh || !channel) {
3269 meshlink_errno = MESHLINK_EINVAL;
3274 meshlink_errno = MESHLINK_EINVAL;
3278 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3281 aio->cb.buffer = cb;
3284 pthread_mutex_lock(&mesh->mesh_mutex);
3286 /* Append the AIO buffer descriptor to the end of the chain */
3287 meshlink_aio_buffer_t **p = &channel->aio_send;
3295 /* Ensure the poll callback is set, and call it right now to push data if possible */
3296 utcp_set_poll_cb(channel->c, channel_poll);
3297 channel_poll(channel->c, len);
3299 pthread_mutex_unlock(&mesh->mesh_mutex);
3304 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) {
3305 if(!mesh || !channel) {
3306 meshlink_errno = MESHLINK_EINVAL;
3310 if(!len || fd == -1) {
3311 meshlink_errno = MESHLINK_EINVAL;
3315 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3321 pthread_mutex_lock(&mesh->mesh_mutex);
3323 /* Append the AIO buffer descriptor to the end of the chain */
3324 meshlink_aio_buffer_t **p = &channel->aio_send;
3332 /* Ensure the poll callback is set, and call it right now to push data if possible */
3333 utcp_set_poll_cb(channel->c, channel_poll);
3334 channel_poll(channel->c, len);
3336 pthread_mutex_unlock(&mesh->mesh_mutex);
3341 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) {
3342 if(!mesh || !channel) {
3343 meshlink_errno = MESHLINK_EINVAL;
3348 meshlink_errno = MESHLINK_EINVAL;
3352 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3355 aio->cb.buffer = cb;
3358 pthread_mutex_lock(&mesh->mesh_mutex);
3360 /* Append the AIO buffer descriptor to the end of the chain */
3361 meshlink_aio_buffer_t **p = &channel->aio_receive;
3369 pthread_mutex_unlock(&mesh->mesh_mutex);
3374 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) {
3375 if(!mesh || !channel) {
3376 meshlink_errno = MESHLINK_EINVAL;
3380 if(!len || fd == -1) {
3381 meshlink_errno = MESHLINK_EINVAL;
3385 meshlink_aio_buffer_t *aio = xzalloc(sizeof(*aio));
3391 pthread_mutex_lock(&mesh->mesh_mutex);
3393 /* Append the AIO buffer descriptor to the end of the chain */
3394 meshlink_aio_buffer_t **p = &channel->aio_receive;
3402 pthread_mutex_unlock(&mesh->mesh_mutex);
3407 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3408 if(!mesh || !channel) {
3409 meshlink_errno = MESHLINK_EINVAL;
3413 return channel->c->flags;
3416 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3417 if(!mesh || !channel) {
3418 meshlink_errno = MESHLINK_EINVAL;
3422 return utcp_get_sendq(channel->c);
3425 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
3426 if(!mesh || !channel) {
3427 meshlink_errno = MESHLINK_EINVAL;
3431 return utcp_get_recvq(channel->c);
3434 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
3435 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
3436 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
3439 if(mesh->node_status_cb) {
3440 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
3443 if(mesh->node_pmtu_cb) {
3444 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3448 void update_node_pmtu(meshlink_handle_t *mesh, node_t *n) {
3449 if(mesh->node_pmtu_cb && !n->status.blacklisted) {
3450 mesh->node_pmtu_cb(mesh, (meshlink_node_t *)n, n->minmtu);
3454 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
3455 if(!mesh->node_duplicate_cb || n->status.duplicate) {
3459 n->status.duplicate = true;
3460 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
3463 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
3467 meshlink_errno = MESHLINK_EINVAL;
3471 pthread_mutex_lock(&mesh->mesh_mutex);
3473 if(mesh->discovery == enable) {
3477 if(mesh->threadstarted) {
3479 discovery_start(mesh);
3481 discovery_stop(mesh);
3485 mesh->discovery = enable;
3488 pthread_mutex_unlock(&mesh->mesh_mutex);
3492 meshlink_errno = MESHLINK_ENOTSUP;
3496 void meshlink_set_dev_class_timeouts(meshlink_handle_t *mesh, dev_class_t devclass, int pinginterval, int pingtimeout) {
3497 if(!mesh || devclass < 0 || devclass >= DEV_CLASS_COUNT) {
3498 meshlink_errno = EINVAL;
3502 if(pinginterval < 1 || pingtimeout < 1 || pingtimeout > pinginterval) {
3503 meshlink_errno = EINVAL;
3507 pthread_mutex_lock(&mesh->mesh_mutex);
3508 mesh->dev_class_traits[devclass].pinginterval = pinginterval;
3509 mesh->dev_class_traits[devclass].pingtimeout = pingtimeout;
3510 pthread_mutex_unlock(&mesh->mesh_mutex);
3513 void handle_network_change(meshlink_handle_t *mesh, bool online) {
3516 if(!mesh->connections || !mesh->loop.running) {
3523 static void __attribute__((constructor)) meshlink_init(void) {
3526 randomize(&seed, sizeof(seed));
3530 static void __attribute__((destructor)) meshlink_exit(void) {