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 config_t config = {data, len};
562 node_t *n = new_node();
564 if(!node_read_from_config(mesh, n, &config)) {
566 logger(mesh, MESHLINK_ERROR, "Invalid host config file in invitation file!\n");
567 meshlink_errno = MESHLINK_EPEER;
571 if(!strcmp(n->name, name)) {
572 logger(mesh, MESHLINK_DEBUG, "Secondary chunk would overwrite our own host config file.\n");
574 meshlink_errno = MESHLINK_EPEER;
580 if(!config_write(mesh, n->name, &config)) {
585 sptps_send_record(&(mesh->sptps), 1, ecdsa_get_public_key(mesh->private_key), 32);
588 free(mesh->self->name);
589 mesh->name = xstrdup(name);
590 mesh->self->name = xstrdup(name);
592 logger(mesh, MESHLINK_DEBUG, "Configuration stored in: %s\n", mesh->confbase);
597 static bool invitation_send(void *handle, uint8_t type, const void *data, size_t len) {
599 meshlink_handle_t *mesh = handle;
600 const char *ptr = data;
603 int result = send(mesh->sock, ptr, len, 0);
605 if(result == -1 && errno == EINTR) {
607 } else if(result <= 0) {
618 static bool invitation_receive(void *handle, uint8_t type, const void *msg, uint16_t len) {
619 meshlink_handle_t *mesh = handle;
622 case SPTPS_HANDSHAKE:
623 return sptps_send_record(&(mesh->sptps), 0, mesh->cookie, sizeof(mesh)->cookie);
626 return finalize_join(mesh, msg, len);
629 logger(mesh, MESHLINK_DEBUG, "Invitation succesfully accepted.\n");
630 shutdown(mesh->sock, SHUT_RDWR);
631 mesh->success = true;
641 static bool recvline(meshlink_handle_t *mesh, size_t len) {
642 char *newline = NULL;
648 while(!(newline = memchr(mesh->buffer, '\n', mesh->blen))) {
649 int result = recv(mesh->sock, mesh->buffer + mesh->blen, sizeof(mesh)->buffer - mesh->blen, 0);
651 if(result == -1 && errno == EINTR) {
653 } else if(result <= 0) {
657 mesh->blen += result;
660 if((size_t)(newline - mesh->buffer) >= len) {
664 len = newline - mesh->buffer;
666 memcpy(mesh->line, mesh->buffer, len);
668 memmove(mesh->buffer, newline + 1, mesh->blen - len - 1);
669 mesh->blen -= len + 1;
673 static bool sendline(int fd, char *format, ...) {
674 static char buffer[4096];
679 va_start(ap, format);
680 blen = vsnprintf(buffer, sizeof(buffer), format, ap);
683 if(blen < 1 || (size_t)blen >= sizeof(buffer)) {
691 int result = send(fd, p, blen, MSG_NOSIGNAL);
693 if(result == -1 && errno == EINTR) {
695 } else if(result <= 0) {
706 static const char *errstr[] = {
707 [MESHLINK_OK] = "No error",
708 [MESHLINK_EINVAL] = "Invalid argument",
709 [MESHLINK_ENOMEM] = "Out of memory",
710 [MESHLINK_ENOENT] = "No such node",
711 [MESHLINK_EEXIST] = "Node already exists",
712 [MESHLINK_EINTERNAL] = "Internal error",
713 [MESHLINK_ERESOLV] = "Could not resolve hostname",
714 [MESHLINK_ESTORAGE] = "Storage error",
715 [MESHLINK_ENETWORK] = "Network error",
716 [MESHLINK_EPEER] = "Error communicating with peer",
717 [MESHLINK_ENOTSUP] = "Operation not supported",
718 [MESHLINK_EBUSY] = "MeshLink instance already in use",
721 const char *meshlink_strerror(meshlink_errno_t err) {
722 if((int)err < 0 || err >= sizeof(errstr) / sizeof(*errstr)) {
723 return "Invalid error code";
729 static bool ecdsa_keygen(meshlink_handle_t *mesh) {
730 logger(mesh, MESHLINK_DEBUG, "Generating ECDSA keypairs:\n");
732 mesh->private_key = ecdsa_generate();
733 mesh->invitation_key = ecdsa_generate();
735 if(!mesh->private_key || !mesh->invitation_key) {
736 logger(mesh, MESHLINK_DEBUG, "Error during key generation!\n");
737 meshlink_errno = MESHLINK_EINTERNAL;
741 logger(mesh, MESHLINK_DEBUG, "Done.\n");
746 static struct timeval idle(event_loop_t *loop, void *data) {
748 meshlink_handle_t *mesh = data;
749 struct timeval t, tmin = {3600, 0};
751 for splay_each(node_t, n, mesh->nodes) {
756 t = utcp_timeout(n->utcp);
758 if(timercmp(&t, &tmin, <)) {
766 // Get our local address(es) by simulating connecting to an Internet host.
767 static void add_local_addresses(meshlink_handle_t *mesh) {
768 struct sockaddr_storage sn;
769 socklen_t sl = sizeof(sn);
773 if(getlocaladdr("93.184.216.34", (struct sockaddr *)&sn, &sl)) {
774 ((struct sockaddr_in *)&sn)->sin_port = ntohs(atoi(mesh->myport));
775 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
782 if(getlocaladdr("2606:2800:220:1:248:1893:25c8:1946", (struct sockaddr *)&sn, &sl)) {
783 ((struct sockaddr_in6 *)&sn)->sin6_port = ntohs(atoi(mesh->myport));
784 meshlink_hint_address(mesh, (meshlink_node_t *)mesh->self, (struct sockaddr *)&sn);
789 static bool meshlink_write_config(meshlink_handle_t *mesh) {
791 packmsg_output_t out = {buf, sizeof buf};
792 packmsg_add_str(&out, mesh->name);
793 packmsg_add_uint32(&out, mesh->devclass);
794 packmsg_add_uint16(&out, mesh->port);
795 packmsg_add_bin(&out, ecdsa, sizeof(ecdsa));
796 uint32_t len = packmsg_output_size(&out, buf);
799 logger(mesh, MESHLINK_DEBUG, "Could not create configuration data\n",);
800 meshlink_errno = MESHLINK_EINTERNAL;
806 static bool meshlink_setup(meshlink_handle_t *mesh) {
807 if(!config_init(mesh)) {
808 logger(mesh, MESHLINK_ERROR, "Could not set up configuration in %s: %s\n", mesh->confbase, strerror(errno));
809 meshlink_errno = MESHLINK_ESTORAGE;
813 if(!ecdsa_keygen(mesh)) {
814 meshlink_errno = MESHLINK_EINTERNAL;
818 if(check_port(mesh) == 0) {
819 meshlink_errno = MESHLINK_ENETWORK;
823 /* Create a node for ourself */
825 mesh->self = new_node();
826 mesh->self->name = xstrdup(mesh->name);
827 mesh->self->devclass = mesh->devclass;
828 mesh->self->ecdsa = ecdsa_set_public_key(ecdsa_get_public_key(mesh->private_key));
830 // Write the main config file
832 packmsg_output_t out = {buf, sizeof(buf)};
834 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
835 packmsg_add_str(&out, mesh->name);
836 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->private_key), 96);
837 packmsg_add_bin(&out, ecdsa_get_private_key(mesh->invitation_key), 96);
838 packmsg_add_uint16(&out, atoi(mesh->myport));
840 config_t config = {buf, packmsg_output_size(&out, buf)};
842 if(!main_config_write(mesh, &config)) {
846 // Write our own host config file
848 out.len = sizeof(buf);
849 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
850 packmsg_add_str(&out, mesh->name);
851 packmsg_add_int32(&out, mesh->devclass);
852 packmsg_add_bool(&out, false);
853 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
854 packmsg_add_str(&out, ""); // TODO: copy existing canonical address, in case it was added before meshlink_join().
855 packmsg_add_array(&out, 0);
857 config.len = packmsg_output_size(&out, buf);
859 if(!config_write(mesh, mesh->name, &config)) {
866 static bool meshlink_read_config(meshlink_handle_t *mesh) {
867 // Open the configuration file and lock it
868 if(!main_config_lock(mesh)) {
869 logger(NULL, MESHLINK_ERROR, "Cannot lock main config file\n");
870 meshlink_errno = MESHLINK_ESTORAGE;
876 if(!main_config_read(mesh, &config)) {
877 logger(NULL, MESHLINK_ERROR, "Could not read main configuration file!");
881 packmsg_input_t in = {config.buf, config.len};
882 const void *private_key;
883 const void *invitation_key;
885 uint32_t version = packmsg_get_uint32(&in);
886 char *name = packmsg_get_str_dup(&in);
887 uint32_t private_key_len = packmsg_get_bin_raw(&in, &private_key);
888 uint32_t invitation_key_len = packmsg_get_bin_raw(&in, &invitation_key);
889 uint16_t myport = packmsg_get_uint16(&in);
891 if(!packmsg_done(&in) || version != MESHLINK_CONFIG_VERSION || private_key_len != 96 || invitation_key_len != 96) {
892 logger(NULL, MESHLINK_ERROR, "Error parsing main configuration file!");
894 config_free(&config);
901 if(mesh->name && strcmp(mesh->name, name)) {
902 logger(NULL, MESHLINK_ERROR, "Configuration is for a different name (%s)!", name);
903 meshlink_errno = MESHLINK_ESTORAGE;
905 config_free(&config);
913 xasprintf(&mesh->myport, "%u", myport);
914 mesh->private_key = ecdsa_set_private_key(private_key);
915 mesh->invitation_key = ecdsa_set_private_key(invitation_key);
916 config_free(&config);
918 /* Create a node for ourself and read our host configuration file */
920 mesh->self = new_node();
921 mesh->self->name = xstrdup(name);
922 mesh->self->devclass = mesh->devclass;
924 if(!node_read_public_key(mesh, mesh->self)) {
925 logger(NULL, MESHLINK_ERROR, "Could not read our host configuration file!");
926 free_node(mesh->self);
935 static meshlink_handle_t *meshlink_open_internal(const char *confbase, const char *name, const char *appname, dev_class_t devclass, const void *key, size_t keylen) {
936 // Validate arguments provided by the application
937 bool usingname = false;
939 if(!appname || !*appname) {
940 logger(NULL, MESHLINK_ERROR, "No appname given!\n");
941 meshlink_errno = MESHLINK_EINVAL;
945 if(strchr(appname, ' ')) {
946 logger(NULL, MESHLINK_ERROR, "Invalid appname given!\n");
947 meshlink_errno = MESHLINK_EINVAL;
952 if(!check_id(name)) {
953 logger(NULL, MESHLINK_ERROR, "Invalid name given!\n");
954 meshlink_errno = MESHLINK_EINVAL;
961 if((int)devclass < 0 || devclass > _DEV_CLASS_MAX) {
962 logger(NULL, MESHLINK_ERROR, "Invalid devclass given!\n");
963 meshlink_errno = MESHLINK_EINVAL;
967 meshlink_handle_t *mesh = xzalloc(sizeof(meshlink_handle_t));
970 mesh->confbase = xstrdup(confbase);
973 mesh->appname = xstrdup(appname);
974 mesh->devclass = devclass;
975 mesh->discovery = true;
976 mesh->invitation_timeout = 604800; // 1 week
979 mesh->name = xstrdup(name);
984 mesh->config_key = xmalloc(CHACHA_POLY1305_KEYLEN);
986 if(!prf(key, keylen, "MeshLink configuration key", 26, mesh->config_key, CHACHA_POLY1305_KEYLEN)) {
987 logger(NULL, MESHLINK_ERROR, "Error creating configuration key!\n");
988 meshlink_errno = MESHLINK_EINTERNAL;
994 pthread_mutexattr_t attr;
995 pthread_mutexattr_init(&attr);
996 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
997 pthread_mutex_init(&(mesh->mesh_mutex), &attr);
999 mesh->threadstarted = false;
1000 event_loop_init(&mesh->loop);
1001 mesh->loop.data = mesh;
1003 meshlink_queue_init(&mesh->outpacketqueue);
1005 // If no configuration exists yet, create it.
1007 if(!main_config_exists(mesh)) {
1008 if(!meshlink_setup(mesh)) {
1009 logger(NULL, MESHLINK_ERROR, "Cannot create initial configuration\n");
1010 meshlink_close(mesh);
1014 if(!meshlink_read_config(mesh)) {
1015 logger(NULL, MESHLINK_ERROR, "Cannot read main configuration\n");
1016 meshlink_close(mesh);
1022 struct WSAData wsa_state;
1023 WSAStartup(MAKEWORD(2, 2), &wsa_state);
1026 // Setup up everything
1027 // TODO: we should not open listening sockets yet
1029 if(!setup_network(mesh)) {
1030 meshlink_close(mesh);
1031 meshlink_errno = MESHLINK_ENETWORK;
1035 add_local_addresses(mesh);
1036 node_write_config(mesh, mesh->self);
1038 idle_set(&mesh->loop, idle, mesh);
1040 logger(NULL, MESHLINK_DEBUG, "meshlink_open returning\n");
1044 meshlink_handle_t *meshlink_open(const char *confbase, const char *name, const char *appname, dev_class_t devclass) {
1045 if(!confbase || !*confbase) {
1046 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1047 meshlink_errno = MESHLINK_EINVAL;
1051 return meshlink_open_internal(confbase, name, appname, devclass, NULL, 0);
1054 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) {
1055 if(!confbase || !*confbase) {
1056 logger(NULL, MESHLINK_ERROR, "No confbase given!\n");
1057 meshlink_errno = MESHLINK_EINVAL;
1061 if(!key || !keylen) {
1062 logger(NULL, MESHLINK_ERROR, "No key given!\n");
1063 meshlink_errno = MESHLINK_EINVAL;
1067 return meshlink_open_internal(confbase, name, appname, devclass, key, keylen);
1070 meshlink_handle_t *meshlink_open_ephemeral(const char *name, const char *appname, dev_class_t devclass) {
1071 if(!name || !*name) {
1072 logger(NULL, MESHLINK_ERROR, "No name given!\n");
1073 meshlink_errno = MESHLINK_EINVAL;
1077 return meshlink_open_internal(NULL, name, appname, devclass, NULL, 0);
1081 static void *meshlink_main_loop(void *arg) {
1082 meshlink_handle_t *mesh = arg;
1084 pthread_mutex_lock(&(mesh->mesh_mutex));
1086 logger(mesh, MESHLINK_DEBUG, "Starting main_loop...\n");
1088 logger(mesh, MESHLINK_DEBUG, "main_loop returned.\n");
1090 pthread_mutex_unlock(&(mesh->mesh_mutex));
1094 bool meshlink_start(meshlink_handle_t *mesh) {
1096 assert(mesh->private_key);
1099 meshlink_errno = MESHLINK_EINVAL;
1103 logger(mesh, MESHLINK_DEBUG, "meshlink_start called\n");
1105 pthread_mutex_lock(&(mesh->mesh_mutex));
1107 if(mesh->threadstarted) {
1108 logger(mesh, MESHLINK_DEBUG, "thread was already running\n");
1109 pthread_mutex_unlock(&(mesh->mesh_mutex));
1113 if(mesh->listen_socket[0].tcp.fd < 0) {
1114 logger(mesh, MESHLINK_ERROR, "Listening socket not open\n");
1115 meshlink_errno = MESHLINK_ENETWORK;
1119 mesh->thedatalen = 0;
1121 // TODO: open listening sockets first
1123 //Check that a valid name is set
1125 logger(mesh, MESHLINK_DEBUG, "No name given!\n");
1126 meshlink_errno = MESHLINK_EINVAL;
1127 pthread_mutex_unlock(&(mesh->mesh_mutex));
1131 init_outgoings(mesh);
1133 // Start the main thread
1135 event_loop_start(&mesh->loop);
1137 if(pthread_create(&mesh->thread, NULL, meshlink_main_loop, mesh) != 0) {
1138 logger(mesh, MESHLINK_DEBUG, "Could not start thread: %s\n", strerror(errno));
1139 memset(&mesh->thread, 0, sizeof(mesh)->thread);
1140 meshlink_errno = MESHLINK_EINTERNAL;
1141 event_loop_stop(&mesh->loop);
1142 pthread_mutex_unlock(&(mesh->mesh_mutex));
1146 mesh->threadstarted = true;
1150 if(mesh->discovery) {
1151 discovery_start(mesh);
1156 assert(mesh->self->ecdsa);
1157 assert(!memcmp((uint8_t *)mesh->self->ecdsa + 64, (uint8_t *)mesh->private_key + 64, 32));
1160 pthread_mutex_unlock(&(mesh->mesh_mutex));
1164 void meshlink_stop(meshlink_handle_t *mesh) {
1166 meshlink_errno = MESHLINK_EINVAL;
1170 pthread_mutex_lock(&(mesh->mesh_mutex));
1171 logger(mesh, MESHLINK_DEBUG, "meshlink_stop called\n");
1176 if(mesh->discovery) {
1177 discovery_stop(mesh);
1182 // Shut down the main thread
1183 event_loop_stop(&mesh->loop);
1185 // Send ourselves a UDP packet to kick the event loop
1186 for(int i = 0; i < mesh->listen_sockets; i++) {
1188 socklen_t salen = sizeof(sa.sa);
1190 if(getsockname(mesh->listen_socket[i].udp.fd, &sa.sa, &salen) == -1) {
1191 logger(mesh, MESHLINK_ERROR, "System call `%s' failed: %s", "getsockname", sockstrerror(sockerrno));
1195 if(sendto(mesh->listen_socket[i].udp.fd, "", 1, MSG_NOSIGNAL, &sa.sa, salen) == -1) {
1196 logger(mesh, MESHLINK_ERROR, "Could not send a UDP packet to ourself: %s", sockstrerror(sockerrno));
1200 if(mesh->threadstarted) {
1201 // Wait for the main thread to finish
1202 pthread_mutex_unlock(&(mesh->mesh_mutex));
1203 pthread_join(mesh->thread, NULL);
1204 pthread_mutex_lock(&(mesh->mesh_mutex));
1206 mesh->threadstarted = false;
1209 // Close all metaconnections
1210 if(mesh->connections) {
1211 for(list_node_t *node = mesh->connections->head, *next; node; node = next) {
1213 connection_t *c = node->data;
1215 terminate_connection(mesh, c, false);
1219 exit_outgoings(mesh);
1221 pthread_mutex_unlock(&(mesh->mesh_mutex));
1224 void meshlink_close(meshlink_handle_t *mesh) {
1225 if(!mesh || !mesh->confbase) {
1226 meshlink_errno = MESHLINK_EINVAL;
1230 // stop can be called even if mesh has not been started
1231 meshlink_stop(mesh);
1233 // lock is not released after this
1234 pthread_mutex_lock(&(mesh->mesh_mutex));
1236 // Close and free all resources used.
1238 close_network_connections(mesh);
1240 logger(mesh, MESHLINK_INFO, "Terminating");
1242 event_loop_exit(&mesh->loop);
1246 if(mesh->confbase) {
1252 ecdsa_free(mesh->invitation_key);
1255 free(mesh->appname);
1256 free(mesh->confbase);
1257 pthread_mutex_destroy(&(mesh->mesh_mutex));
1259 main_config_unlock(mesh);
1261 memset(mesh, 0, sizeof(*mesh));
1266 bool meshlink_destroy(const char *confbase) {
1268 meshlink_errno = MESHLINK_EINVAL;
1272 return config_destroy(confbase);
1275 void meshlink_set_receive_cb(meshlink_handle_t *mesh, meshlink_receive_cb_t cb) {
1277 meshlink_errno = MESHLINK_EINVAL;
1281 pthread_mutex_lock(&(mesh->mesh_mutex));
1282 mesh->receive_cb = cb;
1283 pthread_mutex_unlock(&(mesh->mesh_mutex));
1286 void meshlink_set_node_status_cb(meshlink_handle_t *mesh, meshlink_node_status_cb_t cb) {
1288 meshlink_errno = MESHLINK_EINVAL;
1292 pthread_mutex_lock(&(mesh->mesh_mutex));
1293 mesh->node_status_cb = cb;
1294 pthread_mutex_unlock(&(mesh->mesh_mutex));
1297 void meshlink_set_node_duplicate_cb(meshlink_handle_t *mesh, meshlink_node_duplicate_cb_t cb) {
1299 meshlink_errno = MESHLINK_EINVAL;
1303 pthread_mutex_lock(&(mesh->mesh_mutex));
1304 mesh->node_duplicate_cb = cb;
1305 pthread_mutex_unlock(&(mesh->mesh_mutex));
1308 void meshlink_set_log_cb(meshlink_handle_t *mesh, meshlink_log_level_t level, meshlink_log_cb_t cb) {
1310 pthread_mutex_lock(&(mesh->mesh_mutex));
1312 mesh->log_level = cb ? level : 0;
1313 pthread_mutex_unlock(&(mesh->mesh_mutex));
1316 global_log_level = cb ? level : 0;
1320 bool meshlink_send(meshlink_handle_t *mesh, meshlink_node_t *destination, const void *data, size_t len) {
1321 meshlink_packethdr_t *hdr;
1323 // Validate arguments
1324 if(!mesh || !destination || len >= MAXSIZE - sizeof(*hdr)) {
1325 meshlink_errno = MESHLINK_EINVAL;
1334 meshlink_errno = MESHLINK_EINVAL;
1338 // Prepare the packet
1339 vpn_packet_t *packet = malloc(sizeof(*packet));
1342 meshlink_errno = MESHLINK_ENOMEM;
1346 packet->probe = false;
1347 packet->tcp = false;
1348 packet->len = len + sizeof(*hdr);
1350 hdr = (meshlink_packethdr_t *)packet->data;
1351 memset(hdr, 0, sizeof(*hdr));
1352 // leave the last byte as 0 to make sure strings are always
1353 // null-terminated if they are longer than the buffer
1354 strncpy((char *)hdr->destination, destination->name, (sizeof(hdr)->destination) - 1);
1355 strncpy((char *)hdr->source, mesh->self->name, (sizeof(hdr)->source) - 1);
1357 memcpy(packet->data + sizeof(*hdr), data, len);
1360 if(!meshlink_queue_push(&mesh->outpacketqueue, packet)) {
1362 meshlink_errno = MESHLINK_ENOMEM;
1366 // Notify event loop
1367 signal_trigger(&(mesh->loop), &(mesh->datafromapp));
1372 void meshlink_send_from_queue(event_loop_t *loop, meshlink_handle_t *mesh) {
1374 vpn_packet_t *packet = meshlink_queue_pop(&mesh->outpacketqueue);
1380 mesh->self->in_packets++;
1381 mesh->self->in_bytes += packet->len;
1382 route(mesh, mesh->self, packet);
1385 ssize_t meshlink_get_pmtu(meshlink_handle_t *mesh, meshlink_node_t *destination) {
1386 if(!mesh || !destination) {
1387 meshlink_errno = MESHLINK_EINVAL;
1391 pthread_mutex_lock(&(mesh->mesh_mutex));
1393 node_t *n = (node_t *)destination;
1395 if(!n->status.reachable) {
1396 pthread_mutex_unlock(&(mesh->mesh_mutex));
1399 } else if(n->mtuprobes > 30 && n->minmtu) {
1400 pthread_mutex_unlock(&(mesh->mesh_mutex));
1403 pthread_mutex_unlock(&(mesh->mesh_mutex));
1408 char *meshlink_get_fingerprint(meshlink_handle_t *mesh, meshlink_node_t *node) {
1409 if(!mesh || !node) {
1410 meshlink_errno = MESHLINK_EINVAL;
1414 pthread_mutex_lock(&(mesh->mesh_mutex));
1416 node_t *n = (node_t *)node;
1418 if(!node_read_public_key(mesh, n) || !n->ecdsa) {
1419 meshlink_errno = MESHLINK_EINTERNAL;
1420 pthread_mutex_unlock(&(mesh->mesh_mutex));
1424 char *fingerprint = ecdsa_get_base64_public_key(n->ecdsa);
1427 meshlink_errno = MESHLINK_EINTERNAL;
1430 pthread_mutex_unlock(&(mesh->mesh_mutex));
1434 meshlink_node_t *meshlink_get_self(meshlink_handle_t *mesh) {
1436 meshlink_errno = MESHLINK_EINVAL;
1440 return (meshlink_node_t *)mesh->self;
1443 meshlink_node_t *meshlink_get_node(meshlink_handle_t *mesh, const char *name) {
1444 if(!mesh || !name) {
1445 meshlink_errno = MESHLINK_EINVAL;
1449 meshlink_node_t *node = NULL;
1451 pthread_mutex_lock(&(mesh->mesh_mutex));
1452 node = (meshlink_node_t *)lookup_node(mesh, (char *)name); // TODO: make lookup_node() use const
1453 pthread_mutex_unlock(&(mesh->mesh_mutex));
1457 meshlink_node_t **meshlink_get_all_nodes(meshlink_handle_t *mesh, meshlink_node_t **nodes, size_t *nmemb) {
1458 if(!mesh || !nmemb || (*nmemb && !nodes)) {
1459 meshlink_errno = MESHLINK_EINVAL;
1463 meshlink_node_t **result;
1466 pthread_mutex_lock(&(mesh->mesh_mutex));
1468 *nmemb = mesh->nodes->count;
1469 result = realloc(nodes, *nmemb * sizeof(*nodes));
1472 meshlink_node_t **p = result;
1474 for splay_each(node_t, n, mesh->nodes) {
1475 *p++ = (meshlink_node_t *)n;
1480 meshlink_errno = MESHLINK_ENOMEM;
1483 pthread_mutex_unlock(&(mesh->mesh_mutex));
1488 bool meshlink_sign(meshlink_handle_t *mesh, const void *data, size_t len, void *signature, size_t *siglen) {
1489 if(!mesh || !data || !len || !signature || !siglen) {
1490 meshlink_errno = MESHLINK_EINVAL;
1494 if(*siglen < MESHLINK_SIGLEN) {
1495 meshlink_errno = MESHLINK_EINVAL;
1499 pthread_mutex_lock(&(mesh->mesh_mutex));
1501 if(!ecdsa_sign(mesh->private_key, data, len, signature)) {
1502 meshlink_errno = MESHLINK_EINTERNAL;
1503 pthread_mutex_unlock(&(mesh->mesh_mutex));
1507 *siglen = MESHLINK_SIGLEN;
1508 pthread_mutex_unlock(&(mesh->mesh_mutex));
1512 bool meshlink_verify(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len, const void *signature, size_t siglen) {
1513 if(!mesh || !data || !len || !signature) {
1514 meshlink_errno = MESHLINK_EINVAL;
1518 if(siglen != MESHLINK_SIGLEN) {
1519 meshlink_errno = MESHLINK_EINVAL;
1523 pthread_mutex_lock(&(mesh->mesh_mutex));
1527 struct node_t *n = (struct node_t *)source;
1529 if(!node_read_public_key(mesh, n)) {
1530 meshlink_errno = MESHLINK_EINTERNAL;
1533 rval = ecdsa_verify(((struct node_t *)source)->ecdsa, data, len, signature);
1536 pthread_mutex_unlock(&(mesh->mesh_mutex));
1540 static bool refresh_invitation_key(meshlink_handle_t *mesh) {
1541 pthread_mutex_lock(&(mesh->mesh_mutex));
1543 size_t count = invitation_purge_old(mesh, time(NULL) - mesh->invitation_timeout);
1546 // TODO: Update invitation key if necessary?
1549 pthread_mutex_unlock(&(mesh->mesh_mutex));
1551 return mesh->invitation_key;
1554 bool meshlink_set_canonical_address(meshlink_handle_t *mesh, meshlink_node_t *node, const char *address, const char *port) {
1555 if(!mesh || !node || !address) {
1556 meshlink_errno = MESHLINK_EINVAL;
1560 if(!is_valid_hostname(address)) {
1561 logger(mesh, MESHLINK_DEBUG, "Invalid character in address: %s\n", address);
1562 meshlink_errno = MESHLINK_EINVAL;
1566 if(port && !is_valid_port(port)) {
1567 logger(mesh, MESHLINK_DEBUG, "Invalid character in port: %s\n", address);
1568 meshlink_errno = MESHLINK_EINVAL;
1572 char *canonical_address;
1575 xasprintf(&canonical_address, "%s %s", address, port);
1577 canonical_address = xstrdup(address);
1580 pthread_mutex_lock(&(mesh->mesh_mutex));
1582 node_t *n = (node_t *)node;
1583 free(n->canonical_address);
1584 n->canonical_address = canonical_address;
1585 n->status.dirty = true;
1587 pthread_mutex_unlock(&(mesh->mesh_mutex));
1592 bool meshlink_add_address(meshlink_handle_t *mesh, const char *address) {
1593 return meshlink_set_canonical_address(mesh, (meshlink_node_t *)mesh->self, address, NULL);
1596 bool meshlink_add_external_address(meshlink_handle_t *mesh) {
1598 meshlink_errno = MESHLINK_EINVAL;
1602 char *address = meshlink_get_external_address(mesh);
1608 bool rval = meshlink_add_address(mesh, address);
1614 int meshlink_get_port(meshlink_handle_t *mesh) {
1616 meshlink_errno = MESHLINK_EINVAL;
1621 meshlink_errno = MESHLINK_EINTERNAL;
1625 return atoi(mesh->myport);
1628 bool meshlink_set_port(meshlink_handle_t *mesh, int port) {
1629 if(!mesh || port < 0 || port >= 65536 || mesh->threadstarted) {
1630 meshlink_errno = MESHLINK_EINVAL;
1634 if(mesh->myport && port == atoi(mesh->myport)) {
1638 if(!try_bind(port)) {
1639 meshlink_errno = MESHLINK_ENETWORK;
1645 pthread_mutex_lock(&(mesh->mesh_mutex));
1647 if(mesh->threadstarted) {
1648 meshlink_errno = MESHLINK_EINVAL;
1652 close_network_connections(mesh);
1654 // TODO: write meshlink.conf again
1656 if(!setup_network(mesh)) {
1657 meshlink_errno = MESHLINK_ENETWORK;
1663 pthread_mutex_unlock(&(mesh->mesh_mutex));
1668 void meshlink_set_invitation_timeout(meshlink_handle_t *mesh, int timeout) {
1669 mesh->invitation_timeout = timeout;
1672 char *meshlink_invite_ex(meshlink_handle_t *mesh, const char *name, uint32_t flags) {
1674 meshlink_errno = MESHLINK_EINVAL;
1678 pthread_mutex_lock(&(mesh->mesh_mutex));
1680 // Check validity of the new node's name
1681 if(!check_id(name)) {
1682 logger(mesh, MESHLINK_DEBUG, "Invalid name for node.\n");
1683 meshlink_errno = MESHLINK_EINVAL;
1684 pthread_mutex_unlock(&(mesh->mesh_mutex));
1688 // Ensure no host configuration file with that name exists
1689 if(config_exists(mesh, name)) {
1690 logger(mesh, MESHLINK_DEBUG, "A host config file for %s already exists!\n", name);
1691 meshlink_errno = MESHLINK_EEXIST;
1692 pthread_mutex_unlock(&(mesh->mesh_mutex));
1696 // Ensure no other nodes know about this name
1697 if(meshlink_get_node(mesh, name)) {
1698 logger(mesh, MESHLINK_DEBUG, "A node with name %s is already known!\n", name);
1699 meshlink_errno = MESHLINK_EEXIST;
1700 pthread_mutex_unlock(&(mesh->mesh_mutex));
1704 // Get the local address
1705 char *address = get_my_hostname(mesh, flags);
1708 logger(mesh, MESHLINK_DEBUG, "No Address known for ourselves!\n");
1709 meshlink_errno = MESHLINK_ERESOLV;
1710 pthread_mutex_unlock(&(mesh->mesh_mutex));
1714 if(!refresh_invitation_key(mesh)) {
1715 meshlink_errno = MESHLINK_EINTERNAL;
1716 pthread_mutex_unlock(&(mesh->mesh_mutex));
1722 // Create a hash of the key.
1723 char *fingerprint = ecdsa_get_base64_public_key(mesh->invitation_key);
1724 sha512(fingerprint, strlen(fingerprint), hash);
1725 b64encode_urlsafe(hash, hash, 18);
1727 // Create a random cookie for this invitation.
1729 randomize(cookie, 18);
1731 // Create a filename that doesn't reveal the cookie itself
1732 char buf[18 + strlen(fingerprint)];
1733 char cookiehash[64];
1734 memcpy(buf, cookie, 18);
1735 memcpy(buf + 18, fingerprint, sizeof(buf) - 18);
1736 sha512(buf, sizeof(buf), cookiehash);
1737 b64encode_urlsafe(cookiehash, cookiehash, 18);
1739 b64encode_urlsafe(cookie, cookie, 18);
1743 /* Construct the invitation file */
1744 uint8_t outbuf[4096];
1745 packmsg_output_t inv = {outbuf, sizeof(outbuf)};
1747 packmsg_add_uint32(&inv, MESHLINK_INVITATION_VERSION);
1748 packmsg_add_str(&inv, name);
1749 packmsg_add_int32(&inv, DEV_CLASS_UNKNOWN); /* TODO: allow this to be set by inviter? */
1751 /* TODO: Add several host config files to bootstrap connections */
1752 config_t configs[5] = {NULL};
1755 if(config_read(mesh, mesh->self->name, &configs[count])) {
1759 /* Append host config files to the invitation file */
1760 packmsg_add_array(&inv, count);
1762 for(int i = 0; i < count; i++) {
1763 packmsg_add_bin(&inv, configs[i].buf, configs[i].len);
1764 config_free(&configs[i]);
1767 config_t config = {outbuf, packmsg_output_size(&inv, outbuf)};
1769 if(!invitation_write(mesh, cookiehash, &config)) {
1770 logger(mesh, MESHLINK_DEBUG, "Could not create invitation file %s: %s\n", cookiehash, strerror(errno));
1771 meshlink_errno = MESHLINK_ESTORAGE;
1772 pthread_mutex_unlock(&(mesh->mesh_mutex));
1776 // Create an URL from the local address, key hash and cookie
1778 xasprintf(&url, "%s/%s%s", address, hash, cookie);
1781 pthread_mutex_unlock(&(mesh->mesh_mutex));
1785 char *meshlink_invite(meshlink_handle_t *mesh, const char *name) {
1786 return meshlink_invite_ex(mesh, name, 0);
1789 bool meshlink_join(meshlink_handle_t *mesh, const char *invitation) {
1790 if(!mesh || !invitation) {
1791 meshlink_errno = MESHLINK_EINVAL;
1795 pthread_mutex_lock(&(mesh->mesh_mutex));
1797 //Before doing meshlink_join make sure we are not connected to another mesh
1798 if(mesh->threadstarted) {
1799 logger(mesh, MESHLINK_DEBUG, "Already connected to a mesh\n");
1800 meshlink_errno = MESHLINK_EINVAL;
1801 pthread_mutex_unlock(&(mesh->mesh_mutex));
1805 //TODO: think of a better name for this variable, or of a different way to tokenize the invitation URL.
1806 char copy[strlen(invitation) + 1];
1807 strcpy(copy, invitation);
1809 // Split the invitation URL into a list of hostname/port tuples, a key hash and a cookie.
1811 char *slash = strchr(copy, '/');
1819 if(strlen(slash) != 48) {
1823 char *address = copy;
1826 if(!b64decode(slash, mesh->hash, 18) || !b64decode(slash + 24, mesh->cookie, 18)) {
1830 // Generate a throw-away key for the invitation.
1831 ecdsa_t *key = ecdsa_generate();
1834 meshlink_errno = MESHLINK_EINTERNAL;
1835 pthread_mutex_unlock(&(mesh->mesh_mutex));
1839 char *b64key = ecdsa_get_base64_public_key(key);
1843 while(address && *address) {
1844 // We allow commas in the address part to support multiple addresses in one invitation URL.
1845 comma = strchr(address, ',');
1851 // Split of the port
1852 port = strrchr(address, ':');
1860 // IPv6 address are enclosed in brackets, per RFC 3986
1861 if(*address == '[') {
1863 char *bracket = strchr(address, ']');
1876 // Connect to the meshlink daemon mentioned in the URL.
1877 struct addrinfo *ai = str2addrinfo(address, port, SOCK_STREAM);
1880 for(struct addrinfo *aip = ai; aip; aip = aip->ai_next) {
1881 mesh->sock = socket(aip->ai_family, aip->ai_socktype, aip->ai_protocol);
1883 if(mesh->sock == -1) {
1884 logger(mesh, MESHLINK_DEBUG, "Could not open socket: %s\n", strerror(errno));
1885 meshlink_errno = MESHLINK_ENETWORK;
1889 set_timeout(mesh->sock, 5000);
1891 if(connect(mesh->sock, aip->ai_addr, aip->ai_addrlen)) {
1892 logger(mesh, MESHLINK_DEBUG, "Could not connect to %s port %s: %s\n", address, port, strerror(errno));
1893 meshlink_errno = MESHLINK_ENETWORK;
1894 closesocket(mesh->sock);
1902 meshlink_errno = MESHLINK_ERESOLV;
1905 if(mesh->sock != -1 || !comma) {
1912 if(mesh->sock == -1) {
1913 pthread_mutex_unlock(&mesh->mesh_mutex);
1917 logger(mesh, MESHLINK_DEBUG, "Connected to %s port %s...\n", address, port);
1919 // Tell him we have an invitation, and give him our throw-away key.
1923 if(!sendline(mesh->sock, "0 ?%s %d.%d %s", b64key, PROT_MAJOR, 1, mesh->appname)) {
1924 logger(mesh, MESHLINK_DEBUG, "Error sending request to %s port %s: %s\n", address, port, strerror(errno));
1925 closesocket(mesh->sock);
1926 meshlink_errno = MESHLINK_ENETWORK;
1927 pthread_mutex_unlock(&(mesh->mesh_mutex));
1933 char hisname[4096] = "";
1934 int code, hismajor, hisminor = 0;
1936 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) {
1937 logger(mesh, MESHLINK_DEBUG, "Cannot read greeting from peer\n");
1938 closesocket(mesh->sock);
1939 meshlink_errno = MESHLINK_ENETWORK;
1940 pthread_mutex_unlock(&(mesh->mesh_mutex));
1944 // Check if the hash of the key he gave us matches the hash in the URL.
1945 char *fingerprint = mesh->line + 2;
1948 if(sha512(fingerprint, strlen(fingerprint), hishash)) {
1949 logger(mesh, MESHLINK_DEBUG, "Could not create hash\n%s\n", mesh->line + 2);
1950 meshlink_errno = MESHLINK_EINTERNAL;
1951 pthread_mutex_unlock(&(mesh->mesh_mutex));
1955 if(memcmp(hishash, mesh->hash, 18)) {
1956 logger(mesh, MESHLINK_DEBUG, "Peer has an invalid key!\n%s\n", mesh->line + 2);
1957 meshlink_errno = MESHLINK_EPEER;
1958 pthread_mutex_unlock(&(mesh->mesh_mutex));
1963 ecdsa_t *hiskey = ecdsa_set_base64_public_key(fingerprint);
1966 meshlink_errno = MESHLINK_EINTERNAL;
1967 pthread_mutex_unlock(&(mesh->mesh_mutex));
1971 // Start an SPTPS session
1972 if(!sptps_start(&mesh->sptps, mesh, true, false, key, hiskey, meshlink_invitation_label, sizeof(meshlink_invitation_label), invitation_send, invitation_receive)) {
1973 meshlink_errno = MESHLINK_EINTERNAL;
1974 pthread_mutex_unlock(&(mesh->mesh_mutex));
1978 // Feed rest of input buffer to SPTPS
1979 if(!sptps_receive_data(&mesh->sptps, mesh->buffer, mesh->blen)) {
1980 meshlink_errno = MESHLINK_EPEER;
1981 pthread_mutex_unlock(&(mesh->mesh_mutex));
1987 while((len = recv(mesh->sock, mesh->line, sizeof(mesh)->line, 0))) {
1989 if(errno == EINTR) {
1993 logger(mesh, MESHLINK_DEBUG, "Error reading data from %s port %s: %s\n", address, port, strerror(errno));
1994 meshlink_errno = MESHLINK_ENETWORK;
1995 pthread_mutex_unlock(&(mesh->mesh_mutex));
1999 if(!sptps_receive_data(&mesh->sptps, mesh->line, len)) {
2000 meshlink_errno = MESHLINK_EPEER;
2001 pthread_mutex_unlock(&(mesh->mesh_mutex));
2006 sptps_stop(&mesh->sptps);
2009 closesocket(mesh->sock);
2011 if(!mesh->success) {
2012 logger(mesh, MESHLINK_DEBUG, "Connection closed by peer, invitation cancelled.\n");
2013 meshlink_errno = MESHLINK_EPEER;
2014 pthread_mutex_unlock(&(mesh->mesh_mutex));
2018 pthread_mutex_unlock(&(mesh->mesh_mutex));
2022 logger(mesh, MESHLINK_DEBUG, "Invalid invitation URL\n");
2023 meshlink_errno = MESHLINK_EINVAL;
2024 pthread_mutex_unlock(&(mesh->mesh_mutex));
2028 char *meshlink_export(meshlink_handle_t *mesh) {
2030 meshlink_errno = MESHLINK_EINVAL;
2034 // Create a config file on the fly.
2037 packmsg_output_t out = {buf, sizeof(buf)};
2038 packmsg_add_uint32(&out, MESHLINK_CONFIG_VERSION);
2039 packmsg_add_str(&out, mesh->name);
2041 pthread_mutex_lock(&(mesh->mesh_mutex));
2043 packmsg_add_int32(&out, mesh->self->devclass);
2044 packmsg_add_bool(&out, mesh->self->status.blacklisted);
2045 packmsg_add_bin(&out, ecdsa_get_public_key(mesh->private_key), 32);
2046 packmsg_add_str(&out, mesh->self->canonical_address ? mesh->self->canonical_address : "");
2050 for(uint32_t i = 0; i < 5; i++) {
2051 if(mesh->self->recent[i].sa.sa_family) {
2058 packmsg_add_array(&out, count);
2060 for(uint32_t i = 0; i < count; i++) {
2061 packmsg_add_sockaddr(&out, &mesh->self->recent[i]);
2064 pthread_mutex_unlock(&(mesh->mesh_mutex));
2066 if(!packmsg_output_ok(&out)) {
2067 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2068 meshlink_errno = MESHLINK_EINTERNAL;
2072 // Prepare a base64-encoded packmsg array containing our config file
2074 uint32_t len = packmsg_output_size(&out, buf);
2075 uint32_t len2 = ((len + 4) * 4) / 3 + 4;
2076 uint8_t *buf2 = xmalloc(len2);
2077 packmsg_output_t out2 = {buf2, len2};
2078 packmsg_add_array(&out2, 1);
2079 packmsg_add_bin(&out2, buf, packmsg_output_size(&out, buf));
2081 if(!packmsg_output_ok(&out2)) {
2082 logger(mesh, MESHLINK_DEBUG, "Error creating export data\n");
2083 meshlink_errno = MESHLINK_EINTERNAL;
2088 b64encode_urlsafe(buf2, (char *)buf2, packmsg_output_size(&out2, buf2));
2090 return (char *)buf2;
2093 bool meshlink_import(meshlink_handle_t *mesh, const char *data) {
2094 if(!mesh || !data) {
2096 meshlink_errno = MESHLINK_EINVAL;
2100 size_t datalen = strlen(data);
2101 uint8_t *buf = xmalloc(datalen);
2102 int buflen = b64decode(data, buf, datalen);
2106 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2107 meshlink_errno = MESHLINK_EPEER;
2111 packmsg_input_t in = {buf, buflen};
2112 uint32_t count = packmsg_get_array(&in);
2116 logger(mesh, MESHLINK_DEBUG, "Invalid data\n");
2117 meshlink_errno = MESHLINK_EPEER;
2121 pthread_mutex_lock(&(mesh->mesh_mutex));
2125 uint32_t len = packmsg_get_bin_raw(&in, &data);
2131 packmsg_input_t in2 = {data, len};
2132 uint32_t version = packmsg_get_uint32(&in2);
2133 char *name = packmsg_get_str_dup(&in2);
2135 if(!packmsg_input_ok(&in2) || version != MESHLINK_CONFIG_VERSION || !check_id(name)) {
2137 packmsg_input_invalidate(&in2);
2141 if(!check_id(name)) {
2146 node_t *n = lookup_node(mesh, name);
2150 logger(mesh, MESHLINK_DEBUG, "Node %s already exists, not importing\n", name);
2156 n->devclass = packmsg_get_int32(&in2);
2157 n->status.blacklisted = packmsg_get_bool(&in2);
2159 uint32_t keylen = packmsg_get_bin_raw(&in2, &key);
2162 n->ecdsa = ecdsa_set_public_key(key);
2165 n->canonical_address = packmsg_get_str_dup(&in2);
2166 uint32_t count = packmsg_get_array(&in2);
2172 for(uint32_t i = 0; i < count; i++) {
2173 n->recent[i] = packmsg_get_sockaddr(&in2);
2176 if(!packmsg_done(&in2) || keylen != 32) {
2178 packmsg_input_invalidate(&in2);
2181 config_t config = {data, len};
2182 config_write(mesh, n->name, &config);
2187 pthread_mutex_unlock(&(mesh->mesh_mutex));
2189 if(!packmsg_done(&in)) {
2191 logger(mesh, MESHLINK_ERROR, "Invalid data\n");
2192 meshlink_errno = MESHLINK_EPEER;
2199 void meshlink_blacklist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2200 if(!mesh || !node) {
2201 meshlink_errno = MESHLINK_EINVAL;
2205 pthread_mutex_lock(&(mesh->mesh_mutex));
2209 n->status.blacklisted = true;
2210 n->status.dirty = true;
2211 logger(mesh, MESHLINK_DEBUG, "Blacklisted %s.\n", node->name);
2213 //Immediately terminate any connections we have with the blacklisted node
2214 for list_each(connection_t, c, mesh->connections) {
2216 terminate_connection(mesh, c, c->status.active);
2220 pthread_mutex_unlock(&(mesh->mesh_mutex));
2223 void meshlink_whitelist(meshlink_handle_t *mesh, meshlink_node_t *node) {
2224 if(!mesh || !node) {
2225 meshlink_errno = MESHLINK_EINVAL;
2229 pthread_mutex_lock(&(mesh->mesh_mutex));
2231 node_t *n = (node_t *)node;
2232 n->status.blacklisted = false;
2233 n->status.dirty = true;
2235 pthread_mutex_unlock(&(mesh->mesh_mutex));
2239 void meshlink_set_default_blacklist(meshlink_handle_t *mesh, bool blacklist) {
2240 mesh->default_blacklist = blacklist;
2243 /* Hint that a hostname may be found at an address
2244 * See header file for detailed comment.
2246 void meshlink_hint_address(meshlink_handle_t *mesh, meshlink_node_t *node, const struct sockaddr *addr) {
2247 if(!mesh || !node || !addr) {
2248 meshlink_errno = EINVAL;
2252 pthread_mutex_lock(&(mesh->mesh_mutex));
2254 node_t *n = (node_t *)node;
2255 memmove(n->recent + 1, n->recent, 4 * sizeof(*n->recent));
2256 memcpy(n->recent, addr, SALEN(*addr));
2257 n->status.dirty = true;
2259 pthread_mutex_unlock(&(mesh->mesh_mutex));
2260 // @TODO do we want to fire off a connection attempt right away?
2263 static bool channel_pre_accept(struct utcp *utcp, uint16_t port) {
2265 node_t *n = utcp->priv;
2266 meshlink_handle_t *mesh = n->mesh;
2267 return mesh->channel_accept_cb;
2270 static ssize_t channel_recv(struct utcp_connection *connection, const void *data, size_t len) {
2271 meshlink_channel_t *channel = connection->priv;
2277 node_t *n = channel->node;
2278 meshlink_handle_t *mesh = n->mesh;
2280 if(n->status.destroyed) {
2281 meshlink_channel_close(mesh, channel);
2282 } else if(channel->receive_cb) {
2283 channel->receive_cb(mesh, channel, data, len);
2289 static void channel_accept(struct utcp_connection *utcp_connection, uint16_t port) {
2290 node_t *n = utcp_connection->utcp->priv;
2296 meshlink_handle_t *mesh = n->mesh;
2298 if(!mesh->channel_accept_cb) {
2302 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2304 channel->c = utcp_connection;
2306 if(mesh->channel_accept_cb(mesh, channel, port, NULL, 0)) {
2307 utcp_accept(utcp_connection, channel_recv, channel);
2313 static ssize_t channel_send(struct utcp *utcp, const void *data, size_t len) {
2314 node_t *n = utcp->priv;
2316 if(n->status.destroyed) {
2320 meshlink_handle_t *mesh = n->mesh;
2321 return meshlink_send(mesh, (meshlink_node_t *)n, data, len) ? (ssize_t)len : -1;
2324 void meshlink_set_channel_receive_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_receive_cb_t cb) {
2325 if(!mesh || !channel) {
2326 meshlink_errno = MESHLINK_EINVAL;
2330 channel->receive_cb = cb;
2333 static void channel_receive(meshlink_handle_t *mesh, meshlink_node_t *source, const void *data, size_t len) {
2335 node_t *n = (node_t *)source;
2341 utcp_recv(n->utcp, data, len);
2344 static void channel_poll(struct utcp_connection *connection, size_t len) {
2345 meshlink_channel_t *channel = connection->priv;
2351 node_t *n = channel->node;
2352 meshlink_handle_t *mesh = n->mesh;
2354 if(channel->poll_cb) {
2355 channel->poll_cb(mesh, channel, len);
2359 void meshlink_set_channel_poll_cb(meshlink_handle_t *mesh, meshlink_channel_t *channel, meshlink_channel_poll_cb_t cb) {
2361 channel->poll_cb = cb;
2362 utcp_set_poll_cb(channel->c, cb ? channel_poll : NULL);
2365 void meshlink_set_channel_accept_cb(meshlink_handle_t *mesh, meshlink_channel_accept_cb_t cb) {
2367 meshlink_errno = MESHLINK_EINVAL;
2371 pthread_mutex_lock(&mesh->mesh_mutex);
2372 mesh->channel_accept_cb = cb;
2373 mesh->receive_cb = channel_receive;
2375 for splay_each(node_t, n, mesh->nodes) {
2376 if(!n->utcp && n != mesh->self) {
2377 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2381 pthread_mutex_unlock(&mesh->mesh_mutex);
2384 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) {
2386 abort(); // TODO: handle non-NULL data
2389 if(!mesh || !node) {
2390 meshlink_errno = MESHLINK_EINVAL;
2394 node_t *n = (node_t *)node;
2397 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2398 mesh->receive_cb = channel_receive;
2401 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2406 meshlink_channel_t *channel = xzalloc(sizeof(*channel));
2408 channel->receive_cb = cb;
2409 channel->c = utcp_connect_ex(n->utcp, port, channel_recv, channel, flags);
2412 meshlink_errno = errno == ENOMEM ? MESHLINK_ENOMEM : MESHLINK_EINTERNAL;
2420 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) {
2421 return meshlink_channel_open_ex(mesh, node, port, cb, data, len, MESHLINK_CHANNEL_TCP);
2424 void meshlink_channel_shutdown(meshlink_handle_t *mesh, meshlink_channel_t *channel, int direction) {
2425 if(!mesh || !channel) {
2426 meshlink_errno = MESHLINK_EINVAL;
2430 utcp_shutdown(channel->c, direction);
2433 void meshlink_channel_close(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2434 if(!mesh || !channel) {
2435 meshlink_errno = MESHLINK_EINVAL;
2439 utcp_close(channel->c);
2443 ssize_t meshlink_channel_send(meshlink_handle_t *mesh, meshlink_channel_t *channel, const void *data, size_t len) {
2444 if(!mesh || !channel) {
2445 meshlink_errno = MESHLINK_EINVAL;
2454 meshlink_errno = MESHLINK_EINVAL;
2458 // TODO: more finegrained locking.
2459 // Ideally we want to put the data into the UTCP connection's send buffer.
2460 // Then, preferrably only if there is room in the receiver window,
2461 // kick the meshlink thread to go send packets.
2463 pthread_mutex_lock(&mesh->mesh_mutex);
2464 ssize_t retval = utcp_send(channel->c, data, len);
2465 pthread_mutex_unlock(&mesh->mesh_mutex);
2468 meshlink_errno = MESHLINK_ENETWORK;
2474 uint32_t meshlink_channel_get_flags(meshlink_handle_t *mesh, meshlink_channel_t *channel) {
2475 if(!mesh || !channel) {
2476 meshlink_errno = MESHLINK_EINVAL;
2480 return channel->c->flags;
2483 void update_node_status(meshlink_handle_t *mesh, node_t *n) {
2484 if(n->status.reachable && mesh->channel_accept_cb && !n->utcp) {
2485 n->utcp = utcp_init(channel_accept, channel_pre_accept, channel_send, n);
2488 if(mesh->node_status_cb) {
2489 mesh->node_status_cb(mesh, (meshlink_node_t *)n, n->status.reachable);
2493 void handle_duplicate_node(meshlink_handle_t *mesh, node_t *n) {
2494 if(!mesh->node_duplicate_cb || n->status.duplicate) {
2498 n->status.duplicate = true;
2499 mesh->node_duplicate_cb(mesh, (meshlink_node_t *)n);
2502 void meshlink_enable_discovery(meshlink_handle_t *mesh, bool enable) {
2506 meshlink_errno = MESHLINK_EINVAL;
2510 pthread_mutex_lock(&mesh->mesh_mutex);
2512 if(mesh->discovery == enable) {
2516 if(mesh->threadstarted) {
2518 discovery_start(mesh);
2520 discovery_stop(mesh);
2524 mesh->discovery = enable;
2527 pthread_mutex_unlock(&mesh->mesh_mutex);
2531 meshlink_errno = MESHLINK_ENOTSUP;
2535 static void __attribute__((constructor)) meshlink_init(void) {
2538 randomize(&seed, sizeof(seed));
2542 static void __attribute__((destructor)) meshlink_exit(void) {
2546 /// Device class traits
2547 dev_class_traits_t dev_class_traits[_DEV_CLASS_MAX + 1] = {
2548 { .min_connects = 3, .max_connects = 10000, .edge_weight = 1 }, // DEV_CLASS_BACKBONE
2549 { .min_connects = 3, .max_connects = 100, .edge_weight = 3 }, // DEV_CLASS_STATIONARY
2550 { .min_connects = 3, .max_connects = 3, .edge_weight = 6 }, // DEV_CLASS_PORTABLE
2551 { .min_connects = 1, .max_connects = 1, .edge_weight = 9 }, // DEV_CLASS_UNKNOWN