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"
36 #include "ed25519/sha512.h"
37 #include "discovery.h"
40 #define MSG_NOSIGNAL 0
43 __thread meshlink_errno_t meshlink_errno;
44 meshlink_log_cb_t global_log_cb;
45 meshlink_log_level_t global_log_level;
47 static int rstrip(char *value) {
48 int len = strlen(value);
50 while(len && strchr("\t\r\n ", value[len - 1])) {
57 static void get_canonical_address(node_t *n, char **hostname, char **port) {
58 if(!n->canonical_address) {
62 *hostname = xstrdup(n->canonical_address);
63 char *space = strchr(*hostname, ' ');
67 *port = xstrdup(space);
71 static bool is_valid_hostname(const char *hostname) {
76 for(const char *p = hostname; *p; p++) {
77 if(!(isalnum(*p) || *p == '-' || *p == '.' || *p == ':')) {
85 static bool is_valid_port(const char *port) {
92 unsigned long int result = strtoul(port, &end, 10);
93 return result && result < 65536 && !*end;
96 for(const char *p = port; *p; p++) {
97 if(!(isalnum(*p) || *p == '-')) {
105 static void set_timeout(int sock, int timeout) {
110 tv.tv_sec = timeout / 1000;
111 tv.tv_usec = (timeout - tv.tv_sec * 1000) * 1000;
113 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
114 setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
117 // Find out what local address a socket would use if we connect to the given address.
118 // We do this using connect() on a UDP socket, so the kernel has to resolve the address
119 // of both endpoints, but this will actually not send any UDP packet.
120 static bool getlocaladdr(char *destaddr, struct sockaddr *sn, socklen_t *sl) {
121 struct addrinfo *rai = NULL;
122 const struct addrinfo hint = {
123 .ai_family = AF_UNSPEC,
124 .ai_socktype = SOCK_DGRAM,
125 .ai_protocol = IPPROTO_UDP,
128 if(getaddrinfo(destaddr, "80", &hint, &rai) || !rai) {
132 int sock = socket(rai->ai_family, rai->ai_socktype, rai->ai_protocol);
139 if(connect(sock, rai->ai_addr, rai->ai_addrlen) && !sockwouldblock(errno)) {
147 if(getsockname(sock, sn, sl)) {
156 static bool getlocaladdrname(char *destaddr, char *host, socklen_t hostlen) {
157 struct sockaddr_storage sn;
158 socklen_t sl = sizeof(sn);
160 if(!getlocaladdr(destaddr, (struct sockaddr *)&sn, &sl)) {
164 if(getnameinfo((struct sockaddr *)&sn, sl, host, hostlen, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV)) {
171 char *meshlink_get_external_address(meshlink_handle_t *mesh) {
172 return meshlink_get_external_address_for_family(mesh, AF_UNSPEC);
175 char *meshlink_get_external_address_for_family(meshlink_handle_t *mesh, int family) {
176 char *hostname = NULL;
178 logger(mesh, MESHLINK_DEBUG, "Trying to discover externally visible hostname...\n");
179 struct addrinfo *ai = str2addrinfo("meshlink.io", "80", SOCK_STREAM);
180 static const char request[] = "GET http://www.meshlink.io/host.cgi HTTP/1.0\r\n\r\n";
183 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
184 if(family != AF_UNSPEC && aip->ai_family != family) {
188 int s = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
191 set_timeout(s, 5000);
193 if(connect(s, aip->ai_addr, aip->ai_addrlen)) {
200 send(s, request, sizeof(request) - 1, 0);
201 int len = recv(s, line, sizeof(line) - 1, MSG_WAITALL);
206 if(line[len - 1] == '\n') {
210 char *p = strrchr(line, '\n');
213 hostname = xstrdup(p + 1);
229 // Check that the hostname is reasonable
230 if(hostname && !is_valid_hostname(hostname)) {
236 meshlink_errno = MESHLINK_ERESOLV;
242 char *meshlink_get_local_address_for_family(meshlink_handle_t *mesh, int family) {
245 // Determine address of the local interface used for outgoing connections.
246 char localaddr[NI_MAXHOST];
247 bool success = false;
249 if(family == AF_INET) {
250 success = getlocaladdrname("93.184.216.34", localaddr, sizeof(localaddr));
251 } else if(family == AF_INET6) {
252 success = getlocaladdrname("2606:2800:220:1:248:1893:25c8:1946", localaddr, sizeof(localaddr));
256 meshlink_errno = MESHLINK_ENETWORK;
260 return xstrdup(localaddr);
263 void remove_duplicate_hostnames(char *host[], char *port[], int n) {
264 for(int i = 0; i < n; i++) {
269 // Ignore duplicate hostnames
272 for(int j = 0; j < i; j++) {
277 if(strcmp(host[i], host[j])) {
281 if(strcmp(port[i], port[j])) {
299 // This gets the hostname part for use in invitation URLs
300 static char *get_my_hostname(meshlink_handle_t *mesh, uint32_t flags) {
301 char *hostname[4] = {NULL};
302 char *port[4] = {NULL};
303 char *hostport = NULL;
305 if(!(flags & (MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC))) {
306 flags |= MESHLINK_INVITE_LOCAL | MESHLINK_INVITE_PUBLIC;
309 if(!(flags & (MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6))) {
310 flags |= MESHLINK_INVITE_IPV4 | MESHLINK_INVITE_IPV6;
313 // Add local addresses if requested
314 if(flags & MESHLINK_INVITE_LOCAL) {
315 if(flags & MESHLINK_INVITE_IPV4) {
316 hostname[0] = meshlink_get_local_address_for_family(mesh, AF_INET);
319 if(flags & MESHLINK_INVITE_IPV6) {
320 hostname[1] = meshlink_get_local_address_for_family(mesh, AF_INET6);
324 // Add public/canonical addresses if requested
325 if(flags & MESHLINK_INVITE_PUBLIC) {
326 // Try the CanonicalAddress first
327 get_canonical_address(mesh->self, &hostname[2], &port[2]);
330 if(flags & MESHLINK_INVITE_IPV4) {
331 hostname[2] = meshlink_get_external_address_for_family(mesh, AF_INET);
334 if(flags & MESHLINK_INVITE_IPV6) {
335 hostname[3] = meshlink_get_external_address_for_family(mesh, AF_INET6);
340 for(int i = 0; i < 4; i++) {
341 // Ensure we always have a port number
342 if(hostname[i] && !port[i]) {
343 port[i] = xstrdup(mesh->myport);
347 remove_duplicate_hostnames(hostname, port, 4);
349 if(!(flags & MESHLINK_INVITE_NUMERIC)) {
350 for(int i = 0; i < 4; i++) {
355 // Convert what we have to a sockaddr
356 struct addrinfo *ai_in, *ai_out;
357 struct addrinfo hint = {
358 .ai_family = AF_UNSPEC,
359 .ai_flags = AI_NUMERICSERV,
360 .ai_socktype = SOCK_STREAM,
362 int err = getaddrinfo(hostname[i], port[i], &hint, &ai_in);
368 // Convert it to a hostname
369 char resolved_host[NI_MAXHOST];
370 char resolved_port[NI_MAXSERV];
371 err = getnameinfo(ai_in->ai_addr, ai_in->ai_addrlen, resolved_host, sizeof resolved_host, resolved_port, sizeof resolved_port, NI_NUMERICSERV);
378 // Convert the hostname back to a sockaddr
379 hint.ai_family = ai_in->ai_family;
380 err = getaddrinfo(resolved_host, resolved_port, &hint, &ai_out);
387 // Check if it's still the same sockaddr
388 if(ai_in->ai_addrlen != ai_out->ai_addrlen || memcmp(ai_in->ai_addr, ai_out->ai_addr, ai_in->ai_addrlen)) {
390 freeaddrinfo(ai_out);
394 // Yes: replace the hostname with the resolved one
396 hostname[i] = xstrdup(resolved_host);
399 freeaddrinfo(ai_out);
403 // Remove duplicates again, since IPv4 and IPv6 addresses might map to the same hostname
404 remove_duplicate_hostnames(hostname, port, 4);
406 // Concatenate all unique address to the hostport string
407 for(int i = 0; i < 4; i++) {
412 // Ensure we have the same addresses in our own host config file.
414 xasprintf(&tmphostport, "%s %s", hostname[i], port[i]);
416 //config_add_string(&mesh->config, "Address", tmphostport);
419 // Append the address to the hostport string
421 xasprintf(&newhostport, (strchr(hostname[i], ':') ? "%s%s[%s]:%s" : "%s%s%s:%s"), hostport ? hostport : "", hostport ? "," : "", hostname[i], port[i]);
423 hostport = newhostport;
432 static bool try_bind(int port) {
433 struct addrinfo *ai = NULL;
434 struct addrinfo hint = {
435 .ai_flags = AI_PASSIVE,
436 .ai_family = AF_UNSPEC,
437 .ai_socktype = SOCK_STREAM,
438 .ai_protocol = IPPROTO_TCP,
442 snprintf(portstr, sizeof(portstr), "%d", port);
444 if(getaddrinfo(NULL, portstr, &hint, &ai) || !ai) {
449 int fd = socket(ai->ai_family, SOCK_STREAM, IPPROTO_TCP);
456 int result = bind(fd, ai->ai_addr, ai->ai_addrlen);
471 int check_port(meshlink_handle_t *mesh) {
472 for(int i = 0; i < 1000; i++) {
473 int port = 0x1000 + (rand() & 0x7fff);
477 xasprintf(&mesh->myport, "%d", port);
482 meshlink_errno = MESHLINK_ENETWORK;
483 logger(mesh, MESHLINK_DEBUG, "Could not find any available network port.\n");
487 static bool finalize_join(meshlink_handle_t *mesh, const void *buf, uint16_t len) {
488 packmsg_input_t in = {buf, len};
489 uint32_t version = packmsg_get_uint32(&in);
491 if(version != MESHLINK_INVITATION_VERSION) {
492 logger(mesh, MESHLINK_ERROR, "Invalid invitation version!\n");
496 char *name = packmsg_get_str_dup(&in);
497 int32_t devclass = packmsg_get_int32(&in);
498 uint32_t count = packmsg_get_array(&in);
501 logger(mesh, MESHLINK_DEBUG, "No Name found in invitation!\n");
505 if(!check_id(name)) {
506 logger(mesh, MESHLINK_DEBUG, "Invalid Name found in invitation: %s!\n", name);
511 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
515 // Initialize configuration directory
516 if(!config_init(mesh)) {
520 // Write main config file
521 uint8_t outbuf[4096];
522 packmsg_output_t out = {outbuf, sizeof(outbuf)};
523 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
524 packmsg_add_str(&out, name);
525 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
526 packmsg_add_uint16(&out, atoi(mesh->myport));
528 config_t config = {outbuf, packmsg_output_size(&out, outbuf)};
530 if(!main_config_write(mesh, &config)) {
534 // Write our own host config file
536 out.len = sizeof(outbuf);
537 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
538 packmsg_add_str(&out, name);
539 packmsg_add_int32(&out, devclass);
540 packmsg_add_bool(&out, false);
541 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
542 packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
543 packmsg_add_array(&out, 0);
545 config.len = packmsg_output_size(&out, outbuf);
547 if(!config_write(mesh, name, &config)) {
551 // Write host config files
554 uint32_t len = packmsg_get_bin_raw(&in, &data);
557 logger(mesh, MESHLINK_ERROR, "Incomplete invitation file!\n");
561 packmsg_input_t in2 = {data, len};
562 uint32_t version = packmsg_get_uint32(&in2);
564 if(version != MESHLINK_CONFIG_VERSION) {
565 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
569 char *host = packmsg_get_str_dup(&in2);
571 if(!check_id(host)) {
572 logger(mesh, MESHLINK_ERROR, "Invalid node name in invitation file!\n");
577 if(!strcmp(host, name)) {
578 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
583 config_t config = {data, len};
584 config_write(mesh, host, &config);
586 node_t *n = new_node();
588 node_read_full(mesh, n);
589 n->devclass = mesh->devclass;
593 sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
596 free(mesh->self->name);
597 mesh->name = xstrdup(name);
598 mesh->self->name = xstrdup(name);
600 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
602 load_all_nodes(mesh);
607 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
609 meshlink_handle_t *mesh = handle;
610 const char *ptr = data;
613 int result = send(mesh->sock, ptr, len, 0);
615 if(result == -1 && errno == EINTR) {
617 } else if(result <= 0) {
628 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
629 meshlink_handle_t *mesh = handle;
632 case SPTPS_HANDSHAKE:
633 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
636 return finalize_join(mesh, msg, len);
639 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
640 shutdown(mesh->sock, SHUT_RDWR);
641 mesh->success = true;
651 static bool recvline(meshlink_handle_t *mesh, size_t len) {
652 char *newline = NULL;
658 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
659 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
661 if(result == -1 && errno == EINTR) {
663 } else if(result <= 0) {
667 mesh->blen += result;
670 if((size_t)(newline - mesh->buffer) >= len) {
674 len = newline - mesh->buffer;
676 memcpy(mesh->line, mesh->buffer, len);
678 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
679 mesh->blen -= len + 1;
683 static bool sendline(int fd, char *format, ...) {
684 static char buffer[4096];
689 va_start(ap, format);
690 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
693 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
701 int result = send(fd, p, blen, MSG_NOSIGNAL);
703 if(result == -1 && errno == EINTR) {
705 } else if(result <= 0) {
716 static const char *errstr[] = {
717 [MESHLINK_OK] = "No error",
718 [MESHLINK_EINVAL] = "Invalid argument",
719 [MESHLINK_ENOMEM] = "Out of memory",
720 [MESHLINK_ENOENT] = "No such node",
721 [MESHLINK_EEXIST] = "Node already exists",
722 [MESHLINK_EINTERNAL] = "Internal error",
723 [MESHLINK_ERESOLV] = "Could not resolve hostname",
724 [MESHLINK_ESTORAGE] = "Storage error",
725 [MESHLINK_ENETWORK] = "Network error",
726 [MESHLINK_EPEER] = "Error communicating with peer",
727 [MESHLINK_ENOTSUP] = "Operation not supported",
728 [MESHLINK_EBUSY] = "MeshLink instance already in use",
731 const char *meshlink_strerror(meshlink_errno_t err) {
732 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
733 return "Invalid error code";
739 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
740 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
742 mesh->private_key = ecdsa_generate();
743 mesh->invitation_key = ecdsa_generate();
745 if(!mesh->private_key || !mesh->invitation_key) {
746 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
747 meshlink_errno = MESHLINK_EINTERNAL;
751 logger(mesh, MESHLINK_DEBUG, "Done.\n");
756 static struct timeval idle(event_loop_t *loop, void *data) {
758 meshlink_handle_t *mesh = data;
759 struct timeval t, tmin = {3600, 0};
761 for splay_each(node_t, n, mesh->nodes) {
766 t = utcp_timeout(n->utcp);
768 if(timercmp(&t, &tmin, <)) {
776 // Get our local address(es) by simulating connecting to an Internet host.
777 static void add_local_addresses(meshlink_handle_t *mesh) {
778 struct sockaddr_storage sn;
779 socklen_t sl = sizeof(sn);
783 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl)) {
784 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
785 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
792 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl)) {
793 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
794 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
799 static bool meshlink_write_config(meshlink_handle_t *mesh) {
801 packmsg_output_t out = {buf, sizeof buf};
802 packmsg_add_str(&out, mesh->name);
803 packmsg_add_uint32(&out, mesh->devclass);
804 packmsg_add_uint16(&out, mesh->port);
805 packmsg_add_bin(&out, ecdsa, sizeof(ecdsa));
806 uint32_t len = packmsg_output_size(&out, buf);
809 logger(mesh, MESHLINK_DEBUG, "Could not create configuration data\n",);
810 meshlink_errno = MESHLINK_EINTERNAL;
816 static bool meshlink_setup(meshlink_handle_t *mesh) {
817 if(!config_init(mesh)) {
818 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s: %s\n", mesh->confbase, strerror(errno));
819 meshlink_errno = MESHLINK_ESTORAGE;
823 if(!ecdsa_keygen(mesh)) {
824 meshlink_errno = MESHLINK_EINTERNAL;
828 if(check_port(mesh) == 0) {
829 meshlink_errno = MESHLINK_ENETWORK;
833 /* Create a node for ourself */
835 mesh->self = new_node();
836 mesh->self->name = xstrdup(mesh->name);
837 mesh->self->devclass = mesh->devclass;
838 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
840 // Write the main config file
842 packmsg_output_t out = {buf, sizeof(buf)};
844 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
845 packmsg_add_str(&out, mesh->name);
846 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
847 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
848 packmsg_add_uint16(&out, atoi(mesh->myport));
850 config_t config = {buf, packmsg_output_size(&out, buf)};
852 if(!main_config_write(mesh, &config)) {
856 // Write our own host config file
858 out.len = sizeof(buf);
859 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
860 packmsg_add_str(&out, mesh->name);
861 packmsg_add_int32(&out, mesh->devclass);
862 packmsg_add_bool(&out, false);
863 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
864 packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
865 packmsg_add_array(&out, 0);
867 config.len = packmsg_output_size(&out, buf);
869 if(!config_write(mesh, mesh->name, &config)) {
876 static bool meshlink_read_config(meshlink_handle_t *mesh) {
877 // Open the configuration file and lock it
878 if(!main_config_lock(mesh)) {
879 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
880 meshlink_errno = MESHLINK_ESTORAGE;
886 if(!main_config_read(mesh, &config)) {
887 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
891 packmsg_input_t in = {config.buf, config.len};
892 const void *private_key;
893 const void *invitation_key;
895 uint32_t version = packmsg_get_uint32(&in);
896 char *name = packmsg_get_str_dup(&in);
897 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
898 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
899 uint16_t myport = packmsg_get_uint16(&in);
901 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
902 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
904 config_free(&config);
911 if(mesh->name && strcmp(mesh->name, name)) {
912 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
913 meshlink_errno = MESHLINK_ESTORAGE;
915 config_free(&config);
923 xasprintf(&mesh->myport, "%u", myport);
924 mesh->private_key = ecdsa_set_private_key(private_key);
925 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
926 config_free(&config);
928 /* Create a node for ourself and read our host configuration file */
930 mesh->self = new_node();
931 mesh->self->name = xstrdup(name);
932 mesh->self->devclass = mesh->devclass;
934 if(!node_read_public_key(mesh, mesh->self)) {
935 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
936 free_node(mesh->self);
945 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) {
946 // Validate arguments provided by the application
947 bool usingname = false;
949 logger(NULL, MESHLINK_DEBUG, "meshlink_open called\n");
951 if(!confbase || !*confbase) {
952 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
953 meshlink_errno = MESHLINK_EINVAL;
957 if(!appname || !*appname) {
958 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
959 meshlink_errno = MESHLINK_EINVAL;
963 if(strchr(appname, ' ')) {
964 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
965 meshlink_errno = MESHLINK_EINVAL;
969 if(!name || !*name) {
970 logger(NULL, MESHLINK_ERROR, "No name given!\n");
972 } else { //check name only if there is a name != NULL
973 if(!check_id(name)) {
974 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
975 meshlink_errno = MESHLINK_EINVAL;
982 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
983 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
984 meshlink_errno = MESHLINK_EINVAL;
988 if((key && !keylen) || (!key && keylen)) {
989 logger(NULL, MESHLINK_ERROR, "Invalid key length!\n");
990 meshlink_errno = MESHLINK_EINVAL;
994 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
995 mesh->confbase = xstrdup(confbase);
996 mesh->appname = xstrdup(appname);
997 mesh->devclass = devclass;
998 mesh->discovery = true;
999 mesh->invitation_timeout = 604800; // 1 week
1002 mesh->name = xstrdup(name);
1007 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
1009 if(!prf(key, keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
1010 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
1011 meshlink_errno = MESHLINK_EINTERNAL;
1017 pthread_mutexattr_t attr;
1018 pthread_mutexattr_init(&attr);
1019 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1020 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
1022 mesh->threadstarted = false;
1023 event_loop_init(&mesh->loop);
1024 mesh->loop.data = mesh;
1026 meshlink_queue_init(&mesh->outpacketqueue);
1028 // If no configuration exists yet, create it.
1030 if(!main_config_exists(mesh)) {
1031 if(!meshlink_setup(mesh)) {
1032 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1033 meshlink_close(mesh);
1037 if(!meshlink_read_config(mesh)) {
1038 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1039 meshlink_close(mesh);
1045 struct WSAData wsa_state;
1046 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1049 // Setup up everything
1050 // TODO: we should not open listening sockets yet
1052 if(!setup_network(mesh)) {
1053 meshlink_close(mesh);
1054 meshlink_errno = MESHLINK_ENETWORK;
1058 add_local_addresses(mesh);
1059 node_write_config(mesh, mesh->self);
1061 idle_set(&mesh->loop, idle, mesh);
1063 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1067 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1068 return meshlink_open_encrypted(confbase, name, appname, devclass, NULL, 0);
1071 static void *meshlink_main_loop(void *arg) {
1072 meshlink_handle_t *mesh = arg;
1074 pthread_mutex_lock(&(mesh->mesh_mutex));
1076 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1078 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1080 pthread_mutex_unlock(&(mesh->mesh_mutex));
1084 bool meshlink_start(meshlink_handle_t *mesh) {
1086 assert(mesh->private_key);
1089 meshlink_errno = MESHLINK_EINVAL;
1093 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1095 pthread_mutex_lock(&(mesh->mesh_mutex));
1097 if(mesh->threadstarted) {
1098 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1099 pthread_mutex_unlock(&(mesh->mesh_mutex));
1103 if(mesh->listen_socket[0].tcp.fd < 0) {
1104 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1105 meshlink_errno = MESHLINK_ENETWORK;
1109 mesh->thedatalen = 0;
1111 // TODO: open listening sockets first
1113 //Check that a valid name is set
1115 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1116 meshlink_errno = MESHLINK_EINVAL;
1117 pthread_mutex_unlock(&(mesh->mesh_mutex));
1121 init_outgoings(mesh);
1123 // Start the main thread
1125 event_loop_start(&mesh->loop);
1127 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1128 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1129 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1130 meshlink_errno = MESHLINK_EINTERNAL;
1131 event_loop_stop(&mesh->loop);
1132 pthread_mutex_unlock(&(mesh->mesh_mutex));
1136 mesh->threadstarted = true;
1140 if(mesh->discovery) {
1141 discovery_start(mesh);
1146 assert(mesh->self->ecdsa);
1147 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1150 pthread_mutex_unlock(&(mesh->mesh_mutex));
1154 void meshlink_stop(meshlink_handle_t *mesh) {
1156 meshlink_errno = MESHLINK_EINVAL;
1160 pthread_mutex_lock(&(mesh->mesh_mutex));
1161 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1166 if(mesh->discovery) {
1167 discovery_stop(mesh);
1172 // Shut down the main thread
1173 event_loop_stop(&mesh->loop);
1175 // Send ourselves a UDP packet to kick the event loop
1176 for(int i = 0; i < mesh->listen_sockets; i++) {
1178 socklen_t salen = sizeof(sa.sa);
1180 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1181 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1185 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1186 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1190 if(mesh->threadstarted) {
1191 // Wait for the main thread to finish
1192 pthread_mutex_unlock(&(mesh->mesh_mutex));
1193 pthread_join(mesh->thread, NULL);
1194 pthread_mutex_lock(&(mesh->mesh_mutex));
1196 mesh->threadstarted = false;
1199 // Close all metaconnections
1200 if(mesh->connections) {
1201 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1203 connection_t *c = node->data;
1205 terminate_connection(mesh, c, false);
1209 exit_outgoings(mesh);
1211 pthread_mutex_unlock(&(mesh->mesh_mutex));
1214 void meshlink_close(meshlink_handle_t *mesh) {
1215 if(!mesh || !mesh->confbase) {
1216 meshlink_errno = MESHLINK_EINVAL;
1220 // stop can be called even if mesh has not been started
1221 meshlink_stop(mesh);
1223 // lock is not released after this
1224 pthread_mutex_lock(&(mesh->mesh_mutex));
1226 // Close and free all resources used.
1228 close_network_connections(mesh);
1230 logger(mesh, MESHLINK_INFO, "Terminating");
1232 event_loop_exit(&mesh->loop);
1236 if(mesh->confbase) {
1242 ecdsa_free(mesh->invitation_key);
1245 free(mesh->appname);
1246 free(mesh->confbase);
1247 pthread_mutex_destroy(&(mesh->mesh_mutex));
1249 main_config_unlock(mesh);
1251 memset(mesh, 0, sizeof(*mesh));
1256 bool meshlink_destroy(const char *confbase) {
1258 meshlink_errno = MESHLINK_EINVAL;
1262 return config_destroy(confbase);
1265 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1267 meshlink_errno = MESHLINK_EINVAL;
1271 pthread_mutex_lock(&(mesh->mesh_mutex));
1272 mesh->receive_cb = cb;
1273 pthread_mutex_unlock(&(mesh->mesh_mutex));
1276 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1278 meshlink_errno = MESHLINK_EINVAL;
1282 pthread_mutex_lock(&(mesh->mesh_mutex));
1283 mesh->node_status_cb = cb;
1284 pthread_mutex_unlock(&(mesh->mesh_mutex));
1287 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1289 meshlink_errno = MESHLINK_EINVAL;
1293 pthread_mutex_lock(&(mesh->mesh_mutex));
1294 mesh->node_duplicate_cb = cb;
1295 pthread_mutex_unlock(&(mesh->mesh_mutex));
1298 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1300 pthread_mutex_lock(&(mesh->mesh_mutex));
1302 mesh->log_level = cb ? level : 0;
1303 pthread_mutex_unlock(&(mesh->mesh_mutex));
1306 global_log_level = cb ? level : 0;
1310 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1311 meshlink_packethdr_t *hdr;
1313 // Validate arguments
1314 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1315 meshlink_errno = MESHLINK_EINVAL;
1324 meshlink_errno = MESHLINK_EINVAL;
1328 // Prepare the packet
1329 vpn_packet_t *packet = malloc(sizeof(*packet));
1332 meshlink_errno = MESHLINK_ENOMEM;
1336 packet->probe = false;
1337 packet->tcp = false;
1338 packet->len = len + sizeof(*hdr);
1340 hdr = (meshlink_packethdr_t *)packet->data;
1341 memset(hdr, 0, sizeof(*hdr));
1342 // leave the last byte as 0 to make sure strings are always
1343 // null-terminated if they are longer than the buffer
1344 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1345 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1347 memcpy(packet->data + sizeof(*hdr), data, len);
1350 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1352 meshlink_errno = MESHLINK_ENOMEM;
1356 // Notify event loop
1357 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1362 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1364 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1370 mesh->self->in_packets++;
1371 mesh->self->in_bytes += packet->len;
1372 route(mesh, mesh->self, packet);
1375 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1376 if(!mesh || !destination) {
1377 meshlink_errno = MESHLINK_EINVAL;
1381 pthread_mutex_lock(&(mesh->mesh_mutex));
1383 node_t *n = (node_t *)destination;
1385 if(!n->status.reachable) {
1386 pthread_mutex_unlock(&(mesh->mesh_mutex));
1389 } else if(n->mtuprobes > 30 && n->minmtu) {
1390 pthread_mutex_unlock(&(mesh->mesh_mutex));
1393 pthread_mutex_unlock(&(mesh->mesh_mutex));
1398 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1399 if(!mesh || !node) {
1400 meshlink_errno = MESHLINK_EINVAL;
1404 pthread_mutex_lock(&(mesh->mesh_mutex));
1406 node_t *n = (node_t *)node;
1408 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1409 meshlink_errno = MESHLINK_EINTERNAL;
1410 pthread_mutex_unlock(&(mesh->mesh_mutex));
1414 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1417 meshlink_errno = MESHLINK_EINTERNAL;
1420 pthread_mutex_unlock(&(mesh->mesh_mutex));
1424 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1426 meshlink_errno = MESHLINK_EINVAL;
1430 return (meshlink_node_t *)mesh->self;
1433 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1434 if(!mesh || !name) {
1435 meshlink_errno = MESHLINK_EINVAL;
1439 meshlink_node_t *node = NULL;
1441 pthread_mutex_lock(&(mesh->mesh_mutex));
1442 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1443 pthread_mutex_unlock(&(mesh->mesh_mutex));
1447 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1448 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1449 meshlink_errno = MESHLINK_EINVAL;
1453 meshlink_node_t **result;
1456 pthread_mutex_lock(&(mesh->mesh_mutex));
1458 *nmemb = mesh->nodes->count;
1459 result = realloc(nodes, *nmemb * sizeof(*nodes));
1462 meshlink_node_t **p = result;
1464 for splay_each(node_t, n, mesh->nodes) {
1465 *p++ = (meshlink_node_t *)n;
1470 meshlink_errno = MESHLINK_ENOMEM;
1473 pthread_mutex_unlock(&(mesh->mesh_mutex));
1478 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1479 if(!mesh || !data || !len || !signature || !siglen) {
1480 meshlink_errno = MESHLINK_EINVAL;
1484 if(*siglen < MESHLINK_SIGLEN) {
1485 meshlink_errno = MESHLINK_EINVAL;
1489 pthread_mutex_lock(&(mesh->mesh_mutex));
1491 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1492 meshlink_errno = MESHLINK_EINTERNAL;
1493 pthread_mutex_unlock(&(mesh->mesh_mutex));
1497 *siglen = MESHLINK_SIGLEN;
1498 pthread_mutex_unlock(&(mesh->mesh_mutex));
1502 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1503 if(!mesh || !data || !len || !signature) {
1504 meshlink_errno = MESHLINK_EINVAL;
1508 if(siglen != MESHLINK_SIGLEN) {
1509 meshlink_errno = MESHLINK_EINVAL;
1513 pthread_mutex_lock(&(mesh->mesh_mutex));
1517 struct node_t *n = (struct node_t *)source;
1519 if(!node_read_public_key(mesh, n)) {
1520 meshlink_errno = MESHLINK_EINTERNAL;
1523 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1526 pthread_mutex_unlock(&(mesh->mesh_mutex));
1530 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1531 pthread_mutex_lock(&(mesh->mesh_mutex));
1533 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
1536 // TODO: Update invitation key if necessary?
1539 pthread_mutex_unlock(&(mesh->mesh_mutex));
1541 return mesh->invitation_key;
1544 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1545 if(!mesh || !node || !address) {
1546 meshlink_errno = MESHLINK_EINVAL;
1550 if(!is_valid_hostname(address)) {
1551 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1552 meshlink_errno = MESHLINK_EINVAL;
1556 if(port && !is_valid_port(port)) {
1557 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1558 meshlink_errno = MESHLINK_EINVAL;
1562 char *canonical_address;
1565 xasprintf(&canonical_address, "%s %s", address, port);
1567 canonical_address = xstrdup(address);
1570 pthread_mutex_lock(&(mesh->mesh_mutex));
1572 node_t *n = (node_t *)node;
1573 free(n->canonical_address);
1574 n->canonical_address = canonical_address;
1575 n->status.dirty = true;
1577 pthread_mutex_unlock(&(mesh->mesh_mutex));
1582 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1583 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1586 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1588 meshlink_errno = MESHLINK_EINVAL;
1592 char *address = meshlink_get_external_address(mesh);
1598 bool rval = meshlink_add_address(mesh, address);
1604 int meshlink_get_port(meshlink_handle_t *mesh) {
1606 meshlink_errno = MESHLINK_EINVAL;
1611 meshlink_errno = MESHLINK_EINTERNAL;
1615 return atoi(mesh->myport);
1618 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1619 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1620 meshlink_errno = MESHLINK_EINVAL;
1624 if(mesh->myport && port == atoi(mesh->myport)) {
1628 if(!try_bind(port)) {
1629 meshlink_errno = MESHLINK_ENETWORK;
1635 pthread_mutex_lock(&(mesh->mesh_mutex));
1637 if(mesh->threadstarted) {
1638 meshlink_errno = MESHLINK_EINVAL;
1642 close_network_connections(mesh);
1644 // TODO: write meshlink.conf again
1646 if(!setup_network(mesh)) {
1647 meshlink_errno = MESHLINK_ENETWORK;
1653 pthread_mutex_unlock(&(mesh->mesh_mutex));
1658 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1659 mesh->invitation_timeout = timeout;
1662 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
1664 meshlink_errno = MESHLINK_EINVAL;
1668 pthread_mutex_lock(&(mesh->mesh_mutex));
1670 // Check validity of the new node's name
1671 if(!check_id(name)) {
1672 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1673 meshlink_errno = MESHLINK_EINVAL;
1674 pthread_mutex_unlock(&(mesh->mesh_mutex));
1678 // Ensure no host configuration file with that name exists
1679 if(config_exists(mesh, name)) {
1680 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1681 meshlink_errno = MESHLINK_EEXIST;
1682 pthread_mutex_unlock(&(mesh->mesh_mutex));
1686 // Ensure no other nodes know about this name
1687 if(meshlink_get_node(mesh, name)) {
1688 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1689 meshlink_errno = MESHLINK_EEXIST;
1690 pthread_mutex_unlock(&(mesh->mesh_mutex));
1694 // Get the local address
1695 char *address = get_my_hostname(mesh, flags);
1698 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1699 meshlink_errno = MESHLINK_ERESOLV;
1700 pthread_mutex_unlock(&(mesh->mesh_mutex));
1704 if(!refresh_invitation_key(mesh)) {
1705 meshlink_errno = MESHLINK_EINTERNAL;
1706 pthread_mutex_unlock(&(mesh->mesh_mutex));
1712 // Create a hash of the key.
1713 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1714 sha512(fingerprint, strlen(fingerprint), hash);
1715 b64encode_urlsafe(hash, hash, 18);
1717 // Create a random cookie for this invitation.
1719 randomize(cookie, 18);
1721 // Create a filename that doesn't reveal the cookie itself
1722 char buf[18 + strlen(fingerprint)];
1723 char cookiehash[64];
1724 memcpy(buf, cookie, 18);
1725 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1726 sha512(buf, sizeof(buf), cookiehash);
1727 b64encode_urlsafe(cookiehash, cookiehash, 18);
1729 b64encode_urlsafe(cookie, cookie, 18);
1733 /* Construct the invitation file */
1734 uint8_t outbuf[4096];
1735 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
1737 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
1738 packmsg_add_str(&inv, name);
1739 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
1741 /* TODO: Add several host config files to bootstrap connections */
1742 config_t configs[5] = {NULL};
1745 if(config_read(mesh, mesh->self->name, &configs[count])) {
1749 /* Append host config files to the invitation file */
1750 packmsg_add_array(&inv, count);
1752 for(int i = 0; i < count; i++) {
1753 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
1754 config_free(&configs[i]);
1757 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
1759 if(!invitation_write(mesh, cookiehash, &config)) {
1760 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
1761 meshlink_errno = MESHLINK_ESTORAGE;
1762 pthread_mutex_unlock(&(mesh->mesh_mutex));
1766 // Create an URL from the local address, key hash and cookie
1768 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1771 pthread_mutex_unlock(&(mesh->mesh_mutex));
1775 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1776 return meshlink_invite_ex(mesh, name, 0);
1779 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1780 if(!mesh || !invitation) {
1781 meshlink_errno = MESHLINK_EINVAL;
1785 pthread_mutex_lock(&(mesh->mesh_mutex));
1787 //Before doing meshlink_join make sure we are not connected to another mesh
1788 if(mesh->threadstarted) {
1789 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1790 meshlink_errno = MESHLINK_EINVAL;
1791 pthread_mutex_unlock(&(mesh->mesh_mutex));
1795 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1796 char copy[strlen(invitation) + 1];
1797 strcpy(copy, invitation);
1799 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1801 char *slash = strchr(copy, '/');
1809 if(strlen(slash) != 48) {
1813 char *address = copy;
1816 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
1820 // Generate a throw-away key for the invitation.
1821 ecdsa_t *key = ecdsa_generate();
1824 meshlink_errno = MESHLINK_EINTERNAL;
1825 pthread_mutex_unlock(&(mesh->mesh_mutex));
1829 char *b64key = ecdsa_get_base64_public_key(key);
1833 while(address && *address) {
1834 // We allow commas in the address part to support multiple addresses in one invitation URL.
1835 comma = strchr(address, ',');
1841 // Split of the port
1842 port = strrchr(address, ':');
1850 // IPv6 address are enclosed in brackets, per RFC 3986
1851 if(*address == '[') {
1853 char *bracket = strchr(address, ']');
1866 // Connect to the meshlink daemon mentioned in the URL.
1867 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1870 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1871 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1873 if(mesh->sock == -1) {
1874 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1875 meshlink_errno = MESHLINK_ENETWORK;
1879 set_timeout(mesh->sock, 5000);
1881 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
1882 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1883 meshlink_errno = MESHLINK_ENETWORK;
1884 closesocket(mesh->sock);
1892 meshlink_errno = MESHLINK_ERESOLV;
1895 if(mesh->sock != -1 || !comma) {
1902 if(mesh->sock == -1) {
1903 pthread_mutex_unlock(&mesh->mesh_mutex);
1907 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1909 // Tell him we have an invitation, and give him our throw-away key.
1913 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
1914 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1915 closesocket(mesh->sock);
1916 meshlink_errno = MESHLINK_ENETWORK;
1917 pthread_mutex_unlock(&(mesh->mesh_mutex));
1923 char hisname[4096] = "";
1924 int code, hismajor, hisminor = 0;
1926 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) {
1927 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1928 closesocket(mesh->sock);
1929 meshlink_errno = MESHLINK_ENETWORK;
1930 pthread_mutex_unlock(&(mesh->mesh_mutex));
1934 // Check if the hash of the key he gave us matches the hash in the URL.
1935 char *fingerprint = mesh->line + 2;
1938 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1939 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1940 meshlink_errno = MESHLINK_EINTERNAL;
1941 pthread_mutex_unlock(&(mesh->mesh_mutex));
1945 if(memcmp(hishash, mesh->hash, 18)) {
1946 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1947 meshlink_errno = MESHLINK_EPEER;
1948 pthread_mutex_unlock(&(mesh->mesh_mutex));
1953 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1956 meshlink_errno = MESHLINK_EINTERNAL;
1957 pthread_mutex_unlock(&(mesh->mesh_mutex));
1961 // Start an SPTPS session
1962 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1963 meshlink_errno = MESHLINK_EINTERNAL;
1964 pthread_mutex_unlock(&(mesh->mesh_mutex));
1968 // Feed rest of input buffer to SPTPS
1969 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1970 meshlink_errno = MESHLINK_EPEER;
1971 pthread_mutex_unlock(&(mesh->mesh_mutex));
1977 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
1979 if(errno == EINTR) {
1983 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1984 meshlink_errno = MESHLINK_ENETWORK;
1985 pthread_mutex_unlock(&(mesh->mesh_mutex));
1989 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
1990 meshlink_errno = MESHLINK_EPEER;
1991 pthread_mutex_unlock(&(mesh->mesh_mutex));
1996 sptps_stop(&mesh->sptps);
1999 closesocket(mesh->sock);
2001 if(!mesh->success) {
2002 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2003 meshlink_errno = MESHLINK_EPEER;
2004 pthread_mutex_unlock(&(mesh->mesh_mutex));
2008 pthread_mutex_unlock(&(mesh->mesh_mutex));
2012 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2013 meshlink_errno = MESHLINK_EINVAL;
2014 pthread_mutex_unlock(&(mesh->mesh_mutex));
2018 char *meshlink_export(meshlink_handle_t *mesh) {
2020 meshlink_errno = MESHLINK_EINVAL;
2026 // Get our config file
2028 pthread_mutex_lock(&(mesh->mesh_mutex));
2030 if(!config_read(mesh, mesh->self->name, &config)) {
2031 meshlink_errno = MESHLINK_ESTORAGE;
2032 pthread_mutex_unlock(&mesh->mesh_mutex);
2036 pthread_mutex_unlock(&(mesh->mesh_mutex));
2038 // Prepare a base64-encoded packmsg array containing our config file
2040 uint8_t *buf = xmalloc(((config.len + 4) * 4) / 3 + 4);
2041 packmsg_output_t out = {buf, config.len + 4};
2042 packmsg_add_array(&out, 1);
2043 packmsg_add_bin(&out, config.buf, config.len);
2044 config_free(&config);
2046 if(!packmsg_output_ok(&out)) {
2047 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2048 meshlink_errno = MESHLINK_EINTERNAL;
2053 b64encode_urlsafe(buf, (char *)buf, packmsg_output_size(&out, buf));
2058 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2059 if(!mesh || !data) {
2061 meshlink_errno = MESHLINK_EINVAL;
2065 size_t datalen = strlen(data);
2066 uint8_t *buf = xmalloc(datalen);
2067 int buflen = b64decode(data, buf, datalen);
2071 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2072 meshlink_errno = MESHLINK_EPEER;
2076 packmsg_input_t in = {buf, buflen};
2077 uint32_t count = packmsg_get_array(&in);
2081 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2082 meshlink_errno = MESHLINK_EPEER;
2086 pthread_mutex_lock(&(mesh->mesh_mutex));
2090 uint32_t len = packmsg_get_bin_raw(&in, &data);
2096 packmsg_input_t in2 = {data, len};
2097 uint32_t version = packmsg_get_uint32(&in2);
2098 char *name = packmsg_get_str_dup(&in2);
2100 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2102 packmsg_input_invalidate(&in2);
2106 if(!check_id(name)) {
2111 node_t *n = lookup_node(mesh, name);
2115 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2121 n->devclass = packmsg_get_int32(&in2);
2122 n->status.blacklisted = packmsg_get_bool(&in2);
2124 uint32_t keylen = packmsg_get_bin_raw(&in2, &key);
2127 n->ecdsa = ecdsa_set_public_key(key);
2130 n->canonical_address = packmsg_get_str_dup(&in2);
2131 uint32_t count = packmsg_get_array(&in2);
2137 for(uint32_t i = 0; i < count; i++) {
2138 n->recent[i] = packmsg_get_sockaddr(&in2);
2141 if(!packmsg_done(&in2) || keylen != 32) {
2143 packmsg_input_invalidate(&in2);
2146 config_t config = {data, len};
2147 config_write(mesh, n->name, &config);
2152 pthread_mutex_unlock(&(mesh->mesh_mutex));
2154 if(!packmsg_done(&in)) {
2156 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2157 meshlink_errno = MESHLINK_EPEER;
2164 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2165 if(!mesh || !node) {
2166 meshlink_errno = MESHLINK_EINVAL;
2170 pthread_mutex_lock(&(mesh->mesh_mutex));
2174 n->status.blacklisted = true;
2175 n->status.dirty = true;
2176 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2178 //Immediately terminate any connections we have with the blacklisted node
2179 for list_each(connection_t, c, mesh->connections) {
2181 terminate_connection(mesh, c, c->status.active);
2185 pthread_mutex_unlock(&(mesh->mesh_mutex));
2188 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2189 if(!mesh || !node) {
2190 meshlink_errno = MESHLINK_EINVAL;
2194 pthread_mutex_lock(&(mesh->mesh_mutex));
2196 node_t *n = (node_t *)node;
2197 n->status.blacklisted = false;
2198 n->status.dirty = true;
2200 pthread_mutex_unlock(&(mesh->mesh_mutex));
2204 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2205 mesh->default_blacklist = blacklist;
2208 /* Hint that a hostname may be found at an address
2209 * See header file for detailed comment.
2211 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2212 if(!mesh || !node || !addr) {
2213 meshlink_errno = EINVAL;
2217 pthread_mutex_lock(&(mesh->mesh_mutex));
2219 node_t *n = (node_t *)node;
2220 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2221 memcpy(n->recent, addr, SALEN(*addr));
2222 n->status.dirty = true;
2224 pthread_mutex_unlock(&(mesh->mesh_mutex));
2225 // @TODO do we want to fire off a connection attempt right away?
2228 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2230 node_t *n = utcp->priv;
2231 meshlink_handle_t *mesh = n->mesh;
2232 return mesh->channel_accept_cb;
2235 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2236 meshlink_channel_t *channel = connection->priv;
2242 node_t *n = channel->node;
2243 meshlink_handle_t *mesh = n->mesh;
2245 if(n->status.destroyed) {
2246 meshlink_channel_close(mesh, channel);
2247 } else if(channel->receive_cb) {
2248 channel->receive_cb(mesh, channel, data, len);
2254 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2255 node_t *n = utcp_connection->utcp->priv;
2261 meshlink_handle_t *mesh = n->mesh;
2263 if(!mesh->channel_accept_cb) {
2267 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2269 channel->c = utcp_connection;
2271 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2272 utcp_accept(utcp_connection, channel_recv, channel);
2278 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2279 node_t *n = utcp->priv;
2281 if(n->status.destroyed) {
2285 meshlink_handle_t *mesh = n->mesh;
2286 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2289 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2290 if(!mesh || !channel) {
2291 meshlink_errno = MESHLINK_EINVAL;
2295 channel->receive_cb = cb;
2298 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2300 node_t *n = (node_t *)source;
2306 utcp_recv(n->utcp, data, len);
2309 static void channel_poll(struct utcp_connection *connection, size_t len) {
2310 meshlink_channel_t *channel = connection->priv;
2316 node_t *n = channel->node;
2317 meshlink_handle_t *mesh = n->mesh;
2319 if(channel->poll_cb) {
2320 channel->poll_cb(mesh, channel, len);
2324 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2326 channel->poll_cb = cb;
2327 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2330 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2332 meshlink_errno = MESHLINK_EINVAL;
2336 pthread_mutex_lock(&mesh->mesh_mutex);
2337 mesh->channel_accept_cb = cb;
2338 mesh->receive_cb = channel_receive;
2340 for splay_each(node_t, n, mesh->nodes) {
2341 if(!n->utcp && n != mesh->self) {
2342 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2346 pthread_mutex_unlock(&mesh->mesh_mutex);
2349 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) {
2351 abort(); // TODO: handle non-NULL data
2354 if(!mesh || !node) {
2355 meshlink_errno = MESHLINK_EINVAL;
2359 node_t *n = (node_t *)node;
2362 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2363 mesh->receive_cb = channel_receive;
2366 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2371 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2373 channel->receive_cb = cb;
2374 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2377 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2385 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) {
2386 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2389 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2390 if(!mesh || !channel) {
2391 meshlink_errno = MESHLINK_EINVAL;
2395 utcp_shutdown(channel->c, direction);
2398 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2399 if(!mesh || !channel) {
2400 meshlink_errno = MESHLINK_EINVAL;
2404 utcp_close(channel->c);
2408 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2409 if(!mesh || !channel) {
2410 meshlink_errno = MESHLINK_EINVAL;
2419 meshlink_errno = MESHLINK_EINVAL;
2423 // TODO: more finegrained locking.
2424 // Ideally we want to put the data into the UTCP connection's send buffer.
2425 // Then, preferrably only if there is room in the receiver window,
2426 // kick the meshlink thread to go send packets.
2428 pthread_mutex_lock(&mesh->mesh_mutex);
2429 ssize_t retval = utcp_send(channel->c, data, len);
2430 pthread_mutex_unlock(&mesh->mesh_mutex);
2433 meshlink_errno = MESHLINK_ENETWORK;
2439 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2440 if(!mesh || !channel) {
2441 meshlink_errno = MESHLINK_EINVAL;
2445 return channel->c->flags;
2448 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2449 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2450 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2453 if(mesh->node_status_cb) {
2454 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2458 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2459 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2463 n->status.duplicate = true;
2464 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2467 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2471 meshlink_errno = MESHLINK_EINVAL;
2475 pthread_mutex_lock(&mesh->mesh_mutex);
2477 if(mesh->discovery == enable) {
2481 if(mesh->threadstarted) {
2483 discovery_start(mesh);
2485 discovery_stop(mesh);
2489 mesh->discovery = enable;
2492 pthread_mutex_unlock(&mesh->mesh_mutex);
2496 meshlink_errno = MESHLINK_ENOTSUP;
2500 static void __attribute__((constructor)) meshlink_init(void) {
2503 randomize(&seed, sizeof(seed));
2507 static void __attribute__((destructor)) meshlink_exit(void) {
2511 /// Device class traits
2512 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2513 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2514 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2515 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2516 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN