2 meshlink.c -- Implementation of the MeshLink API.
3 Copyright (C) 2014-2018 Guus Sliepen <guus@meshlink.io>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 #include "meshlink_internal.h"
37 #include "ed25519/sha512.h"
38 #include "discovery.h"
42 #define MSG_NOSIGNAL 0
44 __thread meshlink_errno_t meshlink_errno;
45 meshlink_log_cb_t global_log_cb;
46 meshlink_log_level_t global_log_level;
48 typedef bool (*search_node_by_condition_t)(const node_t *, const void *);
50 static int rstrip(char *value) {
51 int len = strlen(value);
53 while(len && strchr("\t\r\n ", value[len - 1])) {
60 static void get_canonical_address(node_t *n, char **hostname, char **port) {
61 if(!n->canonical_address) {
65 *hostname = xstrdup(n->canonical_address);
66 char *space = strchr(*hostname, ' ');
70 *port = xstrdup(space);
74 static bool is_valid_hostname(const char *hostname) {
79 for(const char *p = hostname; *p; p++) {
80 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
88 static bool is_valid_port(const char *port) {
95 unsigned long int result = strtoul(port, &end, 10);
96 return result && result < 65536 && !*end;
99 for(const char *p = port; *p; p++) {
100 if(!(isalnum(*p) || *p == '-')) {
108 static void set_timeout(int sock, int timeout) {
113 tv.tv_sec = timeout / 1000;
114 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
116 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
117 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
120 struct socket_in_netns_params {
129 static void *socket_in_netns_thread(void *arg) {
130 struct socket_in_netns_params *params = arg;
132 if(setns(params->netns, CLONE_NEWNET) == -1) {
133 meshlink_errno = MESHLINK_EINVAL;
137 params->fd = socket(params->domain, params->type, params->protocol);
143 static int socket_in_netns(int domain, int type, int protocol, int netns) {
145 return socket(domain, type, protocol);
149 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
153 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
154 pthread_join(thr, NULL);
164 // Find out what local address a socket would use if we connect to the given address.
165 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
166 // of both endpoints, but this will actually not send any UDP packet.
167 static bool getlocaladdr(char *destaddr, struct sockaddr *sn, socklen_t *sl, int netns) {
168 struct addrinfo *rai = NULL;
169 const struct addrinfo hint = {
170 .ai_family = AF_UNSPEC,
171 .ai_socktype = SOCK_DGRAM,
172 .ai_protocol = IPPROTO_UDP,
175 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
179 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
186 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
194 if(getsockname(sock, sn, sl)) {
203 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
204 struct sockaddr_storage sn;
205 socklen_t sl = sizeof(sn);
207 if(!getlocaladdr(destaddr, (struct sockaddr *)&sn, &sl, netns)) {
211 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
218 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
219 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
222 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
223 char *hostname = NULL;
225 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
226 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
227 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
230 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
231 if(family != AF_UNSPEC && aip->ai_family != family) {
235 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
238 set_timeout(s, 5000);
240 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
247 send(s, request, sizeof(request) - 1, 0);
248 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
253 if(line[len - 1] == '\n') {
257 char *p = strrchr(line, '\n');
260 hostname = xstrdup(p + 1);
276 // Check that the hostname is reasonable
277 if(hostname && !is_valid_hostname(hostname)) {
283 meshlink_errno = MESHLINK_ERESOLV;
289 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
292 // Determine address of the local interface used for outgoing connections.
293 char localaddr[NI_MAXHOST];
294 bool success = false;
296 if(family == AF_INET) {
297 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
298 } else if(family == AF_INET6) {
299 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
303 meshlink_errno = MESHLINK_ENETWORK;
307 return xstrdup(localaddr);
310 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
311 for(int i = 0; i < n; i++) {
316 // Ignore duplicate hostnames
319 for(int j = 0; j < i; j++) {
324 if(strcmp(host[i], host[j])) {
328 if(strcmp(port[i], port[j])) {
346 // This gets the hostname part for use in invitation URLs
347 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
348 char *hostname[4] = {NULL};
349 char *port[4] = {NULL};
350 char *hostport = NULL;
352 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
353 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
356 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
357 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
360 // Add local addresses if requested
361 if(flags & MESHLINK_INVITE_LOCAL) {
362 if(flags & MESHLINK_INVITE_IPV4) {
363 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
366 if(flags & MESHLINK_INVITE_IPV6) {
367 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
371 // Add public/canonical addresses if requested
372 if(flags & MESHLINK_INVITE_PUBLIC) {
373 // Try the CanonicalAddress first
374 get_canonical_address(mesh->self, &hostname[2], &port[2]);
377 if(flags & MESHLINK_INVITE_IPV4) {
378 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
381 if(flags & MESHLINK_INVITE_IPV6) {
382 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
387 for(int i = 0; i < 4; i++) {
388 // Ensure we always have a port number
389 if(hostname[i] && !port[i]) {
390 port[i] = xstrdup(mesh->myport);
394 remove_duplicate_hostnames(hostname, port, 4);
396 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
397 for(int i = 0; i < 4; i++) {
402 // Convert what we have to a sockaddr
403 struct addrinfo *ai_in, *ai_out;
404 struct addrinfo hint = {
405 .ai_family = AF_UNSPEC,
406 .ai_flags = AI_NUMERICSERV,
407 .ai_socktype = SOCK_STREAM,
409 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
415 // Convert it to a hostname
416 char resolved_host[NI_MAXHOST];
417 char resolved_port[NI_MAXSERV];
418 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
425 // Convert the hostname back to a sockaddr
426 hint.ai_family = ai_in->ai_family;
427 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
434 // Check if it's still the same sockaddr
435 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
437 freeaddrinfo(ai_out);
441 // Yes: replace the hostname with the resolved one
443 hostname[i] = xstrdup(resolved_host);
446 freeaddrinfo(ai_out);
450 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
451 remove_duplicate_hostnames(hostname, port, 4);
453 // Concatenate all unique address to the hostport string
454 for(int i = 0; i < 4; i++) {
459 // Ensure we have the same addresses in our own host config file.
461 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
463 //config_add_string(&mesh->config, "Address", tmphostport);
466 // Append the address to the hostport string
468 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
470 hostport = newhostport;
479 static bool try_bind(int port) {
480 struct addrinfo *ai = NULL;
481 struct addrinfo hint = {
482 .ai_flags = AI_PASSIVE,
483 .ai_family = AF_UNSPEC,
484 .ai_socktype = SOCK_STREAM,
485 .ai_protocol = IPPROTO_TCP,
489 snprintf(portstr, sizeof(portstr), "%d", port);
491 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
496 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
497 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
504 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
517 int check_port(meshlink_handle_t *mesh) {
518 for(int i = 0; i < 1000; i++) {
519 int port = 0x1000 + (rand() & 0x7fff);
523 xasprintf(&mesh->myport, "%d", port);
528 meshlink_errno = MESHLINK_ENETWORK;
529 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
533 static bool write_main_config_files(meshlink_handle_t *mesh) {
536 /* Write the main config file */
537 packmsg_output_t out = {buf, sizeof buf};
539 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
540 packmsg_add_str(&out, mesh->name);
541 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
542 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
543 packmsg_add_uint16(&out, atoi(mesh->myport));
545 if(!packmsg_output_ok(&out)) {
549 config_t config = {buf, packmsg_output_size(&out, buf)};
551 if(!main_config_write(mesh, &config)) {
555 /* Write our own host config file */
556 if(!node_write_config(mesh, mesh->self)) {
563 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
564 packmsg_input_t in = {buf, len};
565 uint32_t version = packmsg_get_uint32(&in);
567 if(version != MESHLINK_INVITATION_VERSION) {
568 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
572 char *name = packmsg_get_str_dup(&in);
573 packmsg_skip_element(&in); /* submesh */
574 int32_t devclass = packmsg_get_int32(&in);
575 uint32_t count = packmsg_get_array(&in);
578 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
582 if(!check_id(name)) {
583 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
589 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
595 free(mesh->self->name);
597 mesh->self->name = xstrdup(name);
598 mesh->self->devclass = devclass;
600 // Initialize configuration directory
601 if(!config_init(mesh)) {
605 if(!write_main_config_files(mesh)) {
609 // Write host config files
612 uint32_t len = packmsg_get_bin_raw(&in, &data);
615 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
619 packmsg_input_t in2 = {data, len};
620 uint32_t version = packmsg_get_uint32(&in2);
621 char *name = packmsg_get_str_dup(&in2);
623 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
625 packmsg_input_invalidate(&in);
629 if(!check_id(name)) {
634 if(!strcmp(name, mesh->name)) {
635 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
637 meshlink_errno = MESHLINK_EPEER;
641 node_t *n = new_node();
644 config_t config = {data, len};
646 if(!node_read_from_config(mesh, n, &config)) {
648 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
649 meshlink_errno = MESHLINK_EPEER;
655 if(!config_write(mesh, n->name, &config)) {
660 sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
662 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
667 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
669 meshlink_handle_t *mesh = handle;
670 const char *ptr = data;
673 int result = send(mesh->sock, ptr, len, 0);
675 if(result == -1 && errno == EINTR) {
677 } else if(result <= 0) {
688 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
689 meshlink_handle_t *mesh = handle;
692 case SPTPS_HANDSHAKE:
693 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
696 return finalize_join(mesh, msg, len);
699 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
700 shutdown(mesh->sock, SHUT_RDWR);
701 mesh->success = true;
711 static bool recvline(meshlink_handle_t *mesh, size_t len) {
712 char *newline = NULL;
718 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
719 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
721 if(result == -1 && errno == EINTR) {
723 } else if(result <= 0) {
727 mesh->blen += result;
730 if((size_t)(newline - mesh->buffer) >= len) {
734 len = newline - mesh->buffer;
736 memcpy(mesh->line, mesh->buffer, len);
738 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
739 mesh->blen -= len + 1;
743 static bool sendline(int fd, char *format, ...) {
744 static char buffer[4096];
749 va_start(ap, format);
750 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
753 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
761 int result = send(fd, p, blen, MSG_NOSIGNAL);
763 if(result == -1 && errno == EINTR) {
765 } else if(result <= 0) {
776 static const char *errstr[] = {
777 [MESHLINK_OK] = "No error",
778 [MESHLINK_EINVAL] = "Invalid argument",
779 [MESHLINK_ENOMEM] = "Out of memory",
780 [MESHLINK_ENOENT] = "No such node",
781 [MESHLINK_EEXIST] = "Node already exists",
782 [MESHLINK_EINTERNAL] = "Internal error",
783 [MESHLINK_ERESOLV] = "Could not resolve hostname",
784 [MESHLINK_ESTORAGE] = "Storage error",
785 [MESHLINK_ENETWORK] = "Network error",
786 [MESHLINK_EPEER] = "Error communicating with peer",
787 [MESHLINK_ENOTSUP] = "Operation not supported",
788 [MESHLINK_EBUSY] = "MeshLink instance already in use",
791 const char *meshlink_strerror(meshlink_errno_t err) {
792 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
793 return "Invalid error code";
799 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
800 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
802 mesh->private_key = ecdsa_generate();
803 mesh->invitation_key = ecdsa_generate();
805 if(!mesh->private_key || !mesh->invitation_key) {
806 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
807 meshlink_errno = MESHLINK_EINTERNAL;
811 logger(mesh, MESHLINK_DEBUG, "Done.\n");
816 static struct timeval idle(event_loop_t *loop, void *data) {
818 meshlink_handle_t *mesh = data;
819 struct timeval t, tmin = {3600, 0};
821 for splay_each(node_t, n, mesh->nodes) {
826 t = utcp_timeout(n->utcp);
828 if(timercmp(&t, &tmin, <)) {
836 // Get our local address(es) by simulating connecting to an Internet host.
837 static void add_local_addresses(meshlink_handle_t *mesh) {
838 struct sockaddr_storage sn;
839 socklen_t sl = sizeof(sn);
843 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl, mesh->netns)) {
844 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
845 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
852 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl, mesh->netns)) {
853 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
854 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
858 static bool meshlink_setup(meshlink_handle_t *mesh) {
859 if(!config_init(mesh)) {
860 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s: %s\n", mesh->confbase, strerror(errno));
861 meshlink_errno = MESHLINK_ESTORAGE;
865 if(!ecdsa_keygen(mesh)) {
866 meshlink_errno = MESHLINK_EINTERNAL;
870 if(check_port(mesh) == 0) {
871 meshlink_errno = MESHLINK_ENETWORK;
875 /* Create a node for ourself */
877 mesh->self = new_node();
878 mesh->self->name = xstrdup(mesh->name);
879 mesh->self->devclass = mesh->devclass;
880 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
882 if(!write_main_config_files(mesh)) {
886 if(!main_config_lock(mesh)) {
887 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
888 meshlink_errno = MESHLINK_ESTORAGE;
895 static bool meshlink_read_config(meshlink_handle_t *mesh) {
896 // Open the configuration file and lock it
897 if(!main_config_lock(mesh)) {
898 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
899 meshlink_errno = MESHLINK_ESTORAGE;
905 if(!main_config_read(mesh, &config)) {
906 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
910 packmsg_input_t in = {config.buf, config.len};
911 const void *private_key;
912 const void *invitation_key;
914 uint32_t version = packmsg_get_uint32(&in);
915 char *name = packmsg_get_str_dup(&in);
916 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
917 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
918 uint16_t myport = packmsg_get_uint16(&in);
920 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
921 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
923 config_free(&config);
930 if(mesh->name && strcmp(mesh->name, name)) {
931 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
932 meshlink_errno = MESHLINK_ESTORAGE;
934 config_free(&config);
942 xasprintf(&mesh->myport, "%u", myport);
943 mesh->private_key = ecdsa_set_private_key(private_key);
944 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
945 config_free(&config);
947 /* Create a node for ourself and read our host configuration file */
949 mesh->self = new_node();
950 mesh->self->name = xstrdup(name);
951 mesh->self->devclass = mesh->devclass;
953 if(!node_read_public_key(mesh, mesh->self)) {
954 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
955 meshlink_errno = MESHLINK_ESTORAGE;
956 free_node(mesh->self);
965 static void *setup_network_in_netns_thread(void *arg) {
966 meshlink_handle_t *mesh = arg;
968 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
972 bool success = setup_network(mesh);
973 add_local_addresses(mesh);
974 return success ? arg : NULL;
978 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
979 if(!confbase || !*confbase) {
980 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
981 meshlink_errno = MESHLINK_EINVAL;
985 if(!appname || !*appname) {
986 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
987 meshlink_errno = MESHLINK_EINVAL;
991 if(strchr(appname, ' ')) {
992 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
993 meshlink_errno = MESHLINK_EINVAL;
997 if(!name || !*name) {
998 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1000 } else { //check name only if there is a name != NULL
1001 if(!check_id(name)) {
1002 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1003 meshlink_errno = MESHLINK_EINVAL;
1008 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1009 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1010 meshlink_errno = MESHLINK_EINVAL;
1014 meshlink_open_params_t *params = xzalloc(sizeof * params);
1016 params->confbase = xstrdup(confbase);
1017 params->name = xstrdup(name);
1018 params->appname = xstrdup(appname);
1019 params->devclass = devclass;
1025 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1027 meshlink_errno = MESHLINK_EINVAL;
1031 params->netns = netns;
1036 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1038 meshlink_errno = MESHLINK_EINVAL;
1042 if((!key && keylen) || (key && !keylen)) {
1043 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1044 meshlink_errno = MESHLINK_EINVAL;
1049 params->keylen = keylen;
1054 void meshlink_open_params_free(meshlink_open_params_t *params) {
1056 meshlink_errno = MESHLINK_EINVAL;
1060 free(params->confbase);
1062 free(params->appname);
1067 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1068 if(!confbase || !*confbase) {
1069 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1070 meshlink_errno = MESHLINK_EINVAL;
1074 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1075 meshlink_open_params_t params;
1076 memset(¶ms, 0, sizeof(params));
1078 params.confbase = (char *)confbase;
1079 params.name = (char *)name;
1080 params.appname = (char *)appname;
1081 params.devclass = devclass;
1084 return meshlink_open_ex(¶ms);
1087 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) {
1088 if(!confbase || !*confbase) {
1089 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1090 meshlink_errno = MESHLINK_EINVAL;
1094 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1095 meshlink_open_params_t params = {NULL};
1097 params.confbase = (char *)confbase;
1098 params.name = (char *)name;
1099 params.appname = (char *)appname;
1100 params.devclass = devclass;
1103 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1107 return meshlink_open_ex(¶ms);
1110 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1111 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1112 meshlink_open_params_t params = {NULL};
1114 params.name = (char *)name;
1115 params.appname = (char *)appname;
1116 params.devclass = devclass;
1119 return meshlink_open_ex(¶ms);
1122 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1123 // Validate arguments provided by the application
1124 bool usingname = false;
1126 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1128 if(!params->appname || !*params->appname) {
1129 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1130 meshlink_errno = MESHLINK_EINVAL;
1134 if(strchr(params->appname, ' ')) {
1135 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1136 meshlink_errno = MESHLINK_EINVAL;
1140 if(!params->name || !*params->name) {
1141 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1143 } else { //check name only if there is a name != NULL
1145 if(!check_id(params->name)) {
1146 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1147 meshlink_errno = MESHLINK_EINVAL;
1154 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1155 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1156 meshlink_errno = MESHLINK_EINVAL;
1160 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1161 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1162 meshlink_errno = MESHLINK_EINVAL;
1166 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1168 if(params->confbase) {
1169 mesh->confbase = xstrdup(params->confbase);
1172 mesh->appname = xstrdup(params->appname);
1173 mesh->devclass = params->devclass;
1174 mesh->discovery = true;
1175 mesh->invitation_timeout = 604800; // 1 week
1176 mesh->netns = params->netns;
1177 mesh->submeshes = NULL;
1180 mesh->name = xstrdup(params->name);
1185 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1187 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1188 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1189 meshlink_close(mesh);
1190 meshlink_errno = MESHLINK_EINTERNAL;
1196 pthread_mutexattr_t attr;
1197 pthread_mutexattr_init(&attr);
1198 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1199 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1201 mesh->threadstarted = false;
1202 event_loop_init(&mesh->loop);
1203 mesh->loop.data = mesh;
1205 meshlink_queue_init(&mesh->outpacketqueue);
1207 // If no configuration exists yet, create it.
1209 if(!main_config_exists(mesh)) {
1210 if(!meshlink_setup(mesh)) {
1211 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1212 meshlink_close(mesh);
1216 if(!meshlink_read_config(mesh)) {
1217 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1218 meshlink_close(mesh);
1224 struct WSAData wsa_state;
1225 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1228 // Setup up everything
1229 // TODO: we should not open listening sockets yet
1231 bool success = false;
1233 if(mesh->netns != -1) {
1237 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1238 void *retval = NULL;
1239 success = pthread_join(thr, &retval) == 0 && retval;
1243 meshlink_errno = MESHLINK_EINTERNAL;
1246 #endif // HAVE_SETNS
1248 success = setup_network(mesh);
1249 add_local_addresses(mesh);
1253 meshlink_close(mesh);
1254 meshlink_errno = MESHLINK_ENETWORK;
1258 add_local_addresses(mesh);
1259 node_write_config(mesh, mesh->self);
1261 idle_set(&mesh->loop, idle, mesh);
1263 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1267 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1268 meshlink_submesh_t *s = NULL;
1271 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1272 meshlink_errno = MESHLINK_EINVAL;
1276 if(!submesh || !*submesh) {
1277 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1278 meshlink_errno = MESHLINK_EINVAL;
1283 pthread_mutex_lock(&(mesh->mesh_mutex));
1285 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1287 pthread_mutex_unlock(&(mesh->mesh_mutex));
1292 static void *meshlink_main_loop(void *arg) {
1293 meshlink_handle_t *mesh = arg;
1295 if(mesh->netns != -1) {
1298 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1304 #endif // HAVE_SETNS
1307 pthread_mutex_lock(&(mesh->mesh_mutex));
1309 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1311 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1313 pthread_mutex_unlock(&(mesh->mesh_mutex));
1317 bool meshlink_start(meshlink_handle_t *mesh) {
1319 assert(mesh->private_key);
1322 meshlink_errno = MESHLINK_EINVAL;
1326 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1328 pthread_mutex_lock(&(mesh->mesh_mutex));
1330 if(mesh->threadstarted) {
1331 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1332 pthread_mutex_unlock(&(mesh->mesh_mutex));
1336 if(mesh->listen_socket[0].tcp.fd < 0) {
1337 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1338 meshlink_errno = MESHLINK_ENETWORK;
1342 mesh->thedatalen = 0;
1344 // TODO: open listening sockets first
1346 //Check that a valid name is set
1348 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1349 meshlink_errno = MESHLINK_EINVAL;
1350 pthread_mutex_unlock(&(mesh->mesh_mutex));
1354 init_outgoings(mesh);
1356 // Start the main thread
1358 event_loop_start(&mesh->loop);
1360 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1361 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1362 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1363 meshlink_errno = MESHLINK_EINTERNAL;
1364 event_loop_stop(&mesh->loop);
1365 pthread_mutex_unlock(&(mesh->mesh_mutex));
1369 mesh->threadstarted = true;
1373 if(mesh->discovery) {
1374 discovery_start(mesh);
1379 assert(mesh->self->ecdsa);
1380 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1383 pthread_mutex_unlock(&(mesh->mesh_mutex));
1387 void meshlink_stop(meshlink_handle_t *mesh) {
1389 meshlink_errno = MESHLINK_EINVAL;
1393 pthread_mutex_lock(&(mesh->mesh_mutex));
1394 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1399 if(mesh->discovery) {
1400 discovery_stop(mesh);
1405 // Shut down the main thread
1406 event_loop_stop(&mesh->loop);
1408 // Send ourselves a UDP packet to kick the event loop
1409 for(int i = 0; i < mesh->listen_sockets; i++) {
1411 socklen_t salen = sizeof(sa.sa);
1413 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1414 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1418 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1419 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1423 if(mesh->threadstarted) {
1424 // Wait for the main thread to finish
1425 pthread_mutex_unlock(&(mesh->mesh_mutex));
1426 pthread_join(mesh->thread, NULL);
1427 pthread_mutex_lock(&(mesh->mesh_mutex));
1429 mesh->threadstarted = false;
1432 // Close all metaconnections
1433 if(mesh->connections) {
1434 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1436 connection_t *c = node->data;
1438 terminate_connection(mesh, c, false);
1442 exit_outgoings(mesh);
1444 // Write out any changed node config files
1446 for splay_each(node_t, n, mesh->nodes) {
1447 if(n->status.dirty) {
1448 node_write_config(mesh, n);
1449 n->status.dirty = false;
1454 pthread_mutex_unlock(&(mesh->mesh_mutex));
1457 void meshlink_close(meshlink_handle_t *mesh) {
1459 meshlink_errno = MESHLINK_EINVAL;
1463 // stop can be called even if mesh has not been started
1464 meshlink_stop(mesh);
1466 // lock is not released after this
1467 pthread_mutex_lock(&(mesh->mesh_mutex));
1469 // Close and free all resources used.
1471 close_network_connections(mesh);
1473 logger(mesh, MESHLINK_INFO, "Terminating");
1475 event_loop_exit(&mesh->loop);
1479 if(mesh->confbase) {
1485 ecdsa_free(mesh->invitation_key);
1487 if(mesh->netns != -1) {
1492 free(mesh->appname);
1493 free(mesh->confbase);
1494 free(mesh->config_key);
1495 ecdsa_free(mesh->private_key);
1496 pthread_mutex_destroy(&(mesh->mesh_mutex));
1498 main_config_unlock(mesh);
1500 memset(mesh, 0, sizeof(*mesh));
1505 bool meshlink_destroy(const char *confbase) {
1507 meshlink_errno = MESHLINK_EINVAL;
1511 return config_destroy(confbase);
1514 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1516 meshlink_errno = MESHLINK_EINVAL;
1520 pthread_mutex_lock(&(mesh->mesh_mutex));
1521 mesh->receive_cb = cb;
1522 pthread_mutex_unlock(&(mesh->mesh_mutex));
1525 void meshlink_set_connection_try_cb(meshlink_handle_t *mesh, meshlink_connection_try_cb_t cb) {
1527 meshlink_errno = MESHLINK_EINVAL;
1531 pthread_mutex_lock(&(mesh->mesh_mutex));
1532 mesh->connection_try_cb = cb;
1533 pthread_mutex_unlock(&(mesh->mesh_mutex));
1536 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1538 meshlink_errno = MESHLINK_EINVAL;
1542 pthread_mutex_lock(&(mesh->mesh_mutex));
1543 mesh->node_status_cb = cb;
1544 pthread_mutex_unlock(&(mesh->mesh_mutex));
1547 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1549 meshlink_errno = MESHLINK_EINVAL;
1553 pthread_mutex_lock(&(mesh->mesh_mutex));
1554 mesh->node_duplicate_cb = cb;
1555 pthread_mutex_unlock(&(mesh->mesh_mutex));
1558 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1560 pthread_mutex_lock(&(mesh->mesh_mutex));
1562 mesh->log_level = cb ? level : 0;
1563 pthread_mutex_unlock(&(mesh->mesh_mutex));
1566 global_log_level = cb ? level : 0;
1570 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1571 meshlink_packethdr_t *hdr;
1573 // Validate arguments
1574 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1575 meshlink_errno = MESHLINK_EINVAL;
1584 meshlink_errno = MESHLINK_EINVAL;
1588 node_t *n = (node_t *)destination;
1590 if(n->status.blacklisted) {
1591 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1595 // Prepare the packet
1596 vpn_packet_t *packet = malloc(sizeof(*packet));
1599 meshlink_errno = MESHLINK_ENOMEM;
1603 packet->probe = false;
1604 packet->tcp = false;
1605 packet->len = len + sizeof(*hdr);
1607 hdr = (meshlink_packethdr_t *)packet->data;
1608 memset(hdr, 0, sizeof(*hdr));
1609 // leave the last byte as 0 to make sure strings are always
1610 // null-terminated if they are longer than the buffer
1611 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1612 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1614 memcpy(packet->data + sizeof(*hdr), data, len);
1617 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1619 meshlink_errno = MESHLINK_ENOMEM;
1623 // Notify event loop
1624 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1629 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1631 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1637 mesh->self->in_packets++;
1638 mesh->self->in_bytes += packet->len;
1639 route(mesh, mesh->self, packet);
1642 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1643 if(!mesh || !destination) {
1644 meshlink_errno = MESHLINK_EINVAL;
1648 pthread_mutex_lock(&(mesh->mesh_mutex));
1650 node_t *n = (node_t *)destination;
1652 if(!n->status.reachable) {
1653 pthread_mutex_unlock(&(mesh->mesh_mutex));
1656 } else if(n->mtuprobes > 30 && n->minmtu) {
1657 pthread_mutex_unlock(&(mesh->mesh_mutex));
1660 pthread_mutex_unlock(&(mesh->mesh_mutex));
1665 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1666 if(!mesh || !node) {
1667 meshlink_errno = MESHLINK_EINVAL;
1671 pthread_mutex_lock(&(mesh->mesh_mutex));
1673 node_t *n = (node_t *)node;
1675 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1676 meshlink_errno = MESHLINK_EINTERNAL;
1677 pthread_mutex_unlock(&(mesh->mesh_mutex));
1681 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1684 meshlink_errno = MESHLINK_EINTERNAL;
1687 pthread_mutex_unlock(&(mesh->mesh_mutex));
1691 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1693 meshlink_errno = MESHLINK_EINVAL;
1697 return (meshlink_node_t *)mesh->self;
1700 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1701 if(!mesh || !name) {
1702 meshlink_errno = MESHLINK_EINVAL;
1706 meshlink_node_t *node = NULL;
1708 pthread_mutex_lock(&(mesh->mesh_mutex));
1709 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1710 pthread_mutex_unlock(&(mesh->mesh_mutex));
1714 meshlink_submesh_t *meshlink_get_submesh(meshlink_handle_t *mesh, const char *name) {
1715 if(!mesh || !name) {
1716 meshlink_errno = MESHLINK_EINVAL;
1720 meshlink_submesh_t *submesh = NULL;
1722 pthread_mutex_lock(&(mesh->mesh_mutex));
1723 submesh = (meshlink_submesh_t *)lookup_submesh(mesh, name);
1724 pthread_mutex_unlock(&(mesh->mesh_mutex));
1728 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1729 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1730 meshlink_errno = MESHLINK_EINVAL;
1734 meshlink_node_t **result;
1737 pthread_mutex_lock(&(mesh->mesh_mutex));
1739 *nmemb = mesh->nodes->count;
1740 result = realloc(nodes, *nmemb * sizeof(*nodes));
1743 meshlink_node_t **p = result;
1745 for splay_each(node_t, n, mesh->nodes) {
1746 *p++ = (meshlink_node_t *)n;
1751 meshlink_errno = MESHLINK_ENOMEM;
1754 pthread_mutex_unlock(&(mesh->mesh_mutex));
1759 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) {
1760 meshlink_node_t **result;
1762 pthread_mutex_lock(&(mesh->mesh_mutex));
1766 for splay_each(node_t, n, mesh->nodes) {
1767 if(true == search_node(n, condition)) {
1768 *nmemb = *nmemb + 1;
1774 pthread_mutex_unlock(&(mesh->mesh_mutex));
1778 result = realloc(nodes, *nmemb * sizeof(*nodes));
1781 meshlink_node_t **p = result;
1783 for splay_each(node_t, n, mesh->nodes) {
1784 if(true == search_node(n, condition)) {
1785 *p++ = (meshlink_node_t *)n;
1791 meshlink_errno = MESHLINK_ENOMEM;
1794 pthread_mutex_unlock(&(mesh->mesh_mutex));
1799 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1800 dev_class_t *devclass = (dev_class_t *)condition;
1802 if(*devclass == node->devclass) {
1809 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1810 if(condition == node->submesh) {
1817 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) {
1818 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1819 meshlink_errno = MESHLINK_EINVAL;
1823 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1826 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1827 if(!mesh || !submesh || !nmemb) {
1828 meshlink_errno = MESHLINK_EINVAL;
1832 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1835 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1836 if(!mesh || !node) {
1837 meshlink_errno = MESHLINK_EINVAL;
1841 dev_class_t devclass;
1843 pthread_mutex_lock(&(mesh->mesh_mutex));
1845 devclass = ((node_t *)node)->devclass;
1847 pthread_mutex_unlock(&(mesh->mesh_mutex));
1852 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1853 if(!mesh || !node) {
1854 meshlink_errno = MESHLINK_EINVAL;
1858 node_t *n = (node_t *)node;
1860 meshlink_submesh_t *s;
1862 s = (meshlink_submesh_t *)n->submesh;
1867 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1868 if(!mesh || !data || !len || !signature || !siglen) {
1869 meshlink_errno = MESHLINK_EINVAL;
1873 if(*siglen < MESHLINK_SIGLEN) {
1874 meshlink_errno = MESHLINK_EINVAL;
1878 pthread_mutex_lock(&(mesh->mesh_mutex));
1880 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1881 meshlink_errno = MESHLINK_EINTERNAL;
1882 pthread_mutex_unlock(&(mesh->mesh_mutex));
1886 *siglen = MESHLINK_SIGLEN;
1887 pthread_mutex_unlock(&(mesh->mesh_mutex));
1891 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1892 if(!mesh || !data || !len || !signature) {
1893 meshlink_errno = MESHLINK_EINVAL;
1897 if(siglen != MESHLINK_SIGLEN) {
1898 meshlink_errno = MESHLINK_EINVAL;
1902 pthread_mutex_lock(&(mesh->mesh_mutex));
1906 struct node_t *n = (struct node_t *)source;
1908 if(!node_read_public_key(mesh, n)) {
1909 meshlink_errno = MESHLINK_EINTERNAL;
1912 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1915 pthread_mutex_unlock(&(mesh->mesh_mutex));
1919 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1920 pthread_mutex_lock(&(mesh->mesh_mutex));
1922 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
1925 // TODO: Update invitation key if necessary?
1928 pthread_mutex_unlock(&(mesh->mesh_mutex));
1930 return mesh->invitation_key;
1933 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1934 if(!mesh || !node || !address) {
1935 meshlink_errno = MESHLINK_EINVAL;
1939 if(!is_valid_hostname(address)) {
1940 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1941 meshlink_errno = MESHLINK_EINVAL;
1945 if(port && !is_valid_port(port)) {
1946 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1947 meshlink_errno = MESHLINK_EINVAL;
1951 char *canonical_address;
1954 xasprintf(&canonical_address, "%s %s", address, port);
1956 canonical_address = xstrdup(address);
1959 pthread_mutex_lock(&(mesh->mesh_mutex));
1961 node_t *n = (node_t *)node;
1962 free(n->canonical_address);
1963 n->canonical_address = canonical_address;
1964 node_write_config(mesh, n);
1966 pthread_mutex_unlock(&(mesh->mesh_mutex));
1971 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1972 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1975 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1977 meshlink_errno = MESHLINK_EINVAL;
1981 char *address = meshlink_get_external_address(mesh);
1987 bool rval = meshlink_add_address(mesh, address);
1993 int meshlink_get_port(meshlink_handle_t *mesh) {
1995 meshlink_errno = MESHLINK_EINVAL;
2000 meshlink_errno = MESHLINK_EINTERNAL;
2004 return atoi(mesh->myport);
2007 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
2008 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
2009 meshlink_errno = MESHLINK_EINVAL;
2013 if(mesh->myport && port == atoi(mesh->myport)) {
2017 if(!try_bind(port)) {
2018 meshlink_errno = MESHLINK_ENETWORK;
2022 devtool_trybind_probe();
2026 pthread_mutex_lock(&(mesh->mesh_mutex));
2028 if(mesh->threadstarted) {
2029 meshlink_errno = MESHLINK_EINVAL;
2034 xasprintf(&mesh->myport, "%d", port);
2036 /* Write meshlink.conf with the updated port number */
2037 write_main_config_files(mesh);
2039 /* Close down the network. This also deletes mesh->self. */
2040 close_network_connections(mesh);
2042 /* Recreate mesh->self. */
2043 mesh->self = new_node();
2044 mesh->self->name = xstrdup(mesh->name);
2045 mesh->self->devclass = mesh->devclass;
2047 if(!node_read_public_key(mesh, mesh->self)) {
2048 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
2049 meshlink_errno = MESHLINK_ESTORAGE;
2050 free_node(mesh->self);
2052 } else if(!setup_network(mesh)) {
2053 meshlink_errno = MESHLINK_ENETWORK;
2059 pthread_mutex_unlock(&(mesh->mesh_mutex));
2061 return rval && meshlink_get_port(mesh) == port;
2064 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2065 mesh->invitation_timeout = timeout;
2068 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2069 meshlink_submesh_t *s = NULL;
2072 meshlink_errno = MESHLINK_EINVAL;
2077 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2080 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2081 meshlink_errno = MESHLINK_EINVAL;
2085 s = (meshlink_submesh_t *)mesh->self->submesh;
2088 pthread_mutex_lock(&(mesh->mesh_mutex));
2090 // Check validity of the new node's name
2091 if(!check_id(name)) {
2092 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2093 meshlink_errno = MESHLINK_EINVAL;
2094 pthread_mutex_unlock(&(mesh->mesh_mutex));
2098 // Ensure no host configuration file with that name exists
2099 if(config_exists(mesh, name)) {
2100 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2101 meshlink_errno = MESHLINK_EEXIST;
2102 pthread_mutex_unlock(&(mesh->mesh_mutex));
2106 // Ensure no other nodes know about this name
2107 if(meshlink_get_node(mesh, name)) {
2108 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2109 meshlink_errno = MESHLINK_EEXIST;
2110 pthread_mutex_unlock(&(mesh->mesh_mutex));
2114 // Get the local address
2115 char *address = get_my_hostname(mesh, flags);
2118 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2119 meshlink_errno = MESHLINK_ERESOLV;
2120 pthread_mutex_unlock(&(mesh->mesh_mutex));
2124 if(!refresh_invitation_key(mesh)) {
2125 meshlink_errno = MESHLINK_EINTERNAL;
2126 pthread_mutex_unlock(&(mesh->mesh_mutex));
2132 // Create a hash of the key.
2133 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2134 sha512(fingerprint, strlen(fingerprint), hash);
2135 b64encode_urlsafe(hash, hash, 18);
2137 // Create a random cookie for this invitation.
2139 randomize(cookie, 18);
2141 // Create a filename that doesn't reveal the cookie itself
2142 char buf[18 + strlen(fingerprint)];
2143 char cookiehash[64];
2144 memcpy(buf, cookie, 18);
2145 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2146 sha512(buf, sizeof(buf), cookiehash);
2147 b64encode_urlsafe(cookiehash, cookiehash, 18);
2149 b64encode_urlsafe(cookie, cookie, 18);
2153 /* Construct the invitation file */
2154 uint8_t outbuf[4096];
2155 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2157 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2158 packmsg_add_str(&inv, name);
2159 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2160 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2162 /* TODO: Add several host config files to bootstrap connections.
2163 * Note: make sure we only add config files of nodes that are in the core mesh or the same submesh,
2164 * and are not blacklisted.
2166 config_t configs[5] = {NULL};
2169 if(config_read(mesh, mesh->self->name, &configs[count])) {
2173 /* Append host config files to the invitation file */
2174 packmsg_add_array(&inv, count);
2176 for(int i = 0; i < count; i++) {
2177 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2178 config_free(&configs[i]);
2181 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2183 if(!invitation_write(mesh, cookiehash, &config)) {
2184 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2185 meshlink_errno = MESHLINK_ESTORAGE;
2186 pthread_mutex_unlock(&(mesh->mesh_mutex));
2190 // Create an URL from the local address, key hash and cookie
2192 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2195 pthread_mutex_unlock(&(mesh->mesh_mutex));
2199 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2200 return meshlink_invite_ex(mesh, submesh, name, 0);
2203 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2204 if(!mesh || !invitation) {
2205 meshlink_errno = MESHLINK_EINVAL;
2209 pthread_mutex_lock(&(mesh->mesh_mutex));
2211 //Before doing meshlink_join make sure we are not connected to another mesh
2212 if(mesh->threadstarted) {
2213 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2214 meshlink_errno = MESHLINK_EINVAL;
2215 pthread_mutex_unlock(&(mesh->mesh_mutex));
2219 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2220 char copy[strlen(invitation) + 1];
2221 strcpy(copy, invitation);
2223 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2225 char *slash = strchr(copy, '/');
2233 if(strlen(slash) != 48) {
2237 char *address = copy;
2240 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2244 // Generate a throw-away key for the invitation.
2245 ecdsa_t *key = ecdsa_generate();
2248 meshlink_errno = MESHLINK_EINTERNAL;
2249 pthread_mutex_unlock(&(mesh->mesh_mutex));
2253 char *b64key = ecdsa_get_base64_public_key(key);
2257 while(address && *address) {
2258 // We allow commas in the address part to support multiple addresses in one invitation URL.
2259 comma = strchr(address, ',');
2265 // Split of the port
2266 port = strrchr(address, ':');
2274 // IPv6 address are enclosed in brackets, per RFC 3986
2275 if(*address == '[') {
2277 char *bracket = strchr(address, ']');
2290 // Connect to the meshlink daemon mentioned in the URL.
2291 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2294 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2295 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2297 if(mesh->sock == -1) {
2298 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2299 meshlink_errno = MESHLINK_ENETWORK;
2303 set_timeout(mesh->sock, 5000);
2305 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2306 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2307 meshlink_errno = MESHLINK_ENETWORK;
2308 closesocket(mesh->sock);
2316 meshlink_errno = MESHLINK_ERESOLV;
2319 if(mesh->sock != -1 || !comma) {
2326 if(mesh->sock == -1) {
2327 pthread_mutex_unlock(&mesh->mesh_mutex);
2331 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2333 // Tell him we have an invitation, and give him our throw-away key.
2337 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, PROT_MINOR, mesh->appname)) {
2338 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2339 closesocket(mesh->sock);
2340 meshlink_errno = MESHLINK_ENETWORK;
2341 pthread_mutex_unlock(&(mesh->mesh_mutex));
2347 char hisname[4096] = "";
2348 int code, hismajor, hisminor = 0;
2350 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) {
2351 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2352 closesocket(mesh->sock);
2353 meshlink_errno = MESHLINK_ENETWORK;
2354 pthread_mutex_unlock(&(mesh->mesh_mutex));
2358 // Check if the hash of the key he gave us matches the hash in the URL.
2359 char *fingerprint = mesh->line + 2;
2362 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2363 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2364 meshlink_errno = MESHLINK_EINTERNAL;
2365 pthread_mutex_unlock(&(mesh->mesh_mutex));
2369 if(memcmp(hishash, mesh->hash, 18)) {
2370 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2371 meshlink_errno = MESHLINK_EPEER;
2372 pthread_mutex_unlock(&(mesh->mesh_mutex));
2377 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2380 meshlink_errno = MESHLINK_EINTERNAL;
2381 pthread_mutex_unlock(&(mesh->mesh_mutex));
2385 // Start an SPTPS session
2386 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2387 meshlink_errno = MESHLINK_EINTERNAL;
2388 pthread_mutex_unlock(&(mesh->mesh_mutex));
2392 // Feed rest of input buffer to SPTPS
2393 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2394 meshlink_errno = MESHLINK_EPEER;
2395 pthread_mutex_unlock(&(mesh->mesh_mutex));
2401 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2403 if(errno == EINTR) {
2407 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2408 meshlink_errno = MESHLINK_ENETWORK;
2409 pthread_mutex_unlock(&(mesh->mesh_mutex));
2413 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2414 meshlink_errno = MESHLINK_EPEER;
2415 pthread_mutex_unlock(&(mesh->mesh_mutex));
2420 sptps_stop(&mesh->sptps);
2423 closesocket(mesh->sock);
2425 if(!mesh->success) {
2426 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2427 meshlink_errno = MESHLINK_EPEER;
2428 pthread_mutex_unlock(&(mesh->mesh_mutex));
2432 pthread_mutex_unlock(&(mesh->mesh_mutex));
2436 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2437 meshlink_errno = MESHLINK_EINVAL;
2438 pthread_mutex_unlock(&(mesh->mesh_mutex));
2442 char *meshlink_export(meshlink_handle_t *mesh) {
2444 meshlink_errno = MESHLINK_EINVAL;
2448 // Create a config file on the fly.
2451 packmsg_output_t out = {buf, sizeof(buf)};
2452 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2453 packmsg_add_str(&out, mesh->name);
2454 packmsg_add_str(&out, CORE_MESH);
2456 pthread_mutex_lock(&(mesh->mesh_mutex));
2458 packmsg_add_int32(&out, mesh->self->devclass);
2459 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2460 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2461 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2465 for(uint32_t i = 0; i < 5; i++) {
2466 if(mesh->self->recent[i].sa.sa_family) {
2473 packmsg_add_array(&out, count);
2475 for(uint32_t i = 0; i < count; i++) {
2476 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2479 pthread_mutex_unlock(&(mesh->mesh_mutex));
2481 if(!packmsg_output_ok(&out)) {
2482 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2483 meshlink_errno = MESHLINK_EINTERNAL;
2487 // Prepare a base64-encoded packmsg array containing our config file
2489 uint32_t len = packmsg_output_size(&out, buf);
2490 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2491 uint8_t *buf2 = xmalloc(len2);
2492 packmsg_output_t out2 = {buf2, len2};
2493 packmsg_add_array(&out2, 1);
2494 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2496 if(!packmsg_output_ok(&out2)) {
2497 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2498 meshlink_errno = MESHLINK_EINTERNAL;
2503 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2505 return (char *)buf2;
2508 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2509 if(!mesh || !data) {
2510 meshlink_errno = MESHLINK_EINVAL;
2514 size_t datalen = strlen(data);
2515 uint8_t *buf = xmalloc(datalen);
2516 int buflen = b64decode(data, buf, datalen);
2519 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2520 meshlink_errno = MESHLINK_EPEER;
2524 packmsg_input_t in = {buf, buflen};
2525 uint32_t count = packmsg_get_array(&in);
2528 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2529 meshlink_errno = MESHLINK_EPEER;
2533 pthread_mutex_lock(&(mesh->mesh_mutex));
2537 uint32_t len = packmsg_get_bin_raw(&in, &data);
2543 packmsg_input_t in2 = {data, len};
2544 uint32_t version = packmsg_get_uint32(&in2);
2545 char *name = packmsg_get_str_dup(&in2);
2547 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2549 packmsg_input_invalidate(&in);
2553 if(!check_id(name)) {
2558 node_t *n = lookup_node(mesh, name);
2561 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2569 config_t config = {data, len};
2571 if(!node_read_from_config(mesh, n, &config)) {
2573 packmsg_input_invalidate(&in);
2577 config_write(mesh, n->name, &config);
2581 pthread_mutex_unlock(&(mesh->mesh_mutex));
2583 if(!packmsg_done(&in)) {
2584 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2585 meshlink_errno = MESHLINK_EPEER;
2592 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2593 if(!mesh || !node) {
2594 meshlink_errno = MESHLINK_EINVAL;
2598 pthread_mutex_lock(&(mesh->mesh_mutex));
2603 if(n == mesh->self) {
2604 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2605 meshlink_errno = MESHLINK_EINVAL;
2606 pthread_mutex_unlock(&(mesh->mesh_mutex));
2610 if(n->status.blacklisted) {
2611 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2612 pthread_mutex_unlock(&(mesh->mesh_mutex));
2616 n->status.blacklisted = true;
2617 node_write_config(mesh, n);
2618 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2620 //Immediately terminate any connections we have with the blacklisted node
2621 for list_each(connection_t, c, mesh->connections) {
2623 terminate_connection(mesh, c, c->status.active);
2627 utcp_abort_all_connections(n->utcp);
2633 n->status.udp_confirmed = false;
2635 if(n->status.reachable) {
2636 update_node_status(mesh, n);
2639 pthread_mutex_unlock(&(mesh->mesh_mutex));
2642 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2643 if(!mesh || !node) {
2644 meshlink_errno = MESHLINK_EINVAL;
2648 pthread_mutex_lock(&(mesh->mesh_mutex));
2650 node_t *n = (node_t *)node;
2652 if(!n->status.blacklisted) {
2653 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2654 meshlink_errno = MESHLINK_EINVAL;
2655 pthread_mutex_unlock(&(mesh->mesh_mutex));
2659 n->status.blacklisted = false;
2660 node_write_config(mesh, n);
2662 pthread_mutex_unlock(&(mesh->mesh_mutex));
2666 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2667 mesh->default_blacklist = blacklist;
2670 /* Hint that a hostname may be found at an address
2671 * See header file for detailed comment.
2673 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2674 if(!mesh || !node || !addr) {
2675 meshlink_errno = EINVAL;
2679 pthread_mutex_lock(&(mesh->mesh_mutex));
2681 node_t *n = (node_t *)node;
2682 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2683 memcpy(n->recent, addr, SALEN(*addr));
2684 node_write_config(mesh, n);
2686 pthread_mutex_unlock(&(mesh->mesh_mutex));
2687 // @TODO do we want to fire off a connection attempt right away?
2690 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2692 node_t *n = utcp->priv;
2693 meshlink_handle_t *mesh = n->mesh;
2694 return mesh->channel_accept_cb;
2697 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2698 meshlink_channel_t *channel = connection->priv;
2704 node_t *n = channel->node;
2705 meshlink_handle_t *mesh = n->mesh;
2707 if(n->status.destroyed) {
2708 meshlink_channel_close(mesh, channel);
2709 } else if(channel->receive_cb) {
2710 channel->receive_cb(mesh, channel, data, len);
2716 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2717 node_t *n = utcp_connection->utcp->priv;
2723 meshlink_handle_t *mesh = n->mesh;
2725 if(!mesh->channel_accept_cb) {
2729 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2731 channel->c = utcp_connection;
2733 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2734 utcp_accept(utcp_connection, channel_recv, channel);
2740 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2741 node_t *n = utcp->priv;
2743 if(n->status.destroyed) {
2747 meshlink_handle_t *mesh = n->mesh;
2748 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2751 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2752 if(!mesh || !channel) {
2753 meshlink_errno = MESHLINK_EINVAL;
2757 channel->receive_cb = cb;
2760 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2762 node_t *n = (node_t *)source;
2768 utcp_recv(n->utcp, data, len);
2771 static void channel_poll(struct utcp_connection *connection, size_t len) {
2772 meshlink_channel_t *channel = connection->priv;
2778 node_t *n = channel->node;
2779 meshlink_handle_t *mesh = n->mesh;
2781 if(channel->poll_cb) {
2782 channel->poll_cb(mesh, channel, len);
2786 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2788 channel->poll_cb = cb;
2789 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2792 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2794 meshlink_errno = MESHLINK_EINVAL;
2798 pthread_mutex_lock(&mesh->mesh_mutex);
2799 mesh->channel_accept_cb = cb;
2800 mesh->receive_cb = channel_receive;
2802 for splay_each(node_t, n, mesh->nodes) {
2803 if(!n->utcp && n != mesh->self) {
2804 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2808 pthread_mutex_unlock(&mesh->mesh_mutex);
2811 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) {
2813 abort(); // TODO: handle non-NULL data
2816 if(!mesh || !node) {
2817 meshlink_errno = MESHLINK_EINVAL;
2821 node_t *n = (node_t *)node;
2824 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2825 mesh->receive_cb = channel_receive;
2828 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2833 if(n->status.blacklisted) {
2834 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2838 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2840 channel->receive_cb = cb;
2841 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2844 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2852 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) {
2853 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2856 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2857 if(!mesh || !channel) {
2858 meshlink_errno = MESHLINK_EINVAL;
2862 utcp_shutdown(channel->c, direction);
2865 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2866 if(!mesh || !channel) {
2867 meshlink_errno = MESHLINK_EINVAL;
2871 utcp_close(channel->c);
2875 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2876 if(!mesh || !channel) {
2877 meshlink_errno = MESHLINK_EINVAL;
2886 meshlink_errno = MESHLINK_EINVAL;
2890 // TODO: more finegrained locking.
2891 // Ideally we want to put the data into the UTCP connection's send buffer.
2892 // Then, preferably only if there is room in the receiver window,
2893 // kick the meshlink thread to go send packets.
2895 pthread_mutex_lock(&mesh->mesh_mutex);
2896 ssize_t retval = utcp_send(channel->c, data, len);
2897 pthread_mutex_unlock(&mesh->mesh_mutex);
2900 meshlink_errno = MESHLINK_ENETWORK;
2906 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2907 if(!mesh || !channel) {
2908 meshlink_errno = MESHLINK_EINVAL;
2912 return channel->c->flags;
2915 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2916 if(!mesh || !channel) {
2917 meshlink_errno = MESHLINK_EINVAL;
2921 return utcp_get_sendq(channel->c);
2924 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2925 if(!mesh || !channel) {
2926 meshlink_errno = MESHLINK_EINVAL;
2930 return utcp_get_recvq(channel->c);
2933 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2934 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2935 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2938 if(mesh->node_status_cb) {
2939 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2943 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2944 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2948 n->status.duplicate = true;
2949 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2952 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2956 meshlink_errno = MESHLINK_EINVAL;
2960 pthread_mutex_lock(&mesh->mesh_mutex);
2962 if(mesh->discovery == enable) {
2966 if(mesh->threadstarted) {
2968 discovery_start(mesh);
2970 discovery_stop(mesh);
2974 mesh->discovery = enable;
2977 pthread_mutex_unlock(&mesh->mesh_mutex);
2981 meshlink_errno = MESHLINK_ENOTSUP;
2985 static void __attribute__((constructor)) meshlink_init(void) {
2988 randomize(&seed, sizeof(seed));
2992 static void __attribute__((destructor)) meshlink_exit(void) {
2996 /// Device class traits
2997 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2998 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2999 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
3000 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
3001 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN