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"
41 #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 {
128 static void *socket_in_netns_thread(void *arg) {
129 struct socket_in_netns_params *params = arg;
131 if(setns(params->netns, CLONE_NEWNET) == -1) {
132 meshlink_errno = MESHLINK_EINVAL;
134 params->fd = socket(params->domain, params->type, params->protocol);
140 static int socket_in_netns(int domain, int type, int protocol, int netns) {
142 return socket(domain, type, protocol);
145 struct socket_in_netns_params params = {domain, type, protocol, netns, -1};
149 if(pthread_create(&thr, NULL, socket_in_netns_thread, ¶ms) == 0) {
150 pthread_join(thr, NULL);
156 // Find out what local address a socket would use if we connect to the given address.
157 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
158 // of both endpoints, but this will actually not send any UDP packet.
159 static bool getlocaladdr(char *destaddr, struct sockaddr *sn, socklen_t *sl, int netns) {
160 struct addrinfo *rai = NULL;
161 const struct addrinfo hint = {
162 .ai_family = AF_UNSPEC,
163 .ai_socktype = SOCK_DGRAM,
164 .ai_protocol = IPPROTO_UDP,
167 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
171 int sock = socket_in_netns(rai->ai_family, rai->ai_socktype, rai->ai_protocol, netns);
178 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
186 if(getsockname(sock, sn, sl)) {
195 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen, int netns) {
196 struct sockaddr_storage sn;
197 socklen_t sl = sizeof(sn);
199 if(!getlocaladdr(destaddr, (struct sockaddr *)&sn, &sl, netns)) {
203 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
210 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
211 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
214 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
215 char *hostname = NULL;
217 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
218 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
219 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
222 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
223 if(family != AF_UNSPEC && aip->ai_family != family) {
227 int s = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
230 set_timeout(s, 5000);
232 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
239 send(s, request, sizeof(request) - 1, 0);
240 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
245 if(line[len - 1] == '\n') {
249 char *p = strrchr(line, '\n');
252 hostname = xstrdup(p + 1);
268 // Check that the hostname is reasonable
269 if(hostname && !is_valid_hostname(hostname)) {
275 meshlink_errno = MESHLINK_ERESOLV;
281 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
284 // Determine address of the local interface used for outgoing connections.
285 char localaddr[NI_MAXHOST];
286 bool success = false;
288 if(family == AF_INET) {
289 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr), mesh->netns);
290 } else if(family == AF_INET6) {
291 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr), mesh->netns);
295 meshlink_errno = MESHLINK_ENETWORK;
299 return xstrdup(localaddr);
302 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
303 for(int i = 0; i < n; i++) {
308 // Ignore duplicate hostnames
311 for(int j = 0; j < i; j++) {
316 if(strcmp(host[i], host[j])) {
320 if(strcmp(port[i], port[j])) {
338 // This gets the hostname part for use in invitation URLs
339 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
340 char *hostname[4] = {NULL};
341 char *port[4] = {NULL};
342 char *hostport = NULL;
344 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
345 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
348 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
349 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
352 // Add local addresses if requested
353 if(flags & MESHLINK_INVITE_LOCAL) {
354 if(flags & MESHLINK_INVITE_IPV4) {
355 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
358 if(flags & MESHLINK_INVITE_IPV6) {
359 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
363 // Add public/canonical addresses if requested
364 if(flags & MESHLINK_INVITE_PUBLIC) {
365 // Try the CanonicalAddress first
366 get_canonical_address(mesh->self, &hostname[2], &port[2]);
369 if(flags & MESHLINK_INVITE_IPV4) {
370 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
373 if(flags & MESHLINK_INVITE_IPV6) {
374 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
379 for(int i = 0; i < 4; i++) {
380 // Ensure we always have a port number
381 if(hostname[i] && !port[i]) {
382 port[i] = xstrdup(mesh->myport);
386 remove_duplicate_hostnames(hostname, port, 4);
388 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
389 for(int i = 0; i < 4; i++) {
394 // Convert what we have to a sockaddr
395 struct addrinfo *ai_in, *ai_out;
396 struct addrinfo hint = {
397 .ai_family = AF_UNSPEC,
398 .ai_flags = AI_NUMERICSERV,
399 .ai_socktype = SOCK_STREAM,
401 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
407 // Convert it to a hostname
408 char resolved_host[NI_MAXHOST];
409 char resolved_port[NI_MAXSERV];
410 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
417 // Convert the hostname back to a sockaddr
418 hint.ai_family = ai_in->ai_family;
419 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
426 // Check if it's still the same sockaddr
427 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
429 freeaddrinfo(ai_out);
433 // Yes: replace the hostname with the resolved one
435 hostname[i] = xstrdup(resolved_host);
438 freeaddrinfo(ai_out);
442 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
443 remove_duplicate_hostnames(hostname, port, 4);
445 // Concatenate all unique address to the hostport string
446 for(int i = 0; i < 4; i++) {
451 // Ensure we have the same addresses in our own host config file.
453 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
455 //config_add_string(&mesh->config, "Address", tmphostport);
458 // Append the address to the hostport string
460 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
462 hostport = newhostport;
471 static bool try_bind(int port) {
472 struct addrinfo *ai = NULL;
473 struct addrinfo hint = {
474 .ai_flags = AI_PASSIVE,
475 .ai_family = AF_UNSPEC,
476 .ai_socktype = SOCK_STREAM,
477 .ai_protocol = IPPROTO_TCP,
481 snprintf(portstr, sizeof(portstr), "%d", port);
483 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
488 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
489 int fd = socket(aip->ai_family, SOCK_STREAM, IPPROTO_TCP);
496 int result = bind(fd, aip->ai_addr, aip->ai_addrlen);
509 int check_port(meshlink_handle_t *mesh) {
510 for(int i = 0; i < 1000; i++) {
511 int port = 0x1000 + (rand() & 0x7fff);
515 xasprintf(&mesh->myport, "%d", port);
520 meshlink_errno = MESHLINK_ENETWORK;
521 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
525 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
526 packmsg_input_t in = {buf, len};
527 uint32_t version = packmsg_get_uint32(&in);
529 if(version != MESHLINK_INVITATION_VERSION) {
530 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
534 char *name = packmsg_get_str_dup(&in);
535 packmsg_skip_element(&in); /* submesh */
536 int32_t devclass = packmsg_get_int32(&in);
537 uint32_t count = packmsg_get_array(&in);
540 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
544 if(!check_id(name)) {
545 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
550 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
554 // Initialize configuration directory
555 if(!config_init(mesh)) {
559 // Write main config file
560 uint8_t outbuf[4096];
561 packmsg_output_t out = {outbuf, sizeof(outbuf)};
562 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
563 packmsg_add_str(&out, name);
564 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
565 packmsg_add_uint16(&out, atoi(mesh->myport));
567 config_t config = {outbuf, packmsg_output_size(&out, outbuf)};
569 if(!main_config_write(mesh, &config)) {
573 // Write our own host config file
575 out.len = sizeof(outbuf);
576 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
577 packmsg_add_str(&out, name);
578 packmsg_add_str(&out, CORE_MESH);
579 packmsg_add_int32(&out, devclass);
580 packmsg_add_bool(&out, false);
581 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
582 packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
583 packmsg_add_array(&out, 0);
585 config.len = packmsg_output_size(&out, outbuf);
587 if(!config_write(mesh, name, &config)) {
591 // Write host config files
594 uint32_t len = packmsg_get_bin_raw(&in, &data);
597 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
601 config_t config = {data, len};
602 node_t *n = new_node();
604 if(!node_read_from_config(mesh, n, &config)) {
606 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
607 meshlink_errno = MESHLINK_EPEER;
611 if(!strcmp(n->name, name)) {
612 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
614 meshlink_errno = MESHLINK_EPEER;
620 if(!config_write(mesh, n->name, &config)) {
625 sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
628 free(mesh->self->name);
629 mesh->name = xstrdup(name);
630 mesh->self->name = xstrdup(name);
632 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
637 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
639 meshlink_handle_t *mesh = handle;
640 const char *ptr = data;
643 int result = send(mesh->sock, ptr, len, 0);
645 if(result == -1 && errno == EINTR) {
647 } else if(result <= 0) {
658 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
659 meshlink_handle_t *mesh = handle;
662 case SPTPS_HANDSHAKE:
663 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
666 return finalize_join(mesh, msg, len);
669 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
670 shutdown(mesh->sock, SHUT_RDWR);
671 mesh->success = true;
681 static bool recvline(meshlink_handle_t *mesh, size_t len) {
682 char *newline = NULL;
688 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
689 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
691 if(result == -1 && errno == EINTR) {
693 } else if(result <= 0) {
697 mesh->blen += result;
700 if((size_t)(newline - mesh->buffer) >= len) {
704 len = newline - mesh->buffer;
706 memcpy(mesh->line, mesh->buffer, len);
708 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
709 mesh->blen -= len + 1;
713 static bool sendline(int fd, char *format, ...) {
714 static char buffer[4096];
719 va_start(ap, format);
720 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
723 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
731 int result = send(fd, p, blen, MSG_NOSIGNAL);
733 if(result == -1 && errno == EINTR) {
735 } else if(result <= 0) {
746 static const char *errstr[] = {
747 [MESHLINK_OK] = "No error",
748 [MESHLINK_EINVAL] = "Invalid argument",
749 [MESHLINK_ENOMEM] = "Out of memory",
750 [MESHLINK_ENOENT] = "No such node",
751 [MESHLINK_EEXIST] = "Node already exists",
752 [MESHLINK_EINTERNAL] = "Internal error",
753 [MESHLINK_ERESOLV] = "Could not resolve hostname",
754 [MESHLINK_ESTORAGE] = "Storage error",
755 [MESHLINK_ENETWORK] = "Network error",
756 [MESHLINK_EPEER] = "Error communicating with peer",
757 [MESHLINK_ENOTSUP] = "Operation not supported",
758 [MESHLINK_EBUSY] = "MeshLink instance already in use",
761 const char *meshlink_strerror(meshlink_errno_t err) {
762 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
763 return "Invalid error code";
769 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
770 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
772 mesh->private_key = ecdsa_generate();
773 mesh->invitation_key = ecdsa_generate();
775 if(!mesh->private_key || !mesh->invitation_key) {
776 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
777 meshlink_errno = MESHLINK_EINTERNAL;
781 logger(mesh, MESHLINK_DEBUG, "Done.\n");
786 static struct timeval idle(event_loop_t *loop, void *data) {
788 meshlink_handle_t *mesh = data;
789 struct timeval t, tmin = {3600, 0};
791 for splay_each(node_t, n, mesh->nodes) {
796 t = utcp_timeout(n->utcp);
798 if(timercmp(&t, &tmin, <)) {
806 // Get our local address(es) by simulating connecting to an Internet host.
807 static void add_local_addresses(meshlink_handle_t *mesh) {
808 struct sockaddr_storage sn;
809 socklen_t sl = sizeof(sn);
813 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl, mesh->netns)) {
814 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
815 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
822 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl, mesh->netns)) {
823 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
824 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
829 static bool meshlink_write_config(meshlink_handle_t *mesh) {
831 packmsg_output_t out = {buf, sizeof buf};
832 packmsg_add_str(&out, mesh->name);
833 packmsg_add_uint32(&out, mesh->devclass);
834 packmsg_add_uint16(&out, mesh->port);
835 packmsg_add_bin(&out, ecdsa, sizeof(ecdsa));
836 uint32_t len = packmsg_output_size(&out, buf);
839 logger(mesh, MESHLINK_DEBUG, "Could not create configuration data\n",);
840 meshlink_errno = MESHLINK_EINTERNAL;
846 static bool meshlink_setup(meshlink_handle_t *mesh) {
847 if(!config_init(mesh)) {
848 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s: %s\n", mesh->confbase, strerror(errno));
849 meshlink_errno = MESHLINK_ESTORAGE;
853 if(!ecdsa_keygen(mesh)) {
854 meshlink_errno = MESHLINK_EINTERNAL;
858 if(check_port(mesh) == 0) {
859 meshlink_errno = MESHLINK_ENETWORK;
863 /* Create a node for ourself */
865 mesh->self = new_node();
866 mesh->self->name = xstrdup(mesh->name);
867 mesh->self->devclass = mesh->devclass;
868 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
870 // Write the main config file
872 packmsg_output_t out = {buf, sizeof(buf)};
874 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
875 packmsg_add_str(&out, mesh->name);
876 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
877 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
878 packmsg_add_uint16(&out, atoi(mesh->myport));
880 config_t config = {buf, packmsg_output_size(&out, buf)};
882 if(!main_config_write(mesh, &config)) {
886 // Write our own host config file
888 out.len = sizeof(buf);
889 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
890 packmsg_add_str(&out, mesh->name);
891 packmsg_add_int32(&out, mesh->devclass);
892 packmsg_add_bool(&out, false);
893 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
894 packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
895 packmsg_add_array(&out, 0);
897 config.len = packmsg_output_size(&out, buf);
899 if(!config_write(mesh, mesh->name, &config)) {
906 static bool meshlink_read_config(meshlink_handle_t *mesh) {
907 // Open the configuration file and lock it
908 if(!main_config_lock(mesh)) {
909 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
910 meshlink_errno = MESHLINK_ESTORAGE;
916 if(!main_config_read(mesh, &config)) {
917 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
921 packmsg_input_t in = {config.buf, config.len};
922 const void *private_key;
923 const void *invitation_key;
925 uint32_t version = packmsg_get_uint32(&in);
926 char *name = packmsg_get_str_dup(&in);
927 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
928 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
929 uint16_t myport = packmsg_get_uint16(&in);
931 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
932 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
934 config_free(&config);
941 if(mesh->name && strcmp(mesh->name, name)) {
942 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
943 meshlink_errno = MESHLINK_ESTORAGE;
945 config_free(&config);
953 xasprintf(&mesh->myport, "%u", myport);
954 mesh->private_key = ecdsa_set_private_key(private_key);
955 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
956 config_free(&config);
958 /* Create a node for ourself and read our host configuration file */
960 mesh->self = new_node();
961 mesh->self->name = xstrdup(name);
962 mesh->self->devclass = mesh->devclass;
964 if(!node_read_public_key(mesh, mesh->self)) {
965 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
966 free_node(mesh->self);
974 static void *setup_network_in_netns_thread(void *arg) {
975 meshlink_handle_t *mesh = arg;
977 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
981 bool success = setup_network(mesh);
982 add_local_addresses(mesh);
983 return success ? arg : NULL;
986 meshlink_open_params_t *meshlink_open_params_init(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
987 if(!confbase || !*confbase) {
988 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
989 meshlink_errno = MESHLINK_EINVAL;
993 if(!appname || !*appname) {
994 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
995 meshlink_errno = MESHLINK_EINVAL;
999 if(strchr(appname, ' ')) {
1000 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1001 meshlink_errno = MESHLINK_EINVAL;
1005 if(!name || !*name) {
1006 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1008 } else { //check name only if there is a name != NULL
1009 if(!check_id(name)) {
1010 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1011 meshlink_errno = MESHLINK_EINVAL;
1016 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
1017 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1018 meshlink_errno = MESHLINK_EINVAL;
1022 meshlink_open_params_t *params = xzalloc(sizeof * params);
1024 params->confbase = xstrdup(confbase);
1025 params->name = xstrdup(name);
1026 params->appname = xstrdup(appname);
1027 params->devclass = devclass;
1033 bool meshlink_open_params_set_netns(meshlink_open_params_t *params, int netns) {
1035 meshlink_errno = MESHLINK_EINVAL;
1039 params->netns = netns;
1044 bool meshlink_open_params_set_storage_key(meshlink_open_params_t *params, const void *key, size_t keylen) {
1046 meshlink_errno = MESHLINK_EINVAL;
1050 if((!key && keylen) || (key && !keylen)) {
1051 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1052 meshlink_errno = MESHLINK_EINVAL;
1057 params->keylen = keylen;
1062 void meshlink_open_params_free(meshlink_open_params_t *params) {
1064 meshlink_errno = MESHLINK_EINVAL;
1068 free(params->confbase);
1070 free(params->appname);
1075 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1076 if(!confbase || !*confbase) {
1077 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1078 meshlink_errno = MESHLINK_EINVAL;
1082 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1083 meshlink_open_params_t params = {NULL};
1085 params.confbase = (char *)confbase;
1086 params.name = (char *)name;
1087 params.appname = (char *)appname;
1088 params.devclass = devclass;
1091 return meshlink_open_ex(¶ms);
1094 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) {
1095 if(!confbase || !*confbase) {
1096 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1097 meshlink_errno = MESHLINK_EINVAL;
1101 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1102 meshlink_open_params_t params = {NULL};
1104 params.confbase = (char *)confbase;
1105 params.name = (char *)name;
1106 params.appname = (char *)appname;
1107 params.devclass = devclass;
1110 if(!meshlink_open_params_set_storage_key(¶ms, key, keylen)) {
1114 return meshlink_open_ex(¶ms);
1117 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1118 /* Create a temporary struct on the stack, to avoid allocating and freeing one. */
1119 meshlink_open_params_t params = {NULL};
1121 params.name = (char *)name;
1122 params.appname = (char *)appname;
1123 params.devclass = devclass;
1126 return meshlink_open_ex(¶ms);
1129 meshlink_handle_t *meshlink_open_ex(const meshlink_open_params_t *params) {
1130 // Validate arguments provided by the application
1131 bool usingname = false;
1133 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
1135 if(!params->appname || !*params->appname) {
1136 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
1137 meshlink_errno = MESHLINK_EINVAL;
1141 if(strchr(params->appname, ' ')) {
1142 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
1143 meshlink_errno = MESHLINK_EINVAL;
1147 if(!params->name || !*params->name) {
1148 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1150 } else { //check name only if there is a name != NULL
1152 if(!check_id(params->name)) {
1153 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
1154 meshlink_errno = MESHLINK_EINVAL;
1161 if((int)params->devclass < 0 || params->devclass > _DEV_CLASS_MAX) {
1162 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
1163 meshlink_errno = MESHLINK_EINVAL;
1167 if((params->key && !params->keylen) || (!params->key && params->keylen)) {
1168 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
1169 meshlink_errno = MESHLINK_EINVAL;
1173 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
1175 if(params->confbase) {
1176 mesh->confbase = xstrdup(params->confbase);
1179 mesh->appname = xstrdup(params->appname);
1180 mesh->devclass = params->devclass;
1181 mesh->discovery = true;
1182 mesh->invitation_timeout = 604800; // 1 week
1183 mesh->netns = params->netns;
1184 mesh->submeshes = NULL;
1187 mesh->name = xstrdup(params->name);
1192 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1194 if(!prf(params->key, params->keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1195 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1196 meshlink_errno = MESHLINK_EINTERNAL;
1202 pthread_mutexattr_t attr;
1203 pthread_mutexattr_init(&attr);
1204 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1205 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1207 mesh->threadstarted = false;
1208 event_loop_init(&mesh->loop);
1209 mesh->loop.data = mesh;
1211 meshlink_queue_init(&mesh->outpacketqueue);
1213 // If no configuration exists yet, create it.
1215 if(!main_config_exists(mesh)) {
1216 if(!meshlink_setup(mesh)) {
1217 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1218 meshlink_close(mesh);
1222 if(!meshlink_read_config(mesh)) {
1223 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1224 meshlink_close(mesh);
1230 struct WSAData wsa_state;
1231 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1234 // Setup up everything
1235 // TODO: we should not open listening sockets yet
1237 bool success = false;
1239 if(mesh->netns != -1) {
1242 if(pthread_create(&thr, NULL, setup_network_in_netns_thread, mesh) == 0) {
1243 void *retval = NULL;
1244 success = pthread_join(thr, &retval) == 0 && retval;
1247 success = setup_network(mesh);
1248 add_local_addresses(mesh);
1252 meshlink_close(mesh);
1253 meshlink_errno = MESHLINK_ENETWORK;
1257 add_local_addresses(mesh);
1258 node_write_config(mesh, mesh->self);
1260 idle_set(&mesh->loop, idle, mesh);
1262 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1266 meshlink_submesh_t *meshlink_submesh_open(meshlink_handle_t *mesh, const char *submesh) {
1267 meshlink_submesh_t *s = NULL;
1270 logger(NULL, MESHLINK_ERROR, "No mesh handle given!\n");
1271 meshlink_errno = MESHLINK_EINVAL;
1275 if(!submesh || !*submesh) {
1276 logger(NULL, MESHLINK_ERROR, "No submesh name given!\n");
1277 meshlink_errno = MESHLINK_EINVAL;
1282 pthread_mutex_lock(&(mesh->mesh_mutex));
1284 s = (meshlink_submesh_t *)create_submesh(mesh, submesh);
1286 pthread_mutex_unlock(&(mesh->mesh_mutex));
1291 static void *meshlink_main_loop(void *arg) {
1292 meshlink_handle_t *mesh = arg;
1294 if(mesh->netns != -1) {
1295 if(setns(mesh->netns, CLONE_NEWNET) != 0) {
1300 pthread_mutex_lock(&(mesh->mesh_mutex));
1302 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1304 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1306 pthread_mutex_unlock(&(mesh->mesh_mutex));
1310 bool meshlink_start(meshlink_handle_t *mesh) {
1312 assert(mesh->private_key);
1315 meshlink_errno = MESHLINK_EINVAL;
1319 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1321 pthread_mutex_lock(&(mesh->mesh_mutex));
1323 if(mesh->threadstarted) {
1324 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1325 pthread_mutex_unlock(&(mesh->mesh_mutex));
1329 if(mesh->listen_socket[0].tcp.fd < 0) {
1330 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1331 meshlink_errno = MESHLINK_ENETWORK;
1335 mesh->thedatalen = 0;
1337 // TODO: open listening sockets first
1339 //Check that a valid name is set
1341 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1342 meshlink_errno = MESHLINK_EINVAL;
1343 pthread_mutex_unlock(&(mesh->mesh_mutex));
1347 init_outgoings(mesh);
1349 // Start the main thread
1351 event_loop_start(&mesh->loop);
1353 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1354 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1355 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1356 meshlink_errno = MESHLINK_EINTERNAL;
1357 event_loop_stop(&mesh->loop);
1358 pthread_mutex_unlock(&(mesh->mesh_mutex));
1362 mesh->threadstarted = true;
1366 if(mesh->discovery) {
1367 discovery_start(mesh);
1372 assert(mesh->self->ecdsa);
1373 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1376 pthread_mutex_unlock(&(mesh->mesh_mutex));
1380 void meshlink_stop(meshlink_handle_t *mesh) {
1382 meshlink_errno = MESHLINK_EINVAL;
1386 pthread_mutex_lock(&(mesh->mesh_mutex));
1387 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1392 if(mesh->discovery) {
1393 discovery_stop(mesh);
1398 // Shut down the main thread
1399 event_loop_stop(&mesh->loop);
1401 // Send ourselves a UDP packet to kick the event loop
1402 for(int i = 0; i < mesh->listen_sockets; i++) {
1404 socklen_t salen = sizeof(sa.sa);
1406 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1407 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1411 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1412 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1416 if(mesh->threadstarted) {
1417 // Wait for the main thread to finish
1418 pthread_mutex_unlock(&(mesh->mesh_mutex));
1419 pthread_join(mesh->thread, NULL);
1420 pthread_mutex_lock(&(mesh->mesh_mutex));
1422 mesh->threadstarted = false;
1425 // Close all metaconnections
1426 if(mesh->connections) {
1427 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1429 connection_t *c = node->data;
1431 terminate_connection(mesh, c, false);
1435 exit_outgoings(mesh);
1437 pthread_mutex_unlock(&(mesh->mesh_mutex));
1440 void meshlink_close(meshlink_handle_t *mesh) {
1442 meshlink_errno = MESHLINK_EINVAL;
1446 // stop can be called even if mesh has not been started
1447 meshlink_stop(mesh);
1449 // lock is not released after this
1450 pthread_mutex_lock(&(mesh->mesh_mutex));
1452 // Close and free all resources used.
1454 close_network_connections(mesh);
1456 logger(mesh, MESHLINK_INFO, "Terminating");
1458 event_loop_exit(&mesh->loop);
1462 if(mesh->confbase) {
1468 ecdsa_free(mesh->invitation_key);
1470 if(mesh->netns != -1) {
1475 free(mesh->appname);
1476 free(mesh->confbase);
1477 pthread_mutex_destroy(&(mesh->mesh_mutex));
1479 main_config_unlock(mesh);
1481 memset(mesh, 0, sizeof(*mesh));
1486 bool meshlink_destroy(const char *confbase) {
1488 meshlink_errno = MESHLINK_EINVAL;
1492 return config_destroy(confbase);
1495 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1497 meshlink_errno = MESHLINK_EINVAL;
1501 pthread_mutex_lock(&(mesh->mesh_mutex));
1502 mesh->receive_cb = cb;
1503 pthread_mutex_unlock(&(mesh->mesh_mutex));
1506 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1508 meshlink_errno = MESHLINK_EINVAL;
1512 pthread_mutex_lock(&(mesh->mesh_mutex));
1513 mesh->node_status_cb = cb;
1514 pthread_mutex_unlock(&(mesh->mesh_mutex));
1517 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1519 meshlink_errno = MESHLINK_EINVAL;
1523 pthread_mutex_lock(&(mesh->mesh_mutex));
1524 mesh->node_duplicate_cb = cb;
1525 pthread_mutex_unlock(&(mesh->mesh_mutex));
1528 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1530 pthread_mutex_lock(&(mesh->mesh_mutex));
1532 mesh->log_level = cb ? level : 0;
1533 pthread_mutex_unlock(&(mesh->mesh_mutex));
1536 global_log_level = cb ? level : 0;
1540 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1541 meshlink_packethdr_t *hdr;
1543 // Validate arguments
1544 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1545 meshlink_errno = MESHLINK_EINVAL;
1554 meshlink_errno = MESHLINK_EINVAL;
1558 node_t *n = (node_t *)destination;
1560 if(n->status.blacklisted) {
1561 logger(mesh, MESHLINK_ERROR, "Node %s blacklisted, dropping packet\n", n->name);
1565 // Prepare the packet
1566 vpn_packet_t *packet = malloc(sizeof(*packet));
1569 meshlink_errno = MESHLINK_ENOMEM;
1573 packet->probe = false;
1574 packet->tcp = false;
1575 packet->len = len + sizeof(*hdr);
1577 hdr = (meshlink_packethdr_t *)packet->data;
1578 memset(hdr, 0, sizeof(*hdr));
1579 // leave the last byte as 0 to make sure strings are always
1580 // null-terminated if they are longer than the buffer
1581 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1582 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1584 memcpy(packet->data + sizeof(*hdr), data, len);
1587 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1589 meshlink_errno = MESHLINK_ENOMEM;
1593 // Notify event loop
1594 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1599 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1601 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1607 mesh->self->in_packets++;
1608 mesh->self->in_bytes += packet->len;
1609 route(mesh, mesh->self, packet);
1612 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1613 if(!mesh || !destination) {
1614 meshlink_errno = MESHLINK_EINVAL;
1618 pthread_mutex_lock(&(mesh->mesh_mutex));
1620 node_t *n = (node_t *)destination;
1622 if(!n->status.reachable) {
1623 pthread_mutex_unlock(&(mesh->mesh_mutex));
1626 } else if(n->mtuprobes > 30 && n->minmtu) {
1627 pthread_mutex_unlock(&(mesh->mesh_mutex));
1630 pthread_mutex_unlock(&(mesh->mesh_mutex));
1635 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1636 if(!mesh || !node) {
1637 meshlink_errno = MESHLINK_EINVAL;
1641 pthread_mutex_lock(&(mesh->mesh_mutex));
1643 node_t *n = (node_t *)node;
1645 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1646 meshlink_errno = MESHLINK_EINTERNAL;
1647 pthread_mutex_unlock(&(mesh->mesh_mutex));
1651 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1654 meshlink_errno = MESHLINK_EINTERNAL;
1657 pthread_mutex_unlock(&(mesh->mesh_mutex));
1661 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1663 meshlink_errno = MESHLINK_EINVAL;
1667 return (meshlink_node_t *)mesh->self;
1670 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1671 if(!mesh || !name) {
1672 meshlink_errno = MESHLINK_EINVAL;
1676 meshlink_node_t *node = NULL;
1678 pthread_mutex_lock(&(mesh->mesh_mutex));
1679 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1680 pthread_mutex_unlock(&(mesh->mesh_mutex));
1684 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1685 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1686 meshlink_errno = MESHLINK_EINVAL;
1690 meshlink_node_t **result;
1693 pthread_mutex_lock(&(mesh->mesh_mutex));
1695 *nmemb = mesh->nodes->count;
1696 result = realloc(nodes, *nmemb * sizeof(*nodes));
1699 meshlink_node_t **p = result;
1701 for splay_each(node_t, n, mesh->nodes) {
1702 *p++ = (meshlink_node_t *)n;
1707 meshlink_errno = MESHLINK_ENOMEM;
1710 pthread_mutex_unlock(&(mesh->mesh_mutex));
1715 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) {
1716 meshlink_node_t **result;
1718 pthread_mutex_lock(&(mesh->mesh_mutex));
1722 for splay_each(node_t, n, mesh->nodes) {
1723 if(true == search_node(n, condition)) {
1724 *nmemb = *nmemb + 1;
1730 pthread_mutex_unlock(&(mesh->mesh_mutex));
1734 result = realloc(nodes, *nmemb * sizeof(*nodes));
1737 meshlink_node_t **p = result;
1739 for splay_each(node_t, n, mesh->nodes) {
1740 if(true == search_node(n, condition)) {
1741 *p++ = (meshlink_node_t *)n;
1747 meshlink_errno = MESHLINK_ENOMEM;
1750 pthread_mutex_unlock(&(mesh->mesh_mutex));
1755 static bool search_node_by_dev_class(const node_t *node, const void *condition) {
1756 dev_class_t *devclass = (dev_class_t *)condition;
1758 if(*devclass == node->devclass) {
1765 static bool search_node_by_submesh(const node_t *node, const void *condition) {
1766 if(condition == node->submesh) {
1773 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) {
1774 if(!mesh || ((int)devclass < 0) || (devclass > _DEV_CLASS_MAX) || !nmemb) {
1775 meshlink_errno = MESHLINK_EINVAL;
1779 return meshlink_get_all_nodes_by_condition(mesh, &devclass, nodes, nmemb, search_node_by_dev_class);
1782 meshlink_node_t **meshlink_get_all_nodes_by_submesh(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, meshlink_node_t **nodes, size_t *nmemb) {
1783 if(!mesh || !submesh || !nmemb) {
1784 meshlink_errno = MESHLINK_EINVAL;
1788 return meshlink_get_all_nodes_by_condition(mesh, submesh, nodes, nmemb, search_node_by_submesh);
1791 dev_class_t meshlink_get_node_dev_class(meshlink_handle_t *mesh, meshlink_node_t *node) {
1792 if(!mesh || !node) {
1793 meshlink_errno = MESHLINK_EINVAL;
1797 dev_class_t devclass;
1799 pthread_mutex_lock(&(mesh->mesh_mutex));
1801 devclass = ((node_t *)node)->devclass;
1803 pthread_mutex_unlock(&(mesh->mesh_mutex));
1808 meshlink_submesh_t *meshlink_get_node_submesh(meshlink_handle_t *mesh, meshlink_node_t *node) {
1809 if(!mesh || !node) {
1810 meshlink_errno = MESHLINK_EINVAL;
1814 node_t *n = (node_t *)node;
1816 meshlink_submesh_t *s;
1818 s = (meshlink_submesh_t *)n->submesh;
1823 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1824 if(!mesh || !data || !len || !signature || !siglen) {
1825 meshlink_errno = MESHLINK_EINVAL;
1829 if(*siglen < MESHLINK_SIGLEN) {
1830 meshlink_errno = MESHLINK_EINVAL;
1834 pthread_mutex_lock(&(mesh->mesh_mutex));
1836 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1837 meshlink_errno = MESHLINK_EINTERNAL;
1838 pthread_mutex_unlock(&(mesh->mesh_mutex));
1842 *siglen = MESHLINK_SIGLEN;
1843 pthread_mutex_unlock(&(mesh->mesh_mutex));
1847 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1848 if(!mesh || !data || !len || !signature) {
1849 meshlink_errno = MESHLINK_EINVAL;
1853 if(siglen != MESHLINK_SIGLEN) {
1854 meshlink_errno = MESHLINK_EINVAL;
1858 pthread_mutex_lock(&(mesh->mesh_mutex));
1862 struct node_t *n = (struct node_t *)source;
1864 if(!node_read_public_key(mesh, n)) {
1865 meshlink_errno = MESHLINK_EINTERNAL;
1868 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1871 pthread_mutex_unlock(&(mesh->mesh_mutex));
1875 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1876 pthread_mutex_lock(&(mesh->mesh_mutex));
1878 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
1881 // TODO: Update invitation key if necessary?
1884 pthread_mutex_unlock(&(mesh->mesh_mutex));
1886 return mesh->invitation_key;
1889 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1890 if(!mesh || !node || !address) {
1891 meshlink_errno = MESHLINK_EINVAL;
1895 if(!is_valid_hostname(address)) {
1896 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1897 meshlink_errno = MESHLINK_EINVAL;
1901 if(port && !is_valid_port(port)) {
1902 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1903 meshlink_errno = MESHLINK_EINVAL;
1907 char *canonical_address;
1910 xasprintf(&canonical_address, "%s %s", address, port);
1912 canonical_address = xstrdup(address);
1915 pthread_mutex_lock(&(mesh->mesh_mutex));
1917 node_t *n = (node_t *)node;
1918 free(n->canonical_address);
1919 n->canonical_address = canonical_address;
1920 n->status.dirty = true;
1922 pthread_mutex_unlock(&(mesh->mesh_mutex));
1927 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1928 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1931 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1933 meshlink_errno = MESHLINK_EINVAL;
1937 char *address = meshlink_get_external_address(mesh);
1943 bool rval = meshlink_add_address(mesh, address);
1949 int meshlink_get_port(meshlink_handle_t *mesh) {
1951 meshlink_errno = MESHLINK_EINVAL;
1956 meshlink_errno = MESHLINK_EINTERNAL;
1960 return atoi(mesh->myport);
1963 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1964 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1965 meshlink_errno = MESHLINK_EINVAL;
1969 if(mesh->myport && port == atoi(mesh->myport)) {
1973 if(!try_bind(port)) {
1974 meshlink_errno = MESHLINK_ENETWORK;
1980 pthread_mutex_lock(&(mesh->mesh_mutex));
1982 if(mesh->threadstarted) {
1983 meshlink_errno = MESHLINK_EINVAL;
1987 close_network_connections(mesh);
1989 // TODO: write meshlink.conf again
1991 if(!setup_network(mesh)) {
1992 meshlink_errno = MESHLINK_ENETWORK;
1998 pthread_mutex_unlock(&(mesh->mesh_mutex));
2003 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
2004 mesh->invitation_timeout = timeout;
2007 char *meshlink_invite_ex(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name, uint32_t flags) {
2008 meshlink_submesh_t *s = NULL;
2011 meshlink_errno = MESHLINK_EINVAL;
2016 s = (meshlink_submesh_t *)lookup_submesh(mesh, submesh->name);
2019 logger(mesh, MESHLINK_DEBUG, "Invalid SubMesh Handle.\n");
2020 meshlink_errno = MESHLINK_EINVAL;
2024 s = (meshlink_submesh_t *)mesh->self->submesh;
2027 pthread_mutex_lock(&(mesh->mesh_mutex));
2029 // Check validity of the new node's name
2030 if(!check_id(name)) {
2031 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
2032 meshlink_errno = MESHLINK_EINVAL;
2033 pthread_mutex_unlock(&(mesh->mesh_mutex));
2037 // Ensure no host configuration file with that name exists
2038 if(config_exists(mesh, name)) {
2039 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
2040 meshlink_errno = MESHLINK_EEXIST;
2041 pthread_mutex_unlock(&(mesh->mesh_mutex));
2045 // Ensure no other nodes know about this name
2046 if(meshlink_get_node(mesh, name)) {
2047 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
2048 meshlink_errno = MESHLINK_EEXIST;
2049 pthread_mutex_unlock(&(mesh->mesh_mutex));
2053 // Get the local address
2054 char *address = get_my_hostname(mesh, flags);
2057 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
2058 meshlink_errno = MESHLINK_ERESOLV;
2059 pthread_mutex_unlock(&(mesh->mesh_mutex));
2063 if(!refresh_invitation_key(mesh)) {
2064 meshlink_errno = MESHLINK_EINTERNAL;
2065 pthread_mutex_unlock(&(mesh->mesh_mutex));
2071 // Create a hash of the key.
2072 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
2073 sha512(fingerprint, strlen(fingerprint), hash);
2074 b64encode_urlsafe(hash, hash, 18);
2076 // Create a random cookie for this invitation.
2078 randomize(cookie, 18);
2080 // Create a filename that doesn't reveal the cookie itself
2081 char buf[18 + strlen(fingerprint)];
2082 char cookiehash[64];
2083 memcpy(buf, cookie, 18);
2084 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
2085 sha512(buf, sizeof(buf), cookiehash);
2086 b64encode_urlsafe(cookiehash, cookiehash, 18);
2088 b64encode_urlsafe(cookie, cookie, 18);
2092 /* Construct the invitation file */
2093 uint8_t outbuf[4096];
2094 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
2096 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
2097 packmsg_add_str(&inv, name);
2098 packmsg_add_str(&inv, s ? s->name : CORE_MESH);
2099 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
2101 /* TODO: Add several host config files to bootstrap connections */
2102 config_t configs[5] = {NULL};
2105 if(config_read(mesh, mesh->self->name, &configs[count])) {
2109 /* Append host config files to the invitation file */
2110 packmsg_add_array(&inv, count);
2112 for(int i = 0; i < count; i++) {
2113 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
2114 config_free(&configs[i]);
2117 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
2119 if(!invitation_write(mesh, cookiehash, &config)) {
2120 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
2121 meshlink_errno = MESHLINK_ESTORAGE;
2122 pthread_mutex_unlock(&(mesh->mesh_mutex));
2126 // Create an URL from the local address, key hash and cookie
2128 xasprintf(&url, "%s/%s%s", address, hash, cookie);
2131 pthread_mutex_unlock(&(mesh->mesh_mutex));
2135 char *meshlink_invite(meshlink_handle_t *mesh, meshlink_submesh_t *submesh, const char *name) {
2136 return meshlink_invite_ex(mesh, submesh, name, 0);
2139 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
2140 if(!mesh || !invitation) {
2141 meshlink_errno = MESHLINK_EINVAL;
2145 pthread_mutex_lock(&(mesh->mesh_mutex));
2147 //Before doing meshlink_join make sure we are not connected to another mesh
2148 if(mesh->threadstarted) {
2149 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
2150 meshlink_errno = MESHLINK_EINVAL;
2151 pthread_mutex_unlock(&(mesh->mesh_mutex));
2155 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
2156 char copy[strlen(invitation) + 1];
2157 strcpy(copy, invitation);
2159 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
2161 char *slash = strchr(copy, '/');
2169 if(strlen(slash) != 48) {
2173 char *address = copy;
2176 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
2180 // Generate a throw-away key for the invitation.
2181 ecdsa_t *key = ecdsa_generate();
2184 meshlink_errno = MESHLINK_EINTERNAL;
2185 pthread_mutex_unlock(&(mesh->mesh_mutex));
2189 char *b64key = ecdsa_get_base64_public_key(key);
2193 while(address && *address) {
2194 // We allow commas in the address part to support multiple addresses in one invitation URL.
2195 comma = strchr(address, ',');
2201 // Split of the port
2202 port = strrchr(address, ':');
2210 // IPv6 address are enclosed in brackets, per RFC 3986
2211 if(*address == '[') {
2213 char *bracket = strchr(address, ']');
2226 // Connect to the meshlink daemon mentioned in the URL.
2227 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
2230 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
2231 mesh->sock = socket_in_netns(aip->ai_family, aip->ai_socktype, aip->ai_protocol, mesh->netns);
2233 if(mesh->sock == -1) {
2234 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
2235 meshlink_errno = MESHLINK_ENETWORK;
2239 set_timeout(mesh->sock, 5000);
2241 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
2242 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
2243 meshlink_errno = MESHLINK_ENETWORK;
2244 closesocket(mesh->sock);
2252 meshlink_errno = MESHLINK_ERESOLV;
2255 if(mesh->sock != -1 || !comma) {
2262 if(mesh->sock == -1) {
2263 pthread_mutex_unlock(&mesh->mesh_mutex);
2267 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
2269 // Tell him we have an invitation, and give him our throw-away key.
2273 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
2274 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
2275 closesocket(mesh->sock);
2276 meshlink_errno = MESHLINK_ENETWORK;
2277 pthread_mutex_unlock(&(mesh->mesh_mutex));
2283 char hisname[4096] = "";
2284 int code, hismajor, hisminor = 0;
2286 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) {
2287 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
2288 closesocket(mesh->sock);
2289 meshlink_errno = MESHLINK_ENETWORK;
2290 pthread_mutex_unlock(&(mesh->mesh_mutex));
2294 // Check if the hash of the key he gave us matches the hash in the URL.
2295 char *fingerprint = mesh->line + 2;
2298 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
2299 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
2300 meshlink_errno = MESHLINK_EINTERNAL;
2301 pthread_mutex_unlock(&(mesh->mesh_mutex));
2305 if(memcmp(hishash, mesh->hash, 18)) {
2306 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
2307 meshlink_errno = MESHLINK_EPEER;
2308 pthread_mutex_unlock(&(mesh->mesh_mutex));
2313 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
2316 meshlink_errno = MESHLINK_EINTERNAL;
2317 pthread_mutex_unlock(&(mesh->mesh_mutex));
2321 // Start an SPTPS session
2322 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
2323 meshlink_errno = MESHLINK_EINTERNAL;
2324 pthread_mutex_unlock(&(mesh->mesh_mutex));
2328 // Feed rest of input buffer to SPTPS
2329 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
2330 meshlink_errno = MESHLINK_EPEER;
2331 pthread_mutex_unlock(&(mesh->mesh_mutex));
2337 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
2339 if(errno == EINTR) {
2343 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
2344 meshlink_errno = MESHLINK_ENETWORK;
2345 pthread_mutex_unlock(&(mesh->mesh_mutex));
2349 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2350 meshlink_errno = MESHLINK_EPEER;
2351 pthread_mutex_unlock(&(mesh->mesh_mutex));
2356 sptps_stop(&mesh->sptps);
2359 closesocket(mesh->sock);
2361 if(!mesh->success) {
2362 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2363 meshlink_errno = MESHLINK_EPEER;
2364 pthread_mutex_unlock(&(mesh->mesh_mutex));
2368 pthread_mutex_unlock(&(mesh->mesh_mutex));
2372 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2373 meshlink_errno = MESHLINK_EINVAL;
2374 pthread_mutex_unlock(&(mesh->mesh_mutex));
2378 char *meshlink_export(meshlink_handle_t *mesh) {
2380 meshlink_errno = MESHLINK_EINVAL;
2384 // Create a config file on the fly.
2387 packmsg_output_t out = {buf, sizeof(buf)};
2388 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2389 packmsg_add_str(&out, mesh->name);
2390 packmsg_add_str(&out, CORE_MESH);
2392 pthread_mutex_lock(&(mesh->mesh_mutex));
2394 packmsg_add_int32(&out, mesh->self->devclass);
2395 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2396 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2397 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2401 for(uint32_t i = 0; i < 5; i++) {
2402 if(mesh->self->recent[i].sa.sa_family) {
2409 packmsg_add_array(&out, count);
2411 for(uint32_t i = 0; i < count; i++) {
2412 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2415 pthread_mutex_unlock(&(mesh->mesh_mutex));
2417 if(!packmsg_output_ok(&out)) {
2418 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2419 meshlink_errno = MESHLINK_EINTERNAL;
2423 // Prepare a base64-encoded packmsg array containing our config file
2425 uint32_t len = packmsg_output_size(&out, buf);
2426 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2427 uint8_t *buf2 = xmalloc(len2);
2428 packmsg_output_t out2 = {buf2, len2};
2429 packmsg_add_array(&out2, 1);
2430 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2432 if(!packmsg_output_ok(&out2)) {
2433 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2434 meshlink_errno = MESHLINK_EINTERNAL;
2439 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2441 return (char *)buf2;
2444 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2445 if(!mesh || !data) {
2446 meshlink_errno = MESHLINK_EINVAL;
2450 size_t datalen = strlen(data);
2451 uint8_t *buf = xmalloc(datalen);
2452 int buflen = b64decode(data, buf, datalen);
2455 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2456 meshlink_errno = MESHLINK_EPEER;
2460 packmsg_input_t in = {buf, buflen};
2461 uint32_t count = packmsg_get_array(&in);
2464 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2465 meshlink_errno = MESHLINK_EPEER;
2469 pthread_mutex_lock(&(mesh->mesh_mutex));
2473 uint32_t len = packmsg_get_bin_raw(&in, &data);
2479 packmsg_input_t in2 = {data, len};
2480 uint32_t version = packmsg_get_uint32(&in2);
2481 char *name = packmsg_get_str_dup(&in2);
2483 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2485 packmsg_input_invalidate(&in2);
2489 if(!check_id(name)) {
2494 node_t *n = lookup_node(mesh, name);
2498 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2504 char *submesh_name = packmsg_get_str_dup(&in2);
2507 if(!strcmp(submesh_name, CORE_MESH)) {
2510 n->submesh = lookup_or_create_submesh(mesh, submesh_name);
2513 packmsg_input_invalidate(&in2);
2520 n->devclass = packmsg_get_int32(&in2);
2521 n->status.blacklisted = packmsg_get_bool(&in2);
2523 uint32_t keylen = packmsg_get_bin_raw(&in2, &key);
2526 n->ecdsa = ecdsa_set_public_key(key);
2529 n->canonical_address = packmsg_get_str_dup(&in2);
2530 uint32_t count = packmsg_get_array(&in2);
2536 for(uint32_t i = 0; i < count; i++) {
2537 n->recent[i] = packmsg_get_sockaddr(&in2);
2540 if(!packmsg_done(&in2) || keylen != 32) {
2541 packmsg_input_invalidate(&in);
2545 config_t config = {data, len};
2546 config_write(mesh, n->name, &config);
2551 pthread_mutex_unlock(&(mesh->mesh_mutex));
2553 if(!packmsg_done(&in)) {
2554 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2555 meshlink_errno = MESHLINK_EPEER;
2562 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2563 if(!mesh || !node) {
2564 meshlink_errno = MESHLINK_EINVAL;
2568 pthread_mutex_lock(&(mesh->mesh_mutex));
2573 if(n == mesh->self) {
2574 logger(mesh, MESHLINK_ERROR, "%s blacklisting itself?\n", node->name);
2575 meshlink_errno = MESHLINK_EINVAL;
2576 pthread_mutex_unlock(&(mesh->mesh_mutex));
2580 if(n->status.blacklisted) {
2581 logger(mesh, MESHLINK_DEBUG, "Node %s already blacklisted\n", node->name);
2582 pthread_mutex_unlock(&(mesh->mesh_mutex));
2586 n->status.blacklisted = true;
2587 n->status.dirty = true;
2588 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2590 //Immediately terminate any connections we have with the blacklisted node
2591 for list_each(connection_t, c, mesh->connections) {
2593 terminate_connection(mesh, c, c->status.active);
2597 utcp_abort_all_connections(n->utcp);
2603 n->status.udp_confirmed = false;
2605 if(n->status.reachable) {
2606 update_node_status(mesh, n);
2609 pthread_mutex_unlock(&(mesh->mesh_mutex));
2612 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2613 if(!mesh || !node) {
2614 meshlink_errno = MESHLINK_EINVAL;
2618 pthread_mutex_lock(&(mesh->mesh_mutex));
2620 node_t *n = (node_t *)node;
2622 if(!n->status.blacklisted) {
2623 logger(mesh, MESHLINK_DEBUG, "Node %s was already whitelisted\n", node->name);
2624 meshlink_errno = MESHLINK_EINVAL;
2625 pthread_mutex_unlock(&(mesh->mesh_mutex));
2629 n->status.blacklisted = false;
2630 n->status.dirty = true;
2632 pthread_mutex_unlock(&(mesh->mesh_mutex));
2636 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2637 mesh->default_blacklist = blacklist;
2640 /* Hint that a hostname may be found at an address
2641 * See header file for detailed comment.
2643 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2644 if(!mesh || !node || !addr) {
2645 meshlink_errno = EINVAL;
2649 pthread_mutex_lock(&(mesh->mesh_mutex));
2651 node_t *n = (node_t *)node;
2652 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2653 memcpy(n->recent, addr, SALEN(*addr));
2654 n->status.dirty = true;
2656 pthread_mutex_unlock(&(mesh->mesh_mutex));
2657 // @TODO do we want to fire off a connection attempt right away?
2660 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2662 node_t *n = utcp->priv;
2663 meshlink_handle_t *mesh = n->mesh;
2664 return mesh->channel_accept_cb;
2667 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2668 meshlink_channel_t *channel = connection->priv;
2674 node_t *n = channel->node;
2675 meshlink_handle_t *mesh = n->mesh;
2677 if(n->status.destroyed) {
2678 meshlink_channel_close(mesh, channel);
2679 } else if(channel->receive_cb) {
2680 channel->receive_cb(mesh, channel, data, len);
2686 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2687 node_t *n = utcp_connection->utcp->priv;
2693 meshlink_handle_t *mesh = n->mesh;
2695 if(!mesh->channel_accept_cb) {
2699 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2701 channel->c = utcp_connection;
2703 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2704 utcp_accept(utcp_connection, channel_recv, channel);
2710 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2711 node_t *n = utcp->priv;
2713 if(n->status.destroyed) {
2717 meshlink_handle_t *mesh = n->mesh;
2718 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2721 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2722 if(!mesh || !channel) {
2723 meshlink_errno = MESHLINK_EINVAL;
2727 channel->receive_cb = cb;
2730 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2732 node_t *n = (node_t *)source;
2738 utcp_recv(n->utcp, data, len);
2741 static void channel_poll(struct utcp_connection *connection, size_t len) {
2742 meshlink_channel_t *channel = connection->priv;
2748 node_t *n = channel->node;
2749 meshlink_handle_t *mesh = n->mesh;
2751 if(channel->poll_cb) {
2752 channel->poll_cb(mesh, channel, len);
2756 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2758 channel->poll_cb = cb;
2759 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2762 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2764 meshlink_errno = MESHLINK_EINVAL;
2768 pthread_mutex_lock(&mesh->mesh_mutex);
2769 mesh->channel_accept_cb = cb;
2770 mesh->receive_cb = channel_receive;
2772 for splay_each(node_t, n, mesh->nodes) {
2773 if(!n->utcp && n != mesh->self) {
2774 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2778 pthread_mutex_unlock(&mesh->mesh_mutex);
2781 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) {
2783 abort(); // TODO: handle non-NULL data
2786 if(!mesh || !node) {
2787 meshlink_errno = MESHLINK_EINVAL;
2791 node_t *n = (node_t *)node;
2794 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2795 mesh->receive_cb = channel_receive;
2798 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2803 if(n->status.blacklisted) {
2804 logger(mesh, MESHLINK_ERROR, "Cannot open a channel with blacklisted node\n");
2808 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2810 channel->receive_cb = cb;
2811 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2814 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2822 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) {
2823 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2826 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2827 if(!mesh || !channel) {
2828 meshlink_errno = MESHLINK_EINVAL;
2832 utcp_shutdown(channel->c, direction);
2835 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2836 if(!mesh || !channel) {
2837 meshlink_errno = MESHLINK_EINVAL;
2841 utcp_close(channel->c);
2845 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2846 if(!mesh || !channel) {
2847 meshlink_errno = MESHLINK_EINVAL;
2856 meshlink_errno = MESHLINK_EINVAL;
2860 // TODO: more finegrained locking.
2861 // Ideally we want to put the data into the UTCP connection's send buffer.
2862 // Then, preferably only if there is room in the receiver window,
2863 // kick the meshlink thread to go send packets.
2865 pthread_mutex_lock(&mesh->mesh_mutex);
2866 ssize_t retval = utcp_send(channel->c, data, len);
2867 pthread_mutex_unlock(&mesh->mesh_mutex);
2870 meshlink_errno = MESHLINK_ENETWORK;
2876 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2877 if(!mesh || !channel) {
2878 meshlink_errno = MESHLINK_EINVAL;
2882 return channel->c->flags;
2885 size_t meshlink_channel_get_sendq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2886 if(!mesh || !channel) {
2887 meshlink_errno = MESHLINK_EINVAL;
2891 return utcp_get_sendq(channel->c);
2894 size_t meshlink_channel_get_recvq(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2895 if(!mesh || !channel) {
2896 meshlink_errno = MESHLINK_EINVAL;
2900 return utcp_get_recvq(channel->c);
2903 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2904 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2905 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2908 if(mesh->node_status_cb) {
2909 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable && !n->status.blacklisted);
2913 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2914 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2918 n->status.duplicate = true;
2919 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2922 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2926 meshlink_errno = MESHLINK_EINVAL;
2930 pthread_mutex_lock(&mesh->mesh_mutex);
2932 if(mesh->discovery == enable) {
2936 if(mesh->threadstarted) {
2938 discovery_start(mesh);
2940 discovery_stop(mesh);
2944 mesh->discovery = enable;
2947 pthread_mutex_unlock(&mesh->mesh_mutex);
2951 meshlink_errno = MESHLINK_ENOTSUP;
2955 static void __attribute__((constructor)) meshlink_init(void) {
2958 randomize(&seed, sizeof(seed));
2962 static void __attribute__((destructor)) meshlink_exit(void) {
2966 /// Device class traits
2967 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2968 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2969 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2970 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2971 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN